Completed
Push — feature/jetpack-packages-2 ( a52b3c )
by
unknown
242:43 queued 236:19
created

class.jetpack.php (10 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
use Automattic\Jetpack\Constants;
4
use Automattic\Jetpack\Tracking\Manager as JetpackTracking;
5
6
/*
7
Options:
8
jetpack_options (array)
9
	An array of options.
10
	@see Jetpack_Options::get_option_names()
11
12
jetpack_register (string)
13
	Temporary verification secrets.
14
15
jetpack_activated (int)
16
	1: the plugin was activated normally
17
	2: the plugin was activated on this site because of a network-wide activation
18
	3: the plugin was auto-installed
19
	4: the plugin was manually disconnected (but is still installed)
20
21
jetpack_active_modules (array)
22
	Array of active module slugs.
23
24
jetpack_do_activate (bool)
25
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
26
*/
27
28
use \Automattic\Jetpack\Connection\Manager as Connection_Manager;
29
use \Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
30
31
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
32
require_once( dirname( __FILE__ ) . '/_inc/lib/tracks/client.php' );
33
34
class Jetpack {
35
	public $xmlrpc_server = null;
36
37
	private $xmlrpc_verification = null;
38
	private $rest_authentication_status = null;
39
40
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
41
42
	/**
43
	 * @var array The handles of styles that are concatenated into jetpack.css.
44
	 *
45
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
46
	 */
47
	public $concatenated_style_handles = array(
48
		'jetpack-carousel',
49
		'grunion.css',
50
		'the-neverending-homepage',
51
		'jetpack_likes',
52
		'jetpack_related-posts',
53
		'sharedaddy',
54
		'jetpack-slideshow',
55
		'presentations',
56
		'quiz',
57
		'jetpack-subscriptions',
58
		'jetpack-responsive-videos-style',
59
		'jetpack-social-menu',
60
		'tiled-gallery',
61
		'jetpack_display_posts_widget',
62
		'gravatar-profile-widget',
63
		'goodreads-widget',
64
		'jetpack_social_media_icons_widget',
65
		'jetpack-top-posts-widget',
66
		'jetpack_image_widget',
67
		'jetpack-my-community-widget',
68
		'jetpack-authors-widget',
69
		'wordads',
70
		'eu-cookie-law-style',
71
		'flickr-widget-style',
72
		'jetpack-search-widget',
73
		'jetpack-simple-payments-widget-style',
74
		'jetpack-widget-social-icons-styles',
75
	);
76
77
	/**
78
	 * Contains all assets that have had their URL rewritten to minified versions.
79
	 *
80
	 * @var array
81
	 */
82
	static $min_assets = array();
83
84
	public $plugins_to_deactivate = array(
85
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
86
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
87
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
88
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
89
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
90
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
91
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
92
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
93
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
94
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
95
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
96
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
97
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
98
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
99
	);
100
101
	static $capability_translations = array(
102
		'administrator' => 'manage_options',
103
		'editor'        => 'edit_others_posts',
104
		'author'        => 'publish_posts',
105
		'contributor'   => 'edit_posts',
106
		'subscriber'    => 'read',
107
	);
108
109
	/**
110
	 * Map of modules that have conflicts with plugins and should not be auto-activated
111
	 * if the plugins are active.  Used by filter_default_modules
112
	 *
113
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
114
	 * change `module-slug` and add this to your plugin:
115
	 *
116
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
117
	 * function my_jetpack_get_default_modules( $modules ) {
118
	 *     return array_diff( $modules, array( 'module-slug' ) );
119
	 * }
120
	 *
121
	 * @var array
122
	 */
123
	private $conflicting_plugins = array(
124
		'comments'          => array(
125
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
126
			'Disqus'                               => 'disqus-comment-system/disqus.php',
127
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
128
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
129
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
130
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
131
		),
132
		'comment-likes' => array(
133
			'Epoch'                                => 'epoch/plugincore.php',
134
		),
135
		'contact-form'      => array(
136
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
137
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
138
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
139
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
140
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
141
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
142
		),
143
		'minileven'         => array(
144
			'WPtouch'                              => 'wptouch/wptouch.php',
145
		),
146
		'latex'             => array(
147
			'LaTeX for WordPress'                  => 'latex/latex.php',
148
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
149
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
150
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
151
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
152
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
153
		),
154
		'protect'           => array(
155
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
156
			'Captcha'                              => 'captcha/captcha.php',
157
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
158
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
159
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
160
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
161
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
162
			'Security-protection'                  => 'security-protection/security-protection.php',
163
			'Login Security'                       => 'login-security/login-security.php',
164
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
165
			'Wordfence Security'                   => 'wordfence/wordfence.php',
166
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
167
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
168
		),
169
		'random-redirect'   => array(
170
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
171
		),
172
		'related-posts'     => array(
173
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
174
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
175
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
176
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
177
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
178
			'outbrain'                             => 'outbrain/outbrain.php',
179
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
180
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
181
		),
182
		'sharedaddy'        => array(
183
			'AddThis'                              => 'addthis/addthis_social_widget.php',
184
			'Add To Any'                           => 'add-to-any/add-to-any.php',
185
			'ShareThis'                            => 'share-this/sharethis.php',
186
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
187
		),
188
		'seo-tools' => array(
189
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
190
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
191
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
192
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
193
			'The SEO Framework'                    => 'autodescription/autodescription.php',
194
		),
195
		'verification-tools' => array(
196
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
197
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
198
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
199
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
200
			'The SEO Framework'                    => 'autodescription/autodescription.php',
201
		),
202
		'widget-visibility' => array(
203
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
204
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
205
		),
206
		'sitemaps' => array(
207
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
208
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
209
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
210
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
211
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
212
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
213
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
214
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
215
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
216
			'The SEO Framework'                    => 'autodescription/autodescription.php',
217
			'Sitemap'                              => 'sitemap/sitemap.php',
218
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
219
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
220
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
221
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
222
		),
223
		'lazy-images' => array(
224
			'Lazy Load'              => 'lazy-load/lazy-load.php',
225
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
226
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
227
		),
228
	);
229
230
	/**
231
	 * Plugins for which we turn off our Facebook OG Tags implementation.
232
	 *
233
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
234
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
235
	 *
236
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
237
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
238
	 */
239
	private $open_graph_conflicting_plugins = array(
240
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
241
		                                                         // 2 Click Social Media Buttons
242
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
243
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
244
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
245
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
246
		                                                         // Open Graph Meta Tags by Heateor
247
		'facebook/facebook.php',                                 // Facebook (official plugin)
248
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
249
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
250
		                                                         // Facebook Featured Image & OG Meta Tags
251
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
252
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
253
		                                                         // Facebook Open Graph Meta Tags for WordPress
254
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
255
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
256
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
257
		                                                         // Fedmich's Facebook Open Graph Meta
258
		'network-publisher/networkpub.php',                      // Network Publisher
259
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
260
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
261
		                                                         // NextScripts SNAP
262
		'og-tags/og-tags.php',                                   // OG Tags
263
		'opengraph/opengraph.php',                               // Open Graph
264
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
265
		                                                         // Open Graph Protocol Framework
266
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
267
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
268
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
269
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
270
		'sharepress/sharepress.php',                             // SharePress
271
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
272
		'social-discussions/social-discussions.php',             // Social Discussions
273
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
274
		'socialize/socialize.php',                               // Socialize
275
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
276
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
277
		                                                         // Tweet, Like, Google +1 and Share
278
		'wordbooker/wordbooker.php',                             // Wordbooker
279
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
280
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
281
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
282
		                                                         // WP Facebook Like Send & Open Graph Meta
283
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
284
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
285
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
286
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
287
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
288
	);
289
290
	/**
291
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
292
	 */
293
	private $twitter_cards_conflicting_plugins = array(
294
	//	'twitter/twitter.php',                       // The official one handles this on its own.
295
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
296
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
297
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
298
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
299
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
300
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
301
		'twitter-cards/twitter-cards.php',           // Twitter Cards
302
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
303
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
304
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
305
	);
306
307
	/**
308
	 * Message to display in admin_notice
309
	 * @var string
310
	 */
311
	public $message = '';
312
313
	/**
314
	 * Error to display in admin_notice
315
	 * @var string
316
	 */
317
	public $error = '';
318
319
	/**
320
	 * Modules that need more privacy description.
321
	 * @var string
322
	 */
323
	public $privacy_checks = '';
324
325
	/**
326
	 * Stats to record once the page loads
327
	 *
328
	 * @var array
329
	 */
330
	public $stats = array();
331
332
	/**
333
	 * Jetpack_Sync object
334
	 */
335
	public $sync;
336
337
	/**
338
	 * Verified data for JSON authorization request
339
	 */
340
	public $json_api_authorization_request = array();
341
342
	/**
343
	 * @var \Automattic\Jetpack\Connection\Manager
344
	 */
345
	protected $connection_manager;
346
347
	/**
348
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
349
	 */
350
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
351
352
	/**
353
	 * Holds the singleton instance of this class
354
	 * @since 2.3.3
355
	 * @var Jetpack
356
	 */
357
	static $instance = false;
358
359
	/**
360
	 * Singleton
361
	 * @static
362
	 */
363
	public static function init() {
364
		if ( ! self::$instance ) {
365
			self::$instance = new Jetpack;
366
367
			self::$instance->plugin_upgrade();
368
		}
369
370
		return self::$instance;
371
	}
372
373
	/**
374
	 * Must never be called statically
375
	 */
376
	function plugin_upgrade() {
377
		if ( Jetpack::is_active() ) {
378
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
379
			if ( JETPACK__VERSION != $version ) {
380
				// Prevent multiple upgrades at once - only a single process should trigger
381
				// an upgrade to avoid stampedes
382
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
383
					return;
384
				}
385
386
				// Set a short lock to prevent multiple instances of the upgrade
387
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
388
389
				// check which active modules actually exist and remove others from active_modules list
390
				$unfiltered_modules = Jetpack::get_active_modules();
391
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
392
				if ( array_diff( $unfiltered_modules, $modules ) ) {
393
					Jetpack::update_active_modules( $modules );
394
				}
395
396
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
397
398
				// Upgrade to 4.3.0
399
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
400
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
401
				}
402
403
				// Make sure Markdown for posts gets turned back on
404
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
405
					update_option( 'wpcom_publish_posts_with_markdown', true );
406
				}
407
408
				if ( did_action( 'wp_loaded' ) ) {
409
					self::upgrade_on_load();
410
				} else {
411
					add_action(
412
						'wp_loaded',
413
						array( __CLASS__, 'upgrade_on_load' )
414
					);
415
				}
416
			}
417
		}
418
	}
419
420
	/**
421
	 * Runs upgrade routines that need to have modules loaded.
422
	 */
423
	static function upgrade_on_load() {
424
425
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
426
		// This can happen in case Jetpack has been just upgraded and is
427
		// being initialized late during the page load. In this case we wait
428
		// until the next proper admin page load with Jetpack active.
429
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
430
			delete_transient( self::$plugin_upgrade_lock_key );
431
432
			return;
433
		}
434
435
		Jetpack::maybe_set_version_option();
436
437
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
438
			Jetpack_Widget_Conditions::migrate_post_type_rules();
439
		}
440
441
		if (
442
			class_exists( 'Jetpack_Sitemap_Manager' )
443
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
444
		) {
445
			do_action( 'jetpack_sitemaps_purge_data' );
446
		}
447
448
		delete_transient( self::$plugin_upgrade_lock_key );
449
	}
450
451
	/**
452
	 * Saves all the currently active modules to options.
453
	 * Also fires Action hooks for each newly activated and deactivated module.
454
	 *
455
	 * @param $modules Array Array of active modules to be saved in options.
456
	 *
457
	 * @return $success bool true for success, false for failure.
458
	 */
459
	static function update_active_modules( $modules ) {
460
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
461
		$active_modules       = Jetpack::get_active_modules();
462
		$new_active_modules   = array_diff( $modules, $current_modules );
463
		$new_inactive_modules = array_diff( $active_modules, $modules );
464
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
465
		$reindexed_modules    = array_values( $new_current_modules );
466
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
467
468
		foreach ( $new_active_modules as $module ) {
469
			/**
470
			 * Fires when a specific module is activated.
471
			 *
472
			 * @since 1.9.0
473
			 *
474
			 * @param string $module Module slug.
475
			 * @param boolean $success whether the module was activated. @since 4.2
476
			 */
477
			do_action( 'jetpack_activate_module', $module, $success );
478
			/**
479
			 * Fires when a module is activated.
480
			 * The dynamic part of the filter, $module, is the module slug.
481
			 *
482
			 * @since 1.9.0
483
			 *
484
			 * @param string $module Module slug.
485
			 */
486
			do_action( "jetpack_activate_module_$module", $module );
487
		}
488
489
		foreach ( $new_inactive_modules as $module ) {
490
			/**
491
			 * Fired after a module has been deactivated.
492
			 *
493
			 * @since 4.2.0
494
			 *
495
			 * @param string $module Module slug.
496
			 * @param boolean $success whether the module was deactivated.
497
			 */
498
			do_action( 'jetpack_deactivate_module', $module, $success );
499
			/**
500
			 * Fires when a module is deactivated.
501
			 * The dynamic part of the filter, $module, is the module slug.
502
			 *
503
			 * @since 1.9.0
504
			 *
505
			 * @param string $module Module slug.
506
			 */
507
			do_action( "jetpack_deactivate_module_$module", $module );
508
		}
509
510
		return $success;
511
	}
512
513
	static function delete_active_modules() {
514
		self::update_active_modules( array() );
515
	}
516
517
	/**
518
	 * Constructor.  Initializes WordPress hooks
519
	 */
520
	private function __construct() {
521
		/*
522
		 * Check for and alert any deprecated hooks
523
		 */
524
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
525
526
		/*
527
		 * Enable enhanced handling of previewing sites in Calypso
528
		 */
529
		if ( Jetpack::is_active() ) {
530
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
531
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
532
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
533
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
534
		}
535
536
		/*
537
		 * Load things that should only be in Network Admin.
538
		 *
539
		 * For now blow away everything else until a more full
540
		 * understanding of what is needed at the network level is
541
		 * available
542
		 */
543
		if ( is_multisite() ) {
544
			Jetpack_Network::init();
545
		}
546
547
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
548
			return function() {
549
				return wp_generate_password( 32, false );
550
			};
551
		} );
552
553
		$this->connection_manager = new Connection_Manager( );
554
555
		/**
556
		 * Prepare Gutenberg Editor functionality
557
		 */
558
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
559
		Jetpack_Gutenberg::init();
560
		Jetpack_Gutenberg::load_independent_blocks();
561
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
562
563
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
564
565
		// Unlink user before deleting the user from .com
566
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
567
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
568
569
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
570
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
571
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
572
				define( 'XMLRPC_REQUEST', true );
573
			}
574
575
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
576
577
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
578
		}
579
580
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
581
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
582
583
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
584
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
585
586
			$this->require_jetpack_authentication();
587
588
			if ( Jetpack::is_active() ) {
589
				// Hack to preserve $HTTP_RAW_POST_DATA
590
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
591
592
				$signed = $this->verify_xml_rpc_signature();
593 View Code Duplication
				if ( $signed && ! is_wp_error( $signed ) ) {
594
					// The actual API methods.
595
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
596
				} else {
597
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
598
					// active Jetpack connection, so that additional users can link their account.
599
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
600
				}
601 View Code Duplication
			} else {
602
				// The bootstrap API methods.
603
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
604
				$signed = $this->verify_xml_rpc_signature();
605
				if ( $signed && ! is_wp_error( $signed ) ) {
606
					// the jetpack Provision method is available for blog-token-signed requests
607
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
608
				}
609
			}
610
611
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
612
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
613
		} elseif (
614
			is_admin() &&
615
			isset( $_POST['action'] ) && (
616
				'jetpack_upload_file' == $_POST['action'] ||
617
				'jetpack_update_file' == $_POST['action']
618
			)
619
		) {
620
			$this->require_jetpack_authentication();
621
			$this->add_remote_request_handlers();
622
		} else {
623
			if ( Jetpack::is_active() ) {
624
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
625
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
626
			}
627
		}
628
629
		if ( Jetpack::is_active() ) {
630
			Jetpack_Heartbeat::init();
631
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
632
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
633
				Jetpack_Search_Performance_Logger::init();
634
			}
635
		}
636
637
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
638
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
639
640
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
641
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
642
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
643
		}
644
645
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
646
647
		add_action( 'admin_init', array( $this, 'admin_init' ) );
648
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
649
650
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
651
652
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
653
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
654
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
655
656
		// returns HTTPS support status
657
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
658
659
		// JITM AJAX callback function
660
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
661
662
		// Universal ajax callback for all tracking events triggered via js
663
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
664
665
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
666
667
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
668
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
669
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
670
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
671
672
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
673
674
		/**
675
		 * These actions run checks to load additional files.
676
		 * They check for external files or plugins, so they need to run as late as possible.
677
		 */
678
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
679
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
680
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
681
682
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
683
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
684
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
685
686
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
687
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
688
689
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
690
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
691
692
		// A filter to control all just in time messages
693
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
694
695
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
696
697
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
698
		// We should make sure to only do this for front end links.
699
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
700
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
701
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
702
703
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
704
			//so they point moderation links on emails to Calypso
705
			jetpack_require_lib( 'functions.wp-notify' );
706
		}
707
708
		// Update the Jetpack plan from API on heartbeats
709
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
710
711
		/**
712
		 * This is the hack to concatenate all css files into one.
713
		 * For description and reasoning see the implode_frontend_css method
714
		 *
715
		 * Super late priority so we catch all the registered styles
716
		 */
717
		if( !is_admin() ) {
718
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
719
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
720
		}
721
722
		/**
723
		 * These are sync actions that we need to keep track of for jitms
724
		 */
725
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
726
727
		// Actually push the stats on shutdown.
728
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
729
			add_action( 'shutdown', array( $this, 'push_stats' ) );
730
		}
731
	}
732
733
	/**
734
	 * This is ported over from the manage module, which has been deprecated and baked in here.
735
	 *
736
	 * @param $domains
737
	 */
738
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
739
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
740
	}
741
742
	/**
743
	 * Return $domains, with 'wordpress.com' appended.
744
	 * This is ported over from the manage module, which has been deprecated and baked in here.
745
	 *
746
	 * @param $domains
747
	 * @return array
748
	 */
749
	function allow_wpcom_domain( $domains ) {
750
		if ( empty( $domains ) ) {
751
			$domains = array();
752
		}
753
		$domains[] = 'wordpress.com';
754
		return array_unique( $domains );
755
	}
756
757
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
758
		$post = get_post( $post_id );
759
760
		if ( empty( $post ) ) {
761
			return $default_url;
762
		}
763
764
		$post_type = $post->post_type;
765
766
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
767
		// https://en.support.wordpress.com/custom-post-types/
768
		$allowed_post_types = array(
769
			'post' => 'post',
770
			'page' => 'page',
771
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
772
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
773
		);
774
775
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
776
			return $default_url;
777
		}
778
779
		$path_prefix = $allowed_post_types[ $post_type ];
780
781
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
782
783
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
784
	}
785
786
	function point_edit_comment_links_to_calypso( $url ) {
787
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
788
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
789
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
790
			Jetpack::build_raw_urls( get_home_url() ),
791
			$query_args['amp;c']
792
		) );
793
	}
794
795
	function jetpack_track_last_sync_callback( $params ) {
796
		/**
797
		 * Filter to turn off jitm caching
798
		 *
799
		 * @since 5.4.0
800
		 *
801
		 * @param bool false Whether to cache just in time messages
802
		 */
803
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
804
			return $params;
805
		}
806
807
		if ( is_array( $params ) && isset( $params[0] ) ) {
808
			$option = $params[0];
809
			if ( 'active_plugins' === $option ) {
810
				// use the cache if we can, but not terribly important if it gets evicted
811
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
812
			}
813
		}
814
815
		return $params;
816
	}
817
818
	function jetpack_connection_banner_callback() {
819
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
820
821
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
822
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
823
			wp_send_json_success();
824
		}
825
826
		wp_die();
827
	}
828
829
	/**
830
	 * Removes all XML-RPC methods that are not `jetpack.*`.
831
	 * Only used in our alternate XML-RPC endpoint, where we want to
832
	 * ensure that Core and other plugins' methods are not exposed.
833
	 *
834
	 * @param array $methods
835
	 * @return array filtered $methods
836
	 */
837
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
838
		$jetpack_methods = array();
839
840
		foreach ( $methods as $method => $callback ) {
841
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
842
				$jetpack_methods[ $method ] = $callback;
843
			}
844
		}
845
846
		return $jetpack_methods;
847
	}
848
849
	/**
850
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
851
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
852
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
853
	 * which is accessible via a different URI. Most of the below is copied directly
854
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
855
	 */
856
	function alternate_xmlrpc() {
857
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
858
		global $HTTP_RAW_POST_DATA;
859
860
		// Some browser-embedded clients send cookies. We don't want them.
861
		$_COOKIE = array();
862
863
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
864
		// but we can do it ourself.
865
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
866
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
867
		}
868
869
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
870
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
871
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
872
		}
873
874
		// phpcs:enable
875
876
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
877
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
878
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
879
880
		/**
881
		 * Filters the class used for handling XML-RPC requests.
882
		 *
883
		 * @since 3.1.0
884
		 *
885
		 * @param string $class The name of the XML-RPC server class.
886
		 */
887
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
888
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
889
890
		// Fire off the request
891
		nocache_headers();
892
		$wp_xmlrpc_server->serve_request();
893
894
		exit;
895
	}
896
897
	function jetpack_admin_ajax_tracks_callback() {
898
		// Check for nonce
899
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
900
			wp_die( 'Permissions check failed.' );
901
		}
902
903
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
904
			wp_die( 'No valid event name or type.' );
905
		}
906
907
		$tracks_data = array();
908
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
909
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
910
				$tracks_data = $_REQUEST['tracksEventProp'];
911
			} else {
912
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
913
			}
914
		}
915
916
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
917
		wp_send_json_success();
918
		wp_die();
919
	}
920
921
	/**
922
	 * The callback for the JITM ajax requests.
923
	 */
924
	function jetpack_jitm_ajax_callback() {
925
		// Check for nonce
926
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
927
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
928
		}
929
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
930
			$module_slug = $_REQUEST['jitmModule'];
931
			Jetpack::log( 'activate', $module_slug );
932
			Jetpack::activate_module( $module_slug, false, false );
933
			Jetpack::state( 'message', 'no_message' );
934
935
			//A Jetpack module is being activated through a JITM, track it
936
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
937
			$this->do_stats( 'server_side' );
938
939
			wp_send_json_success();
940
		}
941
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
942
			// get the hide_jitm options array
943
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
944
			$module_slug = $_REQUEST['jitmModule'];
945
946
			if( ! $jetpack_hide_jitm ) {
947
				$jetpack_hide_jitm = array(
948
					$module_slug => 'hide'
949
				);
950
			} else {
951
				$jetpack_hide_jitm[$module_slug] = 'hide';
952
			}
953
954
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
955
956
			//jitm is being dismissed forever, track it
957
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
958
			$this->do_stats( 'server_side' );
959
960
			wp_send_json_success();
961
		}
962 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
963
			$module_slug = $_REQUEST['jitmModule'];
964
965
			// User went to WordPress.com, track this
966
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
967
			$this->do_stats( 'server_side' );
968
969
			wp_send_json_success();
970
		}
971 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
972
			$track = $_REQUEST['jitmModule'];
973
974
			// User is viewing JITM, track it.
975
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
976
			$this->do_stats( 'server_side' );
977
978
			wp_send_json_success();
979
		}
980
	}
981
982
	/**
983
	 * If there are any stats that need to be pushed, but haven't been, push them now.
984
	 */
985
	function push_stats() {
986
		if ( ! empty( $this->stats ) ) {
987
			$this->do_stats( 'server_side' );
988
		}
989
	}
990
991
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
992
		switch( $cap ) {
993
			case 'jetpack_connect' :
994
			case 'jetpack_reconnect' :
995
				if ( Jetpack::is_development_mode() ) {
996
					$caps = array( 'do_not_allow' );
997
					break;
998
				}
999
				/**
1000
				 * Pass through. If it's not development mode, these should match disconnect.
1001
				 * Let users disconnect if it's development mode, just in case things glitch.
1002
				 */
1003
			case 'jetpack_disconnect' :
1004
				/**
1005
				 * In multisite, can individual site admins manage their own connection?
1006
				 *
1007
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1008
				 */
1009
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1010
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1011
						/**
1012
						 * We need to update the option name -- it's terribly unclear which
1013
						 * direction the override goes.
1014
						 *
1015
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1016
						 */
1017
						$caps = array( 'do_not_allow' );
1018
						break;
1019
					}
1020
				}
1021
1022
				$caps = array( 'manage_options' );
1023
				break;
1024
			case 'jetpack_manage_modules' :
1025
			case 'jetpack_activate_modules' :
1026
			case 'jetpack_deactivate_modules' :
1027
				$caps = array( 'manage_options' );
1028
				break;
1029
			case 'jetpack_configure_modules' :
1030
				$caps = array( 'manage_options' );
1031
				break;
1032
			case 'jetpack_manage_autoupdates' :
1033
				$caps = array(
1034
					'manage_options',
1035
					'update_plugins',
1036
				);
1037
				break;
1038
			case 'jetpack_network_admin_page':
1039
			case 'jetpack_network_settings_page':
1040
				$caps = array( 'manage_network_plugins' );
1041
				break;
1042
			case 'jetpack_network_sites_page':
1043
				$caps = array( 'manage_sites' );
1044
				break;
1045
			case 'jetpack_admin_page' :
1046
				if ( Jetpack::is_development_mode() ) {
1047
					$caps = array( 'manage_options' );
1048
					break;
1049
				} else {
1050
					$caps = array( 'read' );
1051
				}
1052
				break;
1053
			case 'jetpack_connect_user' :
1054
				if ( Jetpack::is_development_mode() ) {
1055
					$caps = array( 'do_not_allow' );
1056
					break;
1057
				}
1058
				$caps = array( 'read' );
1059
				break;
1060
		}
1061
		return $caps;
1062
	}
1063
1064
	function require_jetpack_authentication() {
1065
		// Don't let anyone authenticate
1066
		$_COOKIE = array();
1067
		remove_all_filters( 'authenticate' );
1068
		remove_all_actions( 'wp_login_failed' );
1069
1070
		if ( Jetpack::is_active() ) {
1071
			// Allow Jetpack authentication
1072
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1073
		}
1074
	}
1075
1076
	/**
1077
	 * Load language files
1078
	 * @action plugins_loaded
1079
	 */
1080
	public static function plugin_textdomain() {
1081
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1082
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1083
	}
1084
1085
	/**
1086
	 * Register assets for use in various modules and the Jetpack admin page.
1087
	 *
1088
	 * @uses wp_script_is, wp_register_script, plugins_url
1089
	 * @action wp_loaded
1090
	 * @return null
1091
	 */
1092
	public function register_assets() {
1093
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1094
			wp_register_script(
1095
				'spin',
1096
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1097
				false,
1098
				'1.3'
1099
			);
1100
		}
1101
1102
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1103
			wp_register_script(
1104
				'jquery.spin',
1105
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1106
				array( 'jquery', 'spin' ),
1107
				'1.3'
1108
			);
1109
		}
1110
1111 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1112
			wp_register_script(
1113
				'jetpack-gallery-settings',
1114
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1115
				array( 'media-views' ),
1116
				'20121225'
1117
			);
1118
		}
1119
1120
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1121
			wp_register_script(
1122
				'jetpack-twitter-timeline',
1123
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1124
				array( 'jquery' ),
1125
				'4.0.0',
1126
				true
1127
			);
1128
		}
1129
1130
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1131
			wp_register_script(
1132
				'jetpack-facebook-embed',
1133
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1134
				array( 'jquery' ),
1135
				null,
1136
				true
1137
			);
1138
1139
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1140
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1141
			if ( ! is_numeric( $fb_app_id ) ) {
1142
				$fb_app_id = '';
1143
			}
1144
			wp_localize_script(
1145
				'jetpack-facebook-embed',
1146
				'jpfbembed',
1147
				array(
1148
					'appid' => $fb_app_id,
1149
					'locale' => $this->get_locale(),
1150
				)
1151
			);
1152
		}
1153
1154
		/**
1155
		 * As jetpack_register_genericons is by default fired off a hook,
1156
		 * the hook may have already fired by this point.
1157
		 * So, let's just trigger it manually.
1158
		 */
1159
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1160
		jetpack_register_genericons();
1161
1162
		/**
1163
		 * Register the social logos
1164
		 */
1165
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1166
		jetpack_register_social_logos();
1167
1168 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1169
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1170
	}
1171
1172
	/**
1173
	 * Guess locale from language code.
1174
	 *
1175
	 * @param string $lang Language code.
1176
	 * @return string|bool
1177
	 */
1178 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1179
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1180
			return 'en_US';
1181
		}
1182
1183
		if ( ! class_exists( 'GP_Locales' ) ) {
1184
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1185
				return false;
1186
			}
1187
1188
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1189
		}
1190
1191
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1192
			// WP.com: get_locale() returns 'it'
1193
			$locale = GP_Locales::by_slug( $lang );
1194
		} else {
1195
			// Jetpack: get_locale() returns 'it_IT';
1196
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1197
		}
1198
1199
		if ( ! $locale ) {
1200
			return false;
1201
		}
1202
1203
		if ( empty( $locale->facebook_locale ) ) {
1204
			if ( empty( $locale->wp_locale ) ) {
1205
				return false;
1206
			} else {
1207
				// Facebook SDK is smart enough to fall back to en_US if a
1208
				// locale isn't supported. Since supported Facebook locales
1209
				// can fall out of sync, we'll attempt to use the known
1210
				// wp_locale value and rely on said fallback.
1211
				return $locale->wp_locale;
1212
			}
1213
		}
1214
1215
		return $locale->facebook_locale;
1216
	}
1217
1218
	/**
1219
	 * Get the locale.
1220
	 *
1221
	 * @return string|bool
1222
	 */
1223
	function get_locale() {
1224
		$locale = $this->guess_locale_from_lang( get_locale() );
1225
1226
		if ( ! $locale ) {
1227
			$locale = 'en_US';
1228
		}
1229
1230
		return $locale;
1231
	}
1232
1233
	/**
1234
	 * Device Pixels support
1235
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1236
	 */
1237
	function devicepx() {
1238
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1239
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1240
		}
1241
	}
1242
1243
	/**
1244
	 * Return the network_site_url so that .com knows what network this site is a part of.
1245
	 * @param  bool $option
1246
	 * @return string
1247
	 */
1248
	public function jetpack_main_network_site_option( $option ) {
1249
		return network_site_url();
1250
	}
1251
	/**
1252
	 * Network Name.
1253
	 */
1254
	static function network_name( $option = null ) {
1255
		global $current_site;
1256
		return $current_site->site_name;
1257
	}
1258
	/**
1259
	 * Does the network allow new user and site registrations.
1260
	 * @return string
1261
	 */
1262
	static function network_allow_new_registrations( $option = null ) {
1263
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1264
	}
1265
	/**
1266
	 * Does the network allow admins to add new users.
1267
	 * @return boolian
1268
	 */
1269
	static function network_add_new_users( $option = null ) {
1270
		return (bool) get_site_option( 'add_new_users' );
1271
	}
1272
	/**
1273
	 * File upload psace left per site in MB.
1274
	 *  -1 means NO LIMIT.
1275
	 * @return number
1276
	 */
1277
	static function network_site_upload_space( $option = null ) {
1278
		// value in MB
1279
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1280
	}
1281
1282
	/**
1283
	 * Network allowed file types.
1284
	 * @return string
1285
	 */
1286
	static function network_upload_file_types( $option = null ) {
1287
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1288
	}
1289
1290
	/**
1291
	 * Maximum file upload size set by the network.
1292
	 * @return number
1293
	 */
1294
	static function network_max_upload_file_size( $option = null ) {
1295
		// value in KB
1296
		return get_site_option( 'fileupload_maxk', 300 );
1297
	}
1298
1299
	/**
1300
	 * Lets us know if a site allows admins to manage the network.
1301
	 * @return array
1302
	 */
1303
	static function network_enable_administration_menus( $option = null ) {
1304
		return get_site_option( 'menu_items' );
1305
	}
1306
1307
	/**
1308
	 * If a user has been promoted to or demoted from admin, we need to clear the
1309
	 * jetpack_other_linked_admins transient.
1310
	 *
1311
	 * @since 4.3.2
1312
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1313
	 *
1314
	 * @param int    $user_id   The user ID whose role changed.
1315
	 * @param string $role      The new role.
1316
	 * @param array  $old_roles An array of the user's previous roles.
1317
	 */
1318
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1319
		if ( 'administrator' == $role
1320
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1321
			|| is_null( $old_roles )
1322
		) {
1323
			delete_transient( 'jetpack_other_linked_admins' );
1324
		}
1325
	}
1326
1327
	/**
1328
	 * Checks to see if there are any other users available to become primary
1329
	 * Users must both:
1330
	 * - Be linked to wpcom
1331
	 * - Be an admin
1332
	 *
1333
	 * @return mixed False if no other users are linked, Int if there are.
1334
	 */
1335
	static function get_other_linked_admins() {
1336
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1337
1338
		if ( false === $other_linked_users ) {
1339
			$admins = get_users( array( 'role' => 'administrator' ) );
1340
			if ( count( $admins ) > 1 ) {
1341
				$available = array();
1342
				foreach ( $admins as $admin ) {
1343
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1344
						$available[] = $admin->ID;
1345
					}
1346
				}
1347
1348
				$count_connected_admins = count( $available );
1349
				if ( count( $available ) > 1 ) {
1350
					$other_linked_users = $count_connected_admins;
1351
				} else {
1352
					$other_linked_users = 0;
1353
				}
1354
			} else {
1355
				$other_linked_users = 0;
1356
			}
1357
1358
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1359
		}
1360
1361
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1362
	}
1363
1364
	/**
1365
	 * Return whether we are dealing with a multi network setup or not.
1366
	 * The reason we are type casting this is because we want to avoid the situation where
1367
	 * the result is false since when is_main_network_option return false it cases
1368
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1369
	 * database which could be set to anything as opposed to what this function returns.
1370
	 * @param  bool  $option
1371
	 *
1372
	 * @return boolean
1373
	 */
1374
	public function is_main_network_option( $option ) {
1375
		// return '1' or ''
1376
		return (string) (bool) Jetpack::is_multi_network();
1377
	}
1378
1379
	/**
1380
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1381
	 *
1382
	 * @param  string  $option
1383
	 * @return boolean
1384
	 */
1385
	public function is_multisite( $option ) {
1386
		return (string) (bool) is_multisite();
1387
	}
1388
1389
	/**
1390
	 * Implemented since there is no core is multi network function
1391
	 * Right now there is no way to tell if we which network is the dominant network on the system
1392
	 *
1393
	 * @since  3.3
1394
	 * @return boolean
1395
	 */
1396
	public static function is_multi_network() {
1397
		global  $wpdb;
1398
1399
		// if we don't have a multi site setup no need to do any more
1400
		if ( ! is_multisite() ) {
1401
			return false;
1402
		}
1403
1404
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1405
		if ( $num_sites > 1 ) {
1406
			return true;
1407
		} else {
1408
			return false;
1409
		}
1410
	}
1411
1412
	/**
1413
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1414
	 * @return null
1415
	 */
1416
	function update_jetpack_main_network_site_option() {
1417
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1418
	}
1419
	/**
1420
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1421
	 *
1422
	 */
1423
	function update_jetpack_network_settings() {
1424
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1425
		// Only sync this info for the main network site.
1426
	}
1427
1428
	/**
1429
	 * Get back if the current site is single user site.
1430
	 *
1431
	 * @return bool
1432
	 */
1433
	public static function is_single_user_site() {
1434
		global $wpdb;
1435
1436 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1437
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1438
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1439
		}
1440
		return 1 === (int) $some_users;
1441
	}
1442
1443
	/**
1444
	 * Returns true if the site has file write access false otherwise.
1445
	 * @return string ( '1' | '0' )
1446
	 **/
1447
	public static function file_system_write_access() {
1448
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1449
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1450
		}
1451
1452
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1453
1454
		$filesystem_method = get_filesystem_method();
1455
		if ( $filesystem_method === 'direct' ) {
1456
			return 1;
1457
		}
1458
1459
		ob_start();
1460
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1461
		ob_end_clean();
1462
		if ( $filesystem_credentials_are_stored ) {
1463
			return 1;
1464
		}
1465
		return 0;
1466
	}
1467
1468
	/**
1469
	 * Finds out if a site is using a version control system.
1470
	 * @return string ( '1' | '0' )
1471
	 **/
1472
	public static function is_version_controlled() {
1473
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1474
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1475
	}
1476
1477
	/**
1478
	 * Determines whether the current theme supports featured images or not.
1479
	 * @return string ( '1' | '0' )
1480
	 */
1481
	public static function featured_images_enabled() {
1482
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1483
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1484
	}
1485
1486
	/**
1487
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1488
	 *
1489
	 * @deprecated 4.7 use get_avatar_url instead.
1490
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1491
	 * @param int $size Size of the avatar image
1492
	 * @param string $default URL to a default image to use if no avatar is available
1493
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1494
	 *
1495
	 * @return array
1496
	 */
1497
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1498
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1499
		return get_avatar_url( $id_or_email, array(
1500
			'size' => $size,
1501
			'default' => $default,
1502
			'force_default' => $force_display,
1503
		) );
1504
	}
1505
1506
	/**
1507
	 * jetpack_updates is saved in the following schema:
1508
	 *
1509
	 * array (
1510
	 *      'plugins'                       => (int) Number of plugin updates available.
1511
	 *      'themes'                        => (int) Number of theme updates available.
1512
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1513
	 *      'translations'                  => (int) Number of translation updates available.
1514
	 *      'total'                         => (int) Total of all available updates.
1515
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1516
	 * )
1517
	 * @return array
1518
	 */
1519
	public static function get_updates() {
1520
		$update_data = wp_get_update_data();
1521
1522
		// Stores the individual update counts as well as the total count.
1523
		if ( isset( $update_data['counts'] ) ) {
1524
			$updates = $update_data['counts'];
1525
		}
1526
1527
		// If we need to update WordPress core, let's find the latest version number.
1528 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1529
			$cur = get_preferred_from_update_core();
1530
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1531
				$updates['wp_update_version'] = $cur->current;
1532
			}
1533
		}
1534
		return isset( $updates ) ? $updates : array();
1535
	}
1536
1537
	public static function get_update_details() {
1538
		$update_details = array(
1539
			'update_core' => get_site_transient( 'update_core' ),
1540
			'update_plugins' => get_site_transient( 'update_plugins' ),
1541
			'update_themes' => get_site_transient( 'update_themes' ),
1542
		);
1543
		return $update_details;
1544
	}
1545
1546
	public static function refresh_update_data() {
1547
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1548
1549
	}
1550
1551
	public static function refresh_theme_data() {
1552
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1553
	}
1554
1555
	/**
1556
	 * Is Jetpack active?
1557
	 */
1558
	public static function is_active() {
1559
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1560
	}
1561
1562
	/**
1563
	 * Make an API call to WordPress.com for plan status
1564
	 *
1565
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1566
	 *
1567
	 * @return bool True if plan is updated, false if no update
1568
	 */
1569
	public static function refresh_active_plan_from_wpcom() {
1570
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1571
		return Jetpack_Plan::refresh_from_wpcom();
1572
	}
1573
1574
	/**
1575
	 * Get the plan that this Jetpack site is currently using
1576
	 *
1577
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1578
	 * @return array Active Jetpack plan details.
1579
	 */
1580
	public static function get_active_plan() {
1581
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1582
		return Jetpack_Plan::get();
1583
	}
1584
1585
	/**
1586
	 * Determine whether the active plan supports a particular feature
1587
	 *
1588
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1589
	 * @return bool True if plan supports feature, false if not.
1590
	 */
1591
	public static function active_plan_supports( $feature ) {
1592
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1593
		return Jetpack_Plan::supports( $feature );
1594
	}
1595
1596
	/**
1597
	 * Is Jetpack in development (offline) mode?
1598
	 */
1599
	public static function is_development_mode() {
1600
		$development_mode = false;
1601
1602
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1603
			$development_mode = JETPACK_DEV_DEBUG;
1604
		} elseif ( $site_url = site_url() ) {
1605
			$development_mode = false === strpos( $site_url, '.' );
1606
		}
1607
1608
		/**
1609
		 * Filters Jetpack's development mode.
1610
		 *
1611
		 * @see https://jetpack.com/support/development-mode/
1612
		 *
1613
		 * @since 2.2.1
1614
		 *
1615
		 * @param bool $development_mode Is Jetpack's development mode active.
1616
		 */
1617
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1618
		return $development_mode;
1619
	}
1620
1621
	/**
1622
	 * Whether the site is currently onboarding or not.
1623
	 * A site is considered as being onboarded if it currently has an onboarding token.
1624
	 *
1625
	 * @since 5.8
1626
	 *
1627
	 * @access public
1628
	 * @static
1629
	 *
1630
	 * @return bool True if the site is currently onboarding, false otherwise
1631
	 */
1632
	public static function is_onboarding() {
1633
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1634
	}
1635
1636
	/**
1637
	 * Determines reason for Jetpack development mode.
1638
	 */
1639
	public static function development_mode_trigger_text() {
1640
		if ( ! Jetpack::is_development_mode() ) {
1641
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1642
		}
1643
1644
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1645
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1646
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1647
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1648
		} else {
1649
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1650
		}
1651
1652
		return $notice;
1653
1654
	}
1655
	/**
1656
	* Get Jetpack development mode notice text and notice class.
1657
	*
1658
	* Mirrors the checks made in Jetpack::is_development_mode
1659
	*
1660
	*/
1661
	public static function show_development_mode_notice() {
1662 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1663
			$notice = sprintf(
1664
			/* translators: %s is a URL */
1665
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1666
				'https://jetpack.com/support/development-mode/'
1667
			);
1668
1669
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1670
1671
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1672
		}
1673
1674
		// Throw up a notice if using a development version and as for feedback.
1675
		if ( Jetpack::is_development_version() ) {
1676
			/* translators: %s is a URL */
1677
			$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/' );
1678
1679
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1680
		}
1681
		// Throw up a notice if using staging mode
1682
		if ( Jetpack::is_staging_site() ) {
1683
			/* translators: %s is a URL */
1684
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1685
1686
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1687
		}
1688
	}
1689
1690
	/**
1691
	 * Whether Jetpack's version maps to a public release, or a development version.
1692
	 */
1693
	public static function is_development_version() {
1694
		/**
1695
		 * Allows filtering whether this is a development version of Jetpack.
1696
		 *
1697
		 * This filter is especially useful for tests.
1698
		 *
1699
		 * @since 4.3.0
1700
		 *
1701
		 * @param bool $development_version Is this a develoment version of Jetpack?
1702
		 */
1703
		return (bool) apply_filters(
1704
			'jetpack_development_version',
1705
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1706
		);
1707
	}
1708
1709
	/**
1710
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1711
	 */
1712
	public static function is_user_connected( $user_id = false ) {
1713
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1714
		if ( ! $user_id ) {
1715
			return false;
1716
		}
1717
1718
		return (bool) Jetpack_Data::get_access_token( $user_id );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1719
	}
1720
1721
	/**
1722
	 * Get the wpcom user data of the current|specified connected user.
1723
	 */
1724
	public static function get_connected_user_data( $user_id = null ) {
1725
		if ( ! $user_id ) {
1726
			$user_id = get_current_user_id();
1727
		}
1728
1729
		$transient_key = "jetpack_connected_user_data_$user_id";
1730
1731
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1732
			return $cached_user_data;
1733
		}
1734
1735
		Jetpack::load_xml_rpc_client();
1736
		$xml = new Jetpack_IXR_Client( array(
1737
			'user_id' => $user_id,
1738
		) );
1739
		$xml->query( 'wpcom.getUser' );
1740
		if ( ! $xml->isError() ) {
1741
			$user_data = $xml->getResponse();
1742
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1743
			return $user_data;
1744
		}
1745
1746
		return false;
1747
	}
1748
1749
	/**
1750
	 * Get the wpcom email of the current|specified connected user.
1751
	 */
1752 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1753
		if ( ! $user_id ) {
1754
			$user_id = get_current_user_id();
1755
		}
1756
		Jetpack::load_xml_rpc_client();
1757
		$xml = new Jetpack_IXR_Client( array(
1758
			'user_id' => $user_id,
1759
		) );
1760
		$xml->query( 'wpcom.getUserEmail' );
1761
		if ( ! $xml->isError() ) {
1762
			return $xml->getResponse();
1763
		}
1764
		return false;
1765
	}
1766
1767
	/**
1768
	 * Get the wpcom email of the master user.
1769
	 */
1770
	public static function get_master_user_email() {
1771
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1772
		if ( $master_user_id ) {
1773
			return self::get_connected_user_email( $master_user_id );
1774
		}
1775
		return '';
1776
	}
1777
1778
	function current_user_is_connection_owner() {
1779
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1780
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1781
	}
1782
1783
	/**
1784
	 * Gets current user IP address.
1785
	 *
1786
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1787
	 *
1788
	 * @return string                  Current user IP address.
1789
	 */
1790
	public static function current_user_ip( $check_all_headers = false ) {
1791
		if ( $check_all_headers ) {
1792
			foreach ( array(
1793
				'HTTP_CF_CONNECTING_IP',
1794
				'HTTP_CLIENT_IP',
1795
				'HTTP_X_FORWARDED_FOR',
1796
				'HTTP_X_FORWARDED',
1797
				'HTTP_X_CLUSTER_CLIENT_IP',
1798
				'HTTP_FORWARDED_FOR',
1799
				'HTTP_FORWARDED',
1800
				'HTTP_VIA',
1801
			) as $key ) {
1802
				if ( ! empty( $_SERVER[ $key ] ) ) {
1803
					return $_SERVER[ $key ];
1804
				}
1805
			}
1806
		}
1807
1808
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1809
	}
1810
1811
	/**
1812
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1813
	 */
1814
	function extra_oembed_providers() {
1815
		// Cloudup: https://dev.cloudup.com/#oembed
1816
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1817
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1818
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1819
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1820
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1821
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1822
	}
1823
1824
	/**
1825
	 * Synchronize connected user role changes
1826
	 */
1827
	function user_role_change( $user_id ) {
1828
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1829
		Jetpack_Sync_Users::user_role_change( $user_id );
1830
	}
1831
1832
	/**
1833
	 * Loads the currently active modules.
1834
	 */
1835
	public static function load_modules() {
1836
		if (
1837
			! self::is_active()
1838
			&& ! self::is_development_mode()
1839
			&& ! self::is_onboarding()
1840
			&& (
1841
				! is_multisite()
1842
				|| ! get_site_option( 'jetpack_protect_active' )
1843
			)
1844
		) {
1845
			return;
1846
		}
1847
1848
		$version = Jetpack_Options::get_option( 'version' );
1849 View Code Duplication
		if ( ! $version ) {
1850
			$version = $old_version = JETPACK__VERSION . ':' . time();
1851
			/** This action is documented in class.jetpack.php */
1852
			do_action( 'updating_jetpack_version', $version, false );
1853
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1854
		}
1855
		list( $version ) = explode( ':', $version );
1856
1857
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1858
1859
		$modules_data = array();
1860
1861
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1862
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1863
			$updated_modules = array();
1864
			foreach ( $modules as $module ) {
1865
				$modules_data[ $module ] = Jetpack::get_module( $module );
1866
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1867
					continue;
1868
				}
1869
1870
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1871
					continue;
1872
				}
1873
1874
				$updated_modules[] = $module;
1875
			}
1876
1877
			$modules = array_diff( $modules, $updated_modules );
1878
		}
1879
1880
		$is_development_mode = Jetpack::is_development_mode();
1881
1882
		foreach ( $modules as $index => $module ) {
1883
			// If we're in dev mode, disable modules requiring a connection
1884
			if ( $is_development_mode ) {
1885
				// Prime the pump if we need to
1886
				if ( empty( $modules_data[ $module ] ) ) {
1887
					$modules_data[ $module ] = Jetpack::get_module( $module );
1888
				}
1889
				// If the module requires a connection, but we're in local mode, don't include it.
1890
				if ( $modules_data[ $module ]['requires_connection'] ) {
1891
					continue;
1892
				}
1893
			}
1894
1895
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1896
				continue;
1897
			}
1898
1899
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1900
				unset( $modules[ $index ] );
1901
				self::update_active_modules( array_values( $modules ) );
1902
				continue;
1903
			}
1904
1905
			/**
1906
			 * Fires when a specific module is loaded.
1907
			 * The dynamic part of the hook, $module, is the module slug.
1908
			 *
1909
			 * @since 1.1.0
1910
			 */
1911
			do_action( 'jetpack_module_loaded_' . $module );
1912
		}
1913
1914
		/**
1915
		 * Fires when all the modules are loaded.
1916
		 *
1917
		 * @since 1.1.0
1918
		 */
1919
		do_action( 'jetpack_modules_loaded' );
1920
1921
		// 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.
1922
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1923
	}
1924
1925
	/**
1926
	 * Check if Jetpack's REST API compat file should be included
1927
	 * @action plugins_loaded
1928
	 * @return null
1929
	 */
1930
	public function check_rest_api_compat() {
1931
		/**
1932
		 * Filters the list of REST API compat files to be included.
1933
		 *
1934
		 * @since 2.2.5
1935
		 *
1936
		 * @param array $args Array of REST API compat files to include.
1937
		 */
1938
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1939
1940
		if ( function_exists( 'bbpress' ) )
1941
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1942
1943
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1944
			require_once $_jetpack_rest_api_compat_include;
1945
	}
1946
1947
	/**
1948
	 * Gets all plugins currently active in values, regardless of whether they're
1949
	 * traditionally activated or network activated.
1950
	 *
1951
	 * @todo Store the result in core's object cache maybe?
1952
	 */
1953
	public static function get_active_plugins() {
1954
		$active_plugins = (array) get_option( 'active_plugins', array() );
1955
1956
		if ( is_multisite() ) {
1957
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1958
			// whereas active_plugins stores them in the values.
1959
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1960
			if ( $network_plugins ) {
1961
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1962
			}
1963
		}
1964
1965
		sort( $active_plugins );
1966
1967
		return array_unique( $active_plugins );
1968
	}
1969
1970
	/**
1971
	 * Gets and parses additional plugin data to send with the heartbeat data
1972
	 *
1973
	 * @since 3.8.1
1974
	 *
1975
	 * @return array Array of plugin data
1976
	 */
1977
	public static function get_parsed_plugin_data() {
1978
		if ( ! function_exists( 'get_plugins' ) ) {
1979
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1980
		}
1981
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1982
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1983
		$active_plugins = Jetpack::get_active_plugins();
1984
1985
		$plugins = array();
1986
		foreach ( $all_plugins as $path => $plugin_data ) {
1987
			$plugins[ $path ] = array(
1988
					'is_active' => in_array( $path, $active_plugins ),
1989
					'file'      => $path,
1990
					'name'      => $plugin_data['Name'],
1991
					'version'   => $plugin_data['Version'],
1992
					'author'    => $plugin_data['Author'],
1993
			);
1994
		}
1995
1996
		return $plugins;
1997
	}
1998
1999
	/**
2000
	 * Gets and parses theme data to send with the heartbeat data
2001
	 *
2002
	 * @since 3.8.1
2003
	 *
2004
	 * @return array Array of theme data
2005
	 */
2006
	public static function get_parsed_theme_data() {
2007
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2008
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2009
2010
		$themes = array();
2011
		foreach ( $all_themes as $slug => $theme_data ) {
2012
			$theme_headers = array();
2013
			foreach ( $header_keys as $header_key ) {
2014
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2015
			}
2016
2017
			$themes[ $slug ] = array(
2018
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2019
					'slug' => $slug,
2020
					'theme_root' => $theme_data->get_theme_root_uri(),
2021
					'parent' => $theme_data->parent(),
2022
					'headers' => $theme_headers
2023
			);
2024
		}
2025
2026
		return $themes;
2027
	}
2028
2029
	/**
2030
	 * Checks whether a specific plugin is active.
2031
	 *
2032
	 * We don't want to store these in a static variable, in case
2033
	 * there are switch_to_blog() calls involved.
2034
	 */
2035
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2036
		return in_array( $plugin, self::get_active_plugins() );
2037
	}
2038
2039
	/**
2040
	 * Check if Jetpack's Open Graph tags should be used.
2041
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2042
	 *
2043
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2044
	 * @action plugins_loaded
2045
	 * @return null
2046
	 */
2047
	public function check_open_graph() {
2048
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2049
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2050
		}
2051
2052
		$active_plugins = self::get_active_plugins();
2053
2054
		if ( ! empty( $active_plugins ) ) {
2055
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2056
				if ( in_array( $plugin, $active_plugins ) ) {
2057
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2058
					break;
2059
				}
2060
			}
2061
		}
2062
2063
		/**
2064
		 * Allow the addition of Open Graph Meta Tags to all pages.
2065
		 *
2066
		 * @since 2.0.3
2067
		 *
2068
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2069
		 */
2070
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2071
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2072
		}
2073
	}
2074
2075
	/**
2076
	 * Check if Jetpack's Twitter tags should be used.
2077
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2078
	 *
2079
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2080
	 * @action plugins_loaded
2081
	 * @return null
2082
	 */
2083
	public function check_twitter_tags() {
2084
2085
		$active_plugins = self::get_active_plugins();
2086
2087
		if ( ! empty( $active_plugins ) ) {
2088
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2089
				if ( in_array( $plugin, $active_plugins ) ) {
2090
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2091
					break;
2092
				}
2093
			}
2094
		}
2095
2096
		/**
2097
		 * Allow Twitter Card Meta tags to be disabled.
2098
		 *
2099
		 * @since 2.6.0
2100
		 *
2101
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2102
		 */
2103
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2104
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2105
		}
2106
	}
2107
2108
	/**
2109
	 * Allows plugins to submit security reports.
2110
 	 *
2111
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2112
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2113
	 * @param array   $args         See definitions above
2114
	 */
2115
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2116
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2117
	}
2118
2119
/* Jetpack Options API */
2120
2121
	public static function get_option_names( $type = 'compact' ) {
2122
		return Jetpack_Options::get_option_names( $type );
2123
	}
2124
2125
	/**
2126
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2127
 	 *
2128
	 * @param string $name    Option name
2129
	 * @param mixed  $default (optional)
2130
	 */
2131
	public static function get_option( $name, $default = false ) {
2132
		return Jetpack_Options::get_option( $name, $default );
2133
	}
2134
2135
	/**
2136
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2137
 	 *
2138
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2139
	 * @param string $name  Option name
2140
	 * @param mixed  $value Option value
2141
	 */
2142
	public static function update_option( $name, $value ) {
2143
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2144
		return Jetpack_Options::update_option( $name, $value );
2145
	}
2146
2147
	/**
2148
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2149
 	 *
2150
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2151
	 * @param array $array array( option name => option value, ... )
2152
	 */
2153
	public static function update_options( $array ) {
2154
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2155
		return Jetpack_Options::update_options( $array );
2156
	}
2157
2158
	/**
2159
	 * Deletes the given option.  May be passed multiple option names as an array.
2160
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2161
	 *
2162
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2163
	 * @param string|array $names
2164
	 */
2165
	public static function delete_option( $names ) {
2166
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2167
		return Jetpack_Options::delete_option( $names );
2168
	}
2169
2170
	/**
2171
	 * Enters a user token into the user_tokens option
2172
	 *
2173
	 * @param int $user_id
2174
	 * @param string $token
2175
	 * return bool
2176
	 */
2177
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2178
		// not designed for concurrent updates
2179
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2180
		if ( ! is_array( $user_tokens ) )
2181
			$user_tokens = array();
2182
		$user_tokens[$user_id] = $token;
2183
		if ( $is_master_user ) {
2184
			$master_user = $user_id;
2185
			$options     = compact( 'user_tokens', 'master_user' );
2186
		} else {
2187
			$options = compact( 'user_tokens' );
2188
		}
2189
		return Jetpack_Options::update_options( $options );
2190
	}
2191
2192
	/**
2193
	 * Returns an array of all PHP files in the specified absolute path.
2194
	 * Equivalent to glob( "$absolute_path/*.php" ).
2195
	 *
2196
	 * @param string $absolute_path The absolute path of the directory to search.
2197
	 * @return array Array of absolute paths to the PHP files.
2198
	 */
2199
	public static function glob_php( $absolute_path ) {
2200
		if ( function_exists( 'glob' ) ) {
2201
			return glob( "$absolute_path/*.php" );
2202
		}
2203
2204
		$absolute_path = untrailingslashit( $absolute_path );
2205
		$files = array();
2206
		if ( ! $dir = @opendir( $absolute_path ) ) {
2207
			return $files;
2208
		}
2209
2210
		while ( false !== $file = readdir( $dir ) ) {
2211
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2212
				continue;
2213
			}
2214
2215
			$file = "$absolute_path/$file";
2216
2217
			if ( ! is_file( $file ) ) {
2218
				continue;
2219
			}
2220
2221
			$files[] = $file;
2222
		}
2223
2224
		closedir( $dir );
2225
2226
		return $files;
2227
	}
2228
2229
	public static function activate_new_modules( $redirect = false ) {
2230
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2231
			return;
2232
		}
2233
2234
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2235 View Code Duplication
		if ( ! $jetpack_old_version ) {
2236
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2237
			/** This action is documented in class.jetpack.php */
2238
			do_action( 'updating_jetpack_version', $version, false );
2239
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2240
		}
2241
2242
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2243
2244
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2245
			return;
2246
		}
2247
2248
		$active_modules     = Jetpack::get_active_modules();
2249
		$reactivate_modules = array();
2250
		foreach ( $active_modules as $active_module ) {
2251
			$module = Jetpack::get_module( $active_module );
2252
			if ( ! isset( $module['changed'] ) ) {
2253
				continue;
2254
			}
2255
2256
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2257
				continue;
2258
			}
2259
2260
			$reactivate_modules[] = $active_module;
2261
			Jetpack::deactivate_module( $active_module );
2262
		}
2263
2264
		$new_version = JETPACK__VERSION . ':' . time();
2265
		/** This action is documented in class.jetpack.php */
2266
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2267
		Jetpack_Options::update_options(
2268
			array(
2269
				'version'     => $new_version,
2270
				'old_version' => $jetpack_old_version,
2271
			)
2272
		);
2273
2274
		Jetpack::state( 'message', 'modules_activated' );
2275
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2276
2277
		if ( $redirect ) {
2278
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2279
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2280
				$page = $_GET['page'];
2281
			}
2282
2283
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2284
			exit;
2285
		}
2286
	}
2287
2288
	/**
2289
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2290
	 * Make sure to tuck away module "library" files in a sub-directory.
2291
	 */
2292
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2293
		static $modules = null;
2294
2295
		if ( ! isset( $modules ) ) {
2296
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2297
			// Use the cache if we're on the front-end and it's available...
2298
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2299
				$modules = $available_modules_option[ JETPACK__VERSION ];
2300
			} else {
2301
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2302
2303
				$modules = array();
2304
2305
				foreach ( $files as $file ) {
2306
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2307
						continue;
2308
					}
2309
2310
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2311
				}
2312
2313
				Jetpack_Options::update_option( 'available_modules', array(
2314
					JETPACK__VERSION => $modules,
2315
				) );
2316
			}
2317
		}
2318
2319
		/**
2320
		 * Filters the array of modules available to be activated.
2321
		 *
2322
		 * @since 2.4.0
2323
		 *
2324
		 * @param array $modules Array of available modules.
2325
		 * @param string $min_version Minimum version number required to use modules.
2326
		 * @param string $max_version Maximum version number required to use modules.
2327
		 */
2328
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2329
2330
		if ( ! $min_version && ! $max_version ) {
2331
			return array_keys( $mods );
2332
		}
2333
2334
		$r = array();
2335
		foreach ( $mods as $slug => $introduced ) {
2336
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2337
				continue;
2338
			}
2339
2340
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2341
				continue;
2342
			}
2343
2344
			$r[] = $slug;
2345
		}
2346
2347
		return $r;
2348
	}
2349
2350
	/**
2351
	 * Default modules loaded on activation.
2352
	 */
2353
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2354
		$return = array();
2355
2356
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2357
			$module_data = Jetpack::get_module( $module );
2358
2359
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2360
				case 'yes' :
2361
					$return[] = $module;
2362
					break;
2363
				case 'public' :
2364
					if ( Jetpack_Options::get_option( 'public' ) ) {
2365
						$return[] = $module;
2366
					}
2367
					break;
2368
				case 'no' :
2369
				default :
2370
					break;
2371
			}
2372
		}
2373
		/**
2374
		 * Filters the array of default modules.
2375
		 *
2376
		 * @since 2.5.0
2377
		 *
2378
		 * @param array $return Array of default modules.
2379
		 * @param string $min_version Minimum version number required to use modules.
2380
		 * @param string $max_version Maximum version number required to use modules.
2381
		 */
2382
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2383
	}
2384
2385
	/**
2386
	 * Checks activated modules during auto-activation to determine
2387
	 * if any of those modules are being deprecated.  If so, close
2388
	 * them out, and add any replacement modules.
2389
	 *
2390
	 * Runs at priority 99 by default.
2391
	 *
2392
	 * This is run late, so that it can still activate a module if
2393
	 * the new module is a replacement for another that the user
2394
	 * currently has active, even if something at the normal priority
2395
	 * would kibosh everything.
2396
	 *
2397
	 * @since 2.6
2398
	 * @uses jetpack_get_default_modules filter
2399
	 * @param array $modules
2400
	 * @return array
2401
	 */
2402
	function handle_deprecated_modules( $modules ) {
2403
		$deprecated_modules = array(
2404
			'debug'            => null,  // Closed out and moved to the debugger library.
2405
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2406
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2407
		);
2408
2409
		// Don't activate SSO if they never completed activating WPCC.
2410
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2411
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2412
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2413
				$deprecated_modules['wpcc'] = null;
2414
			}
2415
		}
2416
2417
		foreach ( $deprecated_modules as $module => $replacement ) {
2418
			if ( Jetpack::is_module_active( $module ) ) {
2419
				self::deactivate_module( $module );
2420
				if ( $replacement ) {
2421
					$modules[] = $replacement;
2422
				}
2423
			}
2424
		}
2425
2426
		return array_unique( $modules );
2427
	}
2428
2429
	/**
2430
	 * Checks activated plugins during auto-activation to determine
2431
	 * if any of those plugins are in the list with a corresponding module
2432
	 * that is not compatible with the plugin. The module will not be allowed
2433
	 * to auto-activate.
2434
	 *
2435
	 * @since 2.6
2436
	 * @uses jetpack_get_default_modules filter
2437
	 * @param array $modules
2438
	 * @return array
2439
	 */
2440
	function filter_default_modules( $modules ) {
2441
2442
		$active_plugins = self::get_active_plugins();
2443
2444
		if ( ! empty( $active_plugins ) ) {
2445
2446
			// For each module we'd like to auto-activate...
2447
			foreach ( $modules as $key => $module ) {
2448
				// If there are potential conflicts for it...
2449
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2450
					// For each potential conflict...
2451
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2452
						// If that conflicting plugin is active...
2453
						if ( in_array( $plugin, $active_plugins ) ) {
2454
							// Remove that item from being auto-activated.
2455
							unset( $modules[ $key ] );
2456
						}
2457
					}
2458
				}
2459
			}
2460
		}
2461
2462
		return $modules;
2463
	}
2464
2465
	/**
2466
	 * Extract a module's slug from its full path.
2467
	 */
2468
	public static function get_module_slug( $file ) {
2469
		return str_replace( '.php', '', basename( $file ) );
2470
	}
2471
2472
	/**
2473
	 * Generate a module's path from its slug.
2474
	 */
2475
	public static function get_module_path( $slug ) {
2476
		/**
2477
		 * Filters the path of a modules.
2478
		 *
2479
		 * @since 7.4.0
2480
		 *
2481
		 * @param array $return The absolute path to a module's root php file
2482
		 * @param string $slug The module slug
2483
		 */
2484
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2485
	}
2486
2487
	/**
2488
	 * Load module data from module file. Headers differ from WordPress
2489
	 * plugin headers to avoid them being identified as standalone
2490
	 * plugins on the WordPress plugins page.
2491
	 */
2492
	public static function get_module( $module ) {
2493
		$headers = array(
2494
			'name'                      => 'Module Name',
2495
			'description'               => 'Module Description',
2496
			'jumpstart_desc'            => 'Jumpstart Description',
2497
			'sort'                      => 'Sort Order',
2498
			'recommendation_order'      => 'Recommendation Order',
2499
			'introduced'                => 'First Introduced',
2500
			'changed'                   => 'Major Changes In',
2501
			'deactivate'                => 'Deactivate',
2502
			'free'                      => 'Free',
2503
			'requires_connection'       => 'Requires Connection',
2504
			'auto_activate'             => 'Auto Activate',
2505
			'module_tags'               => 'Module Tags',
2506
			'feature'                   => 'Feature',
2507
			'additional_search_queries' => 'Additional Search Queries',
2508
			'plan_classes'              => 'Plans',
2509
		);
2510
2511
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2512
2513
		$mod = Jetpack::get_file_data( $file, $headers );
2514
		if ( empty( $mod['name'] ) ) {
2515
			return false;
2516
		}
2517
2518
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2519
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2520
		$mod['deactivate']              = empty( $mod['deactivate'] );
2521
		$mod['free']                    = empty( $mod['free'] );
2522
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2523
2524
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2525
			$mod['auto_activate'] = 'No';
2526
		} else {
2527
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2528
		}
2529
2530
		if ( $mod['module_tags'] ) {
2531
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2532
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2533
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2534
		} else {
2535
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2536
		}
2537
2538 View Code Duplication
		if ( $mod['plan_classes'] ) {
2539
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2540
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2541
		} else {
2542
			$mod['plan_classes'] = array( 'free' );
2543
		}
2544
2545 View Code Duplication
		if ( $mod['feature'] ) {
2546
			$mod['feature'] = explode( ',', $mod['feature'] );
2547
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2548
		} else {
2549
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2550
		}
2551
2552
		/**
2553
		 * Filters the feature array on a module.
2554
		 *
2555
		 * This filter allows you to control where each module is filtered: Recommended,
2556
		 * Jumpstart, and the default "Other" listing.
2557
		 *
2558
		 * @since 3.5.0
2559
		 *
2560
		 * @param array   $mod['feature'] The areas to feature this module:
2561
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2562
		 *     'Recommended' shows on the main Jetpack admin screen.
2563
		 *     'Other' should be the default if no other value is in the array.
2564
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2565
		 * @param array   $mod All the currently assembled module data.
2566
		 */
2567
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2568
2569
		/**
2570
		 * Filter the returned data about a module.
2571
		 *
2572
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2573
		 * so please be careful.
2574
		 *
2575
		 * @since 3.6.0
2576
		 *
2577
		 * @param array   $mod    The details of the requested module.
2578
		 * @param string  $module The slug of the module, e.g. sharedaddy
2579
		 * @param string  $file   The path to the module source file.
2580
		 */
2581
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2582
	}
2583
2584
	/**
2585
	 * Like core's get_file_data implementation, but caches the result.
2586
	 */
2587
	public static function get_file_data( $file, $headers ) {
2588
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2589
		$file_name = basename( $file );
2590
2591
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2592
2593
		$file_data_option = get_transient( $cache_key );
2594
2595
		if ( false === $file_data_option ) {
2596
			$file_data_option = array();
2597
		}
2598
2599
		$key           = md5( $file_name . serialize( $headers ) );
2600
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2601
2602
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2603
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2604
			return $file_data_option[ $key ];
2605
		}
2606
2607
		$data = get_file_data( $file, $headers );
2608
2609
		$file_data_option[ $key ] = $data;
2610
2611
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2612
2613
		return $data;
2614
	}
2615
2616
2617
	/**
2618
	 * Return translated module tag.
2619
	 *
2620
	 * @param string $tag Tag as it appears in each module heading.
2621
	 *
2622
	 * @return mixed
2623
	 */
2624
	public static function translate_module_tag( $tag ) {
2625
		return jetpack_get_module_i18n_tag( $tag );
2626
	}
2627
2628
	/**
2629
	 * Get i18n strings as a JSON-encoded string
2630
	 *
2631
	 * @return string The locale as JSON
2632
	 */
2633
	public static function get_i18n_data_json() {
2634
2635
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2636
		// JSON files with the file they should be included for. This is an md5
2637
		// of '_inc/build/admin.js'.
2638
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2639
2640
		$i18n_json =
2641
				   JETPACK__PLUGIN_DIR
2642
				   . 'languages/json/jetpack-'
2643
				   . get_user_locale()
2644
				   . '-'
2645
				   . $path_md5
2646
				   . '.json';
2647
2648
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2649
			$locale_data = @file_get_contents( $i18n_json );
2650
			if ( $locale_data ) {
2651
				return $locale_data;
2652
			}
2653
		}
2654
2655
		// Return valid empty Jed locale
2656
		return '{ "locale_data": { "messages": { "": {} } } }';
2657
	}
2658
2659
	/**
2660
	 * Add locale data setup to wp-i18n
2661
	 *
2662
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2663
	 *
2664
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2665
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2666
	 *
2667
	 * This method provides a safe way to request the setup multiple times but add the script at
2668
	 * most once.
2669
	 *
2670
	 * @since 6.7.0
2671
	 *
2672
	 * @return void
2673
	 */
2674
	public static function setup_wp_i18n_locale_data() {
2675
		static $script_added = false;
2676
		if ( ! $script_added ) {
2677
			$script_added = true;
2678
			wp_add_inline_script(
2679
				'wp-i18n',
2680
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2681
			);
2682
		}
2683
	}
2684
2685
	/**
2686
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2687
	 *
2688
	 * @since 3.9.2
2689
	 *
2690
	 * @param array $modules
2691
	 *
2692
	 * @return string|void
2693
	 */
2694
	public static function get_translated_modules( $modules ) {
2695
		foreach ( $modules as $index => $module ) {
2696
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2697
			if ( isset( $module['name'] ) ) {
2698
				$modules[ $index ]['name'] = $i18n_module['name'];
2699
			}
2700
			if ( isset( $module['description'] ) ) {
2701
				$modules[ $index ]['description'] = $i18n_module['description'];
2702
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2703
			}
2704
		}
2705
		return $modules;
2706
	}
2707
2708
	/**
2709
	 * Get a list of activated modules as an array of module slugs.
2710
	 */
2711
	public static function get_active_modules() {
2712
		$active = Jetpack_Options::get_option( 'active_modules' );
2713
2714
		if ( ! is_array( $active ) ) {
2715
			$active = array();
2716
		}
2717
2718
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2719
			$active[] = 'vaultpress';
2720
		} else {
2721
			$active = array_diff( $active, array( 'vaultpress' ) );
2722
		}
2723
2724
		//If protect is active on the main site of a multisite, it should be active on all sites.
2725
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2726
			$active[] = 'protect';
2727
		}
2728
2729
		/**
2730
		 * Allow filtering of the active modules.
2731
		 *
2732
		 * Gives theme and plugin developers the power to alter the modules that
2733
		 * are activated on the fly.
2734
		 *
2735
		 * @since 5.8.0
2736
		 *
2737
		 * @param array $active Array of active module slugs.
2738
		 */
2739
		$active = apply_filters( 'jetpack_active_modules', $active );
2740
2741
		return array_unique( $active );
2742
	}
2743
2744
	/**
2745
	 * Check whether or not a Jetpack module is active.
2746
	 *
2747
	 * @param string $module The slug of a Jetpack module.
2748
	 * @return bool
2749
	 *
2750
	 * @static
2751
	 */
2752
	public static function is_module_active( $module ) {
2753
		return in_array( $module, self::get_active_modules() );
2754
	}
2755
2756
	public static function is_module( $module ) {
2757
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2758
	}
2759
2760
	/**
2761
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2762
	 *
2763
	 * @param bool $catch True to start catching, False to stop.
2764
	 *
2765
	 * @static
2766
	 */
2767
	public static function catch_errors( $catch ) {
2768
		static $display_errors, $error_reporting;
2769
2770
		if ( $catch ) {
2771
			$display_errors  = @ini_set( 'display_errors', 1 );
2772
			$error_reporting = @error_reporting( E_ALL );
2773
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2774
		} else {
2775
			@ini_set( 'display_errors', $display_errors );
2776
			@error_reporting( $error_reporting );
2777
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2778
		}
2779
	}
2780
2781
	/**
2782
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2783
	 */
2784
	public static function catch_errors_on_shutdown() {
2785
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2786
	}
2787
2788
	/**
2789
	 * Rewrite any string to make paths easier to read.
2790
	 *
2791
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2792
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2793
	 *
2794
	 * @param $string
2795
	 * @return mixed
2796
	 */
2797
	public static function alias_directories( $string ) {
2798
		// ABSPATH has a trailing slash.
2799
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2800
		// WP_CONTENT_DIR does not have a trailing slash.
2801
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2802
2803
		return $string;
2804
	}
2805
2806
	public static function activate_default_modules(
2807
		$min_version = false,
2808
		$max_version = false,
2809
		$other_modules = array(),
2810
		$redirect = true,
2811
		$send_state_messages = true
2812
	) {
2813
		$jetpack = Jetpack::init();
2814
2815
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2816
		$modules = array_merge( $other_modules, $modules );
2817
2818
		// Look for standalone plugins and disable if active.
2819
2820
		$to_deactivate = array();
2821
		foreach ( $modules as $module ) {
2822
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2823
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2824
			}
2825
		}
2826
2827
		$deactivated = array();
2828
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2829
			list( $probable_file, $probable_title ) = $deactivate_me;
2830
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2831
				$deactivated[] = $module;
2832
			}
2833
		}
2834
2835
		if ( $deactivated && $redirect ) {
2836
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2837
2838
			$url = add_query_arg(
2839
				array(
2840
					'action'   => 'activate_default_modules',
2841
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2842
				),
2843
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2844
			);
2845
			wp_safe_redirect( $url );
2846
			exit;
2847
		}
2848
2849
		/**
2850
		 * Fires before default modules are activated.
2851
		 *
2852
		 * @since 1.9.0
2853
		 *
2854
		 * @param string $min_version Minimum version number required to use modules.
2855
		 * @param string $max_version Maximum version number required to use modules.
2856
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2857
		 */
2858
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2859
2860
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2861
		if ( $send_state_messages ) {
2862
			Jetpack::restate();
2863
			Jetpack::catch_errors( true );
2864
		}
2865
2866
		$active = Jetpack::get_active_modules();
2867
2868
		foreach ( $modules as $module ) {
2869
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2870
				$active[] = $module;
2871
				self::update_active_modules( $active );
2872
				continue;
2873
			}
2874
2875
			if ( $send_state_messages && in_array( $module, $active ) ) {
2876
				$module_info = Jetpack::get_module( $module );
2877 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2878
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2879
					if ( $active_state = Jetpack::state( $state ) ) {
2880
						$active_state = explode( ',', $active_state );
2881
					} else {
2882
						$active_state = array();
2883
					}
2884
					$active_state[] = $module;
2885
					Jetpack::state( $state, implode( ',', $active_state ) );
2886
				}
2887
				continue;
2888
			}
2889
2890
			$file = Jetpack::get_module_path( $module );
2891
			if ( ! file_exists( $file ) ) {
2892
				continue;
2893
			}
2894
2895
			// we'll override this later if the plugin can be included without fatal error
2896
			if ( $redirect ) {
2897
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2898
			}
2899
2900
			if ( $send_state_messages ) {
2901
				Jetpack::state( 'error', 'module_activation_failed' );
2902
				Jetpack::state( 'module', $module );
2903
			}
2904
2905
			ob_start();
2906
			require_once $file;
2907
2908
			$active[] = $module;
2909
2910 View Code Duplication
			if ( $send_state_messages ) {
2911
2912
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2913
				if ( $active_state = Jetpack::state( $state ) ) {
2914
					$active_state = explode( ',', $active_state );
2915
				} else {
2916
					$active_state = array();
2917
				}
2918
				$active_state[] = $module;
2919
				Jetpack::state( $state, implode( ',', $active_state ) );
2920
			}
2921
2922
			Jetpack::update_active_modules( $active );
2923
2924
			ob_end_clean();
2925
		}
2926
2927
		if ( $send_state_messages ) {
2928
			Jetpack::state( 'error', false );
2929
			Jetpack::state( 'module', false );
2930
		}
2931
2932
		Jetpack::catch_errors( false );
2933
		/**
2934
		 * Fires when default modules are activated.
2935
		 *
2936
		 * @since 1.9.0
2937
		 *
2938
		 * @param string $min_version Minimum version number required to use modules.
2939
		 * @param string $max_version Maximum version number required to use modules.
2940
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2941
		 */
2942
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2943
	}
2944
2945
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2946
		/**
2947
		 * Fires before a module is activated.
2948
		 *
2949
		 * @since 2.6.0
2950
		 *
2951
		 * @param string $module Module slug.
2952
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2953
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2954
		 */
2955
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2956
2957
		$jetpack = Jetpack::init();
2958
2959
		if ( ! strlen( $module ) )
2960
			return false;
2961
2962
		if ( ! Jetpack::is_module( $module ) )
2963
			return false;
2964
2965
		// If it's already active, then don't do it again
2966
		$active = Jetpack::get_active_modules();
2967
		foreach ( $active as $act ) {
2968
			if ( $act == $module )
2969
				return true;
2970
		}
2971
2972
		$module_data = Jetpack::get_module( $module );
2973
2974
		if ( ! Jetpack::is_active() ) {
2975
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2976
				return false;
2977
2978
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2979
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2980
				return false;
2981
		}
2982
2983
		// Check and see if the old plugin is active
2984
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2985
			// Deactivate the old plugin
2986
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2987
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2988
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2989
				Jetpack::state( 'deactivated_plugins', $module );
2990
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2991
				exit;
2992
			}
2993
		}
2994
2995
		// Protect won't work with mis-configured IPs
2996
		if ( 'protect' === $module ) {
2997
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2998
			if ( ! jetpack_protect_get_ip() ) {
2999
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3000
				return false;
3001
			}
3002
		}
3003
3004
		if ( ! Jetpack_Plan::supports( $module ) ) {
3005
			return false;
3006
		}
3007
3008
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3009
		Jetpack::state( 'module', $module );
3010
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3011
3012
		Jetpack::catch_errors( true );
3013
		ob_start();
3014
		require Jetpack::get_module_path( $module );
3015
		/** This action is documented in class.jetpack.php */
3016
		do_action( 'jetpack_activate_module', $module );
3017
		$active[] = $module;
3018
		Jetpack::update_active_modules( $active );
3019
3020
		Jetpack::state( 'error', false ); // the override
3021
		ob_end_clean();
3022
		Jetpack::catch_errors( false );
3023
3024
		if ( $redirect ) {
3025
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3026
		}
3027
		if ( $exit ) {
3028
			exit;
3029
		}
3030
		return true;
3031
	}
3032
3033
	function activate_module_actions( $module ) {
3034
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3035
	}
3036
3037
	public static function deactivate_module( $module ) {
3038
		/**
3039
		 * Fires when a module is deactivated.
3040
		 *
3041
		 * @since 1.9.0
3042
		 *
3043
		 * @param string $module Module slug.
3044
		 */
3045
		do_action( 'jetpack_pre_deactivate_module', $module );
3046
3047
		$jetpack = Jetpack::init();
3048
3049
		$active = Jetpack::get_active_modules();
3050
		$new    = array_filter( array_diff( $active, (array) $module ) );
3051
3052
		return self::update_active_modules( $new );
3053
	}
3054
3055
	public static function enable_module_configurable( $module ) {
3056
		$module = Jetpack::get_module_slug( $module );
3057
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3058
	}
3059
3060
	/**
3061
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3062
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3063
	 *
3064
	 * @param string $module Module slug
3065
	 * @return string $url module configuration URL
3066
	 */
3067
	public static function module_configuration_url( $module ) {
3068
		$module = Jetpack::get_module_slug( $module );
3069
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3070
		/**
3071
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3072
		 *
3073
		 * @since 6.9.0
3074
		 *
3075
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3076
		 */
3077
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3078
3079
		return $url;
3080
	}
3081
3082
/* Installation */
3083
	public static function bail_on_activation( $message, $deactivate = true ) {
3084
?>
3085
<!doctype html>
3086
<html>
3087
<head>
3088
<meta charset="<?php bloginfo( 'charset' ); ?>">
3089
<style>
3090
* {
3091
	text-align: center;
3092
	margin: 0;
3093
	padding: 0;
3094
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3095
}
3096
p {
3097
	margin-top: 1em;
3098
	font-size: 18px;
3099
}
3100
</style>
3101
<body>
3102
<p><?php echo esc_html( $message ); ?></p>
3103
</body>
3104
</html>
3105
<?php
3106
		if ( $deactivate ) {
3107
			$plugins = get_option( 'active_plugins' );
3108
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3109
			$update  = false;
3110
			foreach ( $plugins as $i => $plugin ) {
3111
				if ( $plugin === $jetpack ) {
3112
					$plugins[$i] = false;
3113
					$update = true;
3114
				}
3115
			}
3116
3117
			if ( $update ) {
3118
				update_option( 'active_plugins', array_filter( $plugins ) );
3119
			}
3120
		}
3121
		exit;
3122
	}
3123
3124
	/**
3125
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3126
	 * @static
3127
	 */
3128
	public static function plugin_activation( $network_wide ) {
3129
		Jetpack_Options::update_option( 'activated', 1 );
3130
3131
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3132
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3133
		}
3134
3135
		if ( $network_wide )
3136
			Jetpack::state( 'network_nag', true );
3137
3138
		// For firing one-off events (notices) immediately after activation
3139
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3140
3141
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3142
3143
		Jetpack::plugin_initialize();
3144
	}
3145
3146
	public static function get_activation_source( $referer_url ) {
3147
3148
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3149
			return array( 'wp-cli', null );
3150
		}
3151
3152
		$referer = parse_url( $referer_url );
3153
3154
		$source_type = 'unknown';
3155
		$source_query = null;
3156
3157
		if ( ! is_array( $referer ) ) {
3158
			return array( $source_type, $source_query );
3159
		}
3160
3161
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3162
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3163
3164
		if ( isset( $referer['query'] ) ) {
3165
			parse_str( $referer['query'], $query_parts );
3166
		} else {
3167
			$query_parts = array();
3168
		}
3169
3170
		if ( $plugins_path === $referer['path'] ) {
3171
			$source_type = 'list';
3172
		} elseif ( $plugins_install_path === $referer['path'] ) {
3173
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3174
			switch( $tab ) {
3175
				case 'popular':
3176
					$source_type = 'popular';
3177
					break;
3178
				case 'recommended':
3179
					$source_type = 'recommended';
3180
					break;
3181
				case 'favorites':
3182
					$source_type = 'favorites';
3183
					break;
3184
				case 'search':
3185
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3186
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3187
					break;
3188
				default:
3189
					$source_type = 'featured';
3190
			}
3191
		}
3192
3193
		return array( $source_type, $source_query );
3194
	}
3195
3196
	/**
3197
	 * Runs before bumping version numbers up to a new version
3198
	 * @param  string $version    Version:timestamp
3199
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3200
	 * @return null              [description]
3201
	 */
3202
	public static function do_version_bump( $version, $old_version ) {
3203
		if ( ! $old_version ) { // For new sites
3204
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3205
		}
3206
	}
3207
3208
	/**
3209
	 * Sets the internal version number and activation state.
3210
	 * @static
3211
	 */
3212
	public static function plugin_initialize() {
3213
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3214
			Jetpack_Options::update_option( 'activated', 2 );
3215
		}
3216
3217 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3218
			$version = $old_version = JETPACK__VERSION . ':' . time();
3219
			/** This action is documented in class.jetpack.php */
3220
			do_action( 'updating_jetpack_version', $version, false );
3221
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3222
		}
3223
3224
		Jetpack::load_modules();
3225
3226
		Jetpack_Options::delete_option( 'do_activate' );
3227
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3228
	}
3229
3230
	/**
3231
	 * Removes all connection options
3232
	 * @static
3233
	 */
3234
	public static function plugin_deactivation( ) {
3235
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3236
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3237
			Jetpack_Network::init()->deactivate();
3238
		} else {
3239
			Jetpack::disconnect( false );
3240
			//Jetpack_Heartbeat::init()->deactivate();
3241
		}
3242
	}
3243
3244
	/**
3245
	 * Disconnects from the Jetpack servers.
3246
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3247
	 * @static
3248
	 */
3249
	public static function disconnect( $update_activated_state = true ) {
3250
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3251
		Jetpack::clean_nonces( true );
3252
3253
		// If the site is in an IDC because sync is not allowed,
3254
		// let's make sure to not disconnect the production site.
3255
		if ( ! self::validate_sync_error_idc_option() ) {
3256
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3257
			Jetpack::load_xml_rpc_client();
3258
			$xml = new Jetpack_IXR_Client();
3259
			$xml->query( 'jetpack.deregister' );
3260
		}
3261
3262
		Jetpack_Options::delete_option(
3263
			array(
3264
				'blog_token',
3265
				'user_token',
3266
				'user_tokens',
3267
				'master_user',
3268
				'time_diff',
3269
				'fallback_no_verify_ssl_certs',
3270
			)
3271
		);
3272
3273
		Jetpack_IDC::clear_all_idc_options();
3274
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3275
3276
		if ( $update_activated_state ) {
3277
			Jetpack_Options::update_option( 'activated', 4 );
3278
		}
3279
3280
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3281
			// Check then record unique disconnection if site has never been disconnected previously
3282
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3283
				$jetpack_unique_connection['disconnected'] = 1;
3284
			} else {
3285
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3286
					//track unique disconnect
3287
					$jetpack = Jetpack::init();
3288
3289
					$jetpack->stat( 'connections', 'unique-disconnect' );
3290
					$jetpack->do_stats( 'server_side' );
3291
				}
3292
				// increment number of times disconnected
3293
				$jetpack_unique_connection['disconnected'] += 1;
3294
			}
3295
3296
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3297
		}
3298
3299
		// Delete cached connected user data
3300
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3301
		delete_transient( $transient_key );
3302
3303
		// Delete all the sync related data. Since it could be taking up space.
3304
		Jetpack_Sync_Sender::get_instance()->uninstall();
3305
3306
		// Disable the Heartbeat cron
3307
		Jetpack_Heartbeat::init()->deactivate();
3308
	}
3309
3310
	/**
3311
	 * Unlinks the current user from the linked WordPress.com user
3312
	 */
3313
	public static function unlink_user( $user_id = null ) {
3314
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3315
			return false;
3316
3317
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3318
3319
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3320
			return false;
3321
3322
		if ( ! isset( $tokens[ $user_id ] ) )
3323
			return false;
3324
3325
		Jetpack::load_xml_rpc_client();
3326
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3327
		$xml->query( 'jetpack.unlink_user', $user_id );
3328
3329
		unset( $tokens[ $user_id ] );
3330
3331
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3332
3333
		/**
3334
		 * Fires after the current user has been unlinked from WordPress.com.
3335
		 *
3336
		 * @since 4.1.0
3337
		 *
3338
		 * @param int $user_id The current user's ID.
3339
		 */
3340
		do_action( 'jetpack_unlinked_user', $user_id );
3341
3342
		return true;
3343
	}
3344
3345
	/**
3346
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3347
	 */
3348
	public static function try_registration() {
3349
		// The user has agreed to the TOS at some point by now.
3350
		Jetpack_Options::update_option( 'tos_agreed', true );
3351
3352
		// Let's get some testing in beta versions and such.
3353
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3354
			// Before attempting to connect, let's make sure that the domains are viable.
3355
			$domains_to_check = array_unique( array(
3356
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3357
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3358
			) );
3359
			foreach ( $domains_to_check as $domain ) {
3360
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
It seems like $domain defined by $domain on line 3359 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
3361
				if ( is_wp_error( $result ) ) {
3362
					return $result;
3363
				}
3364
			}
3365
		}
3366
3367
		$result = Jetpack::register();
3368
3369
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3370
		if ( ! $result || is_wp_error( $result ) ) {
3371
			return $result;
3372
		} else {
3373
			return true;
3374
		}
3375
	}
3376
3377
	/**
3378
	 * Tracking an internal event log. Try not to put too much chaff in here.
3379
	 *
3380
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3381
	 */
3382
	public static function log( $code, $data = null ) {
3383
		// only grab the latest 200 entries
3384
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3385
3386
		// Append our event to the log
3387
		$log_entry = array(
3388
			'time'    => time(),
3389
			'user_id' => get_current_user_id(),
3390
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3391
			'code'    => $code,
3392
		);
3393
		// Don't bother storing it unless we've got some.
3394
		if ( ! is_null( $data ) ) {
3395
			$log_entry['data'] = $data;
3396
		}
3397
		$log[] = $log_entry;
3398
3399
		// Try add_option first, to make sure it's not autoloaded.
3400
		// @todo: Add an add_option method to Jetpack_Options
3401
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3402
			Jetpack_Options::update_option( 'log', $log );
3403
		}
3404
3405
		/**
3406
		 * Fires when Jetpack logs an internal event.
3407
		 *
3408
		 * @since 3.0.0
3409
		 *
3410
		 * @param array $log_entry {
3411
		 *	Array of details about the log entry.
3412
		 *
3413
		 *	@param string time Time of the event.
3414
		 *	@param int user_id ID of the user who trigerred the event.
3415
		 *	@param int blog_id Jetpack Blog ID.
3416
		 *	@param string code Unique name for the event.
3417
		 *	@param string data Data about the event.
3418
		 * }
3419
		 */
3420
		do_action( 'jetpack_log_entry', $log_entry );
3421
	}
3422
3423
	/**
3424
	 * Get the internal event log.
3425
	 *
3426
	 * @param $event (string) - only return the specific log events
3427
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3428
	 *
3429
	 * @return array of log events || WP_Error for invalid params
3430
	 */
3431
	public static function get_log( $event = false, $num = false ) {
3432
		if ( $event && ! is_string( $event ) ) {
3433
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3434
		}
3435
3436
		if ( $num && ! is_numeric( $num ) ) {
3437
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3438
		}
3439
3440
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3441
3442
		// If nothing set - act as it did before, otherwise let's start customizing the output
3443
		if ( ! $num && ! $event ) {
3444
			return $entire_log;
3445
		} else {
3446
			$entire_log = array_reverse( $entire_log );
3447
		}
3448
3449
		$custom_log_output = array();
3450
3451
		if ( $event ) {
3452
			foreach ( $entire_log as $log_event ) {
3453
				if ( $event == $log_event[ 'code' ] ) {
3454
					$custom_log_output[] = $log_event;
3455
				}
3456
			}
3457
		} else {
3458
			$custom_log_output = $entire_log;
3459
		}
3460
3461
		if ( $num ) {
3462
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3463
		}
3464
3465
		return $custom_log_output;
3466
	}
3467
3468
	/**
3469
	 * Log modification of important settings.
3470
	 */
3471
	public static function log_settings_change( $option, $old_value, $value ) {
3472
		switch( $option ) {
3473
			case 'jetpack_sync_non_public_post_stati':
3474
				self::log( $option, $value );
3475
				break;
3476
		}
3477
	}
3478
3479
	/**
3480
	 * Return stat data for WPCOM sync
3481
	 */
3482
	public static function get_stat_data( $encode = true, $extended = true ) {
3483
		$data = Jetpack_Heartbeat::generate_stats_array();
3484
3485
		if ( $extended ) {
3486
			$additional_data = self::get_additional_stat_data();
3487
			$data = array_merge( $data, $additional_data );
3488
		}
3489
3490
		if ( $encode ) {
3491
			return json_encode( $data );
3492
		}
3493
3494
		return $data;
3495
	}
3496
3497
	/**
3498
	 * Get additional stat data to sync to WPCOM
3499
	 */
3500
	public static function get_additional_stat_data( $prefix = '' ) {
3501
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3502
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3503
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3504
		$return["{$prefix}site-count"]     = 0;
3505
3506
		if ( function_exists( 'get_blog_count' ) ) {
3507
			$return["{$prefix}site-count"] = get_blog_count();
3508
		}
3509
		return $return;
3510
	}
3511
3512
	private static function get_site_user_count() {
3513
		global $wpdb;
3514
3515
		if ( function_exists( 'wp_is_large_network' ) ) {
3516
			if ( wp_is_large_network( 'users' ) ) {
3517
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3518
			}
3519
		}
3520 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3521
			// It wasn't there, so regenerate the data and save the transient
3522
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3523
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3524
		}
3525
		return $user_count;
3526
	}
3527
3528
	/* Admin Pages */
3529
3530
	function admin_init() {
3531
		// If the plugin is not connected, display a connect message.
3532
		if (
3533
			// the plugin was auto-activated and needs its candy
3534
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3535
		||
3536
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3537
			! Jetpack_Options::get_option( 'activated' )
3538
		) {
3539
			Jetpack::plugin_initialize();
3540
		}
3541
3542
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3543
			Jetpack_Connection_Banner::init();
3544
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3545
			// Upgrade: 1.1 -> 1.1.1
3546
			// Check and see if host can verify the Jetpack servers' SSL certificate
3547
			$args = array();
3548
			Jetpack_Client::_wp_remote_request(
3549
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3550
				$args,
3551
				true
3552
			);
3553
		}
3554
3555
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3556
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3557
		}
3558
3559
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3560
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3561
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3562
3563
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3564
			// Artificially throw errors in certain whitelisted cases during plugin activation
3565
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3566
		}
3567
3568
		// Add custom column in wp-admin/users.php to show whether user is linked.
3569
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3570
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3571
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3572
	}
3573
3574
	function admin_body_class( $admin_body_class = '' ) {
3575
		$classes = explode( ' ', trim( $admin_body_class ) );
3576
3577
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3578
3579
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3580
		return " $admin_body_class ";
3581
	}
3582
3583
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3584
		return $admin_body_class . ' jetpack-pagestyles ';
3585
	}
3586
3587
	/**
3588
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3589
	 * This function artificially throws errors for such cases (whitelisted).
3590
	 *
3591
	 * @param string $plugin The activated plugin.
3592
	 */
3593
	function throw_error_on_activate_plugin( $plugin ) {
3594
		$active_modules = Jetpack::get_active_modules();
3595
3596
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3597
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3598
			$throw = false;
3599
3600
			// Try and make sure it really was the stats plugin
3601
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3602
				if ( 'stats.php' == basename( $plugin ) ) {
3603
					$throw = true;
3604
				}
3605
			} else {
3606
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3607
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3608
					$throw = true;
3609
				}
3610
			}
3611
3612
			if ( $throw ) {
3613
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3614
			}
3615
		}
3616
	}
3617
3618
	function intercept_plugin_error_scrape_init() {
3619
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3620
	}
3621
3622
	function intercept_plugin_error_scrape( $action, $result ) {
3623
		if ( ! $result ) {
3624
			return;
3625
		}
3626
3627
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3628
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3629
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3630
			}
3631
		}
3632
	}
3633
3634
	function add_remote_request_handlers() {
3635
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3636
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3637
	}
3638
3639
	function remote_request_handlers() {
3640
		$action = current_filter();
3641
3642
		switch ( current_filter() ) {
3643
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3644
			$response = $this->upload_handler();
3645
			break;
3646
3647
		case 'wp_ajax_nopriv_jetpack_update_file' :
3648
			$response = $this->upload_handler( true );
3649
			break;
3650
		default :
3651
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3652
			break;
3653
		}
3654
3655
		if ( ! $response ) {
3656
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3657
		}
3658
3659
		if ( is_wp_error( $response ) ) {
3660
			$status_code       = $response->get_error_data();
3661
			$error             = $response->get_error_code();
3662
			$error_description = $response->get_error_message();
3663
3664
			if ( ! is_int( $status_code ) ) {
3665
				$status_code = 400;
3666
			}
3667
3668
			status_header( $status_code );
3669
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3670
		}
3671
3672
		status_header( 200 );
3673
		if ( true === $response ) {
3674
			exit;
3675
		}
3676
3677
		die( json_encode( (object) $response ) );
3678
	}
3679
3680
	/**
3681
	 * Uploads a file gotten from the global $_FILES.
3682
	 * If `$update_media_item` is true and `post_id` is defined
3683
	 * the attachment file of the media item (gotten through of the post_id)
3684
	 * will be updated instead of add a new one.
3685
	 *
3686
	 * @param  boolean $update_media_item - update media attachment
3687
	 * @return array - An array describing the uploadind files process
3688
	 */
3689
	function upload_handler( $update_media_item = false ) {
3690
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3691
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3692
		}
3693
3694
		$user = wp_authenticate( '', '' );
3695
		if ( ! $user || is_wp_error( $user ) ) {
3696
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3697
		}
3698
3699
		wp_set_current_user( $user->ID );
3700
3701
		if ( ! current_user_can( 'upload_files' ) ) {
3702
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3703
		}
3704
3705
		if ( empty( $_FILES ) ) {
3706
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3707
		}
3708
3709
		foreach ( array_keys( $_FILES ) as $files_key ) {
3710
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3711
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3712
			}
3713
		}
3714
3715
		$media_keys = array_keys( $_FILES['media'] );
3716
3717
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3718
		if ( ! $token || is_wp_error( $token ) ) {
3719
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3720
		}
3721
3722
		$uploaded_files = array();
3723
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3724
		unset( $GLOBALS['post'] );
3725
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3726
			$file = array();
3727
			foreach ( $media_keys as $media_key ) {
3728
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3729
			}
3730
3731
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3732
3733
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3734
			if ( $hmac_provided !== $hmac_file ) {
3735
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3736
				continue;
3737
			}
3738
3739
			$_FILES['.jetpack.upload.'] = $file;
3740
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3741
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3742
				$post_id = 0;
3743
			}
3744
3745
			if ( $update_media_item ) {
3746
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3747
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3748
				}
3749
3750
				$media_array = $_FILES['media'];
3751
3752
				$file_array['name'] = $media_array['name'][0];
3753
				$file_array['type'] = $media_array['type'][0];
3754
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3755
				$file_array['error'] = $media_array['error'][0];
3756
				$file_array['size'] = $media_array['size'][0];
3757
3758
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3759
3760
				if ( is_wp_error( $edited_media_item ) ) {
3761
					return $edited_media_item;
3762
				}
3763
3764
				$response = (object) array(
3765
					'id'   => (string) $post_id,
3766
					'file' => (string) $edited_media_item->post_title,
3767
					'url'  => (string) wp_get_attachment_url( $post_id ),
3768
					'type' => (string) $edited_media_item->post_mime_type,
3769
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3770
				);
3771
3772
				return (array) array( $response );
3773
			}
3774
3775
			$attachment_id = media_handle_upload(
3776
				'.jetpack.upload.',
3777
				$post_id,
3778
				array(),
3779
				array(
3780
					'action' => 'jetpack_upload_file',
3781
				)
3782
			);
3783
3784
			if ( ! $attachment_id ) {
3785
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3786
			} elseif ( is_wp_error( $attachment_id ) ) {
3787
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3788
			} else {
3789
				$attachment = get_post( $attachment_id );
3790
				$uploaded_files[$index] = (object) array(
3791
					'id'   => (string) $attachment_id,
3792
					'file' => $attachment->post_title,
3793
					'url'  => wp_get_attachment_url( $attachment_id ),
3794
					'type' => $attachment->post_mime_type,
3795
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3796
				);
3797
				// Zip files uploads are not supported unless they are done for installation purposed
3798
				// lets delete them in case something goes wrong in this whole process
3799
				if ( 'application/zip' === $attachment->post_mime_type ) {
3800
					// Schedule a cleanup for 2 hours from now in case of failed install.
3801
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3802
				}
3803
			}
3804
		}
3805
		if ( ! is_null( $global_post ) ) {
3806
			$GLOBALS['post'] = $global_post;
3807
		}
3808
3809
		return $uploaded_files;
3810
	}
3811
3812
	/**
3813
	 * Add help to the Jetpack page
3814
	 *
3815
	 * @since Jetpack (1.2.3)
3816
	 * @return false if not the Jetpack page
3817
	 */
3818
	function admin_help() {
3819
		$current_screen = get_current_screen();
3820
3821
		// Overview
3822
		$current_screen->add_help_tab(
3823
			array(
3824
				'id'		=> 'home',
3825
				'title'		=> __( 'Home', 'jetpack' ),
3826
				'content'	=>
3827
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3828
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3829
					'<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>',
3830
			)
3831
		);
3832
3833
		// Screen Content
3834
		if ( current_user_can( 'manage_options' ) ) {
3835
			$current_screen->add_help_tab(
3836
				array(
3837
					'id'		=> 'settings',
3838
					'title'		=> __( 'Settings', 'jetpack' ),
3839
					'content'	=>
3840
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3841
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3842
						'<ol>' .
3843
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3844
							'<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>' .
3845
						'</ol>' .
3846
						'<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>'
3847
				)
3848
			);
3849
		}
3850
3851
		// Help Sidebar
3852
		$current_screen->set_help_sidebar(
3853
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3854
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3855
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3856
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3857
		);
3858
	}
3859
3860
	function admin_menu_css() {
3861
		wp_enqueue_style( 'jetpack-icons' );
3862
	}
3863
3864
	function admin_menu_order() {
3865
		return true;
3866
	}
3867
3868 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3869
		$jp_menu_order = array();
3870
3871
		foreach ( $menu_order as $index => $item ) {
3872
			if ( $item != 'jetpack' ) {
3873
				$jp_menu_order[] = $item;
3874
			}
3875
3876
			if ( $index == 0 ) {
3877
				$jp_menu_order[] = 'jetpack';
3878
			}
3879
		}
3880
3881
		return $jp_menu_order;
3882
	}
3883
3884
	function admin_banner_styles() {
3885
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3886
3887
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3888
			wp_register_style(
3889
				'jetpack-dops-style',
3890
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3891
				array(),
3892
				JETPACK__VERSION
3893
			);
3894
		}
3895
3896
		wp_enqueue_style(
3897
			'jetpack',
3898
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3899
			array( 'jetpack-dops-style' ),
3900
			 JETPACK__VERSION . '-20121016'
3901
		);
3902
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3903
		wp_style_add_data( 'jetpack', 'suffix', $min );
3904
	}
3905
3906
	function plugin_action_links( $actions ) {
3907
3908
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3909
3910
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3911
			return array_merge(
3912
				$jetpack_home,
3913
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3914
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3915
				$actions
3916
				);
3917
			}
3918
3919
		return array_merge( $jetpack_home, $actions );
3920
	}
3921
3922
	/*
3923
	 * Registration flow:
3924
	 * 1 - ::admin_page_load() action=register
3925
	 * 2 - ::try_registration()
3926
	 * 3 - ::register()
3927
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3928
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3929
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3930
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3931
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3932
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3933
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3934
	 *       jetpack_id, jetpack_secret, jetpack_public
3935
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3936
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3937
	 * 5 - user logs in with WP.com account
3938
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3939
	 *		- Jetpack_Client_Server::authorize()
3940
	 *		- Jetpack_Client_Server::get_token()
3941
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3942
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3943
	 *			- which responds with access_token, token_type, scope
3944
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3945
	 *		- Jetpack::activate_default_modules()
3946
	 *     		- Deactivates deprecated plugins
3947
	 *     		- Activates all default modules
3948
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3949
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3950
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3951
	 *     Done!
3952
	 */
3953
3954
	/**
3955
	 * Handles the page load events for the Jetpack admin page
3956
	 */
3957
	function admin_page_load() {
3958
		$error = false;
3959
3960
		// Make sure we have the right body class to hook stylings for subpages off of.
3961
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3962
3963
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3964
			// Should only be used in intermediate redirects to preserve state across redirects
3965
			Jetpack::restate();
3966
		}
3967
3968
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3969
			// @todo: Add validation against a known whitelist
3970
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3971
			// User clicked in the iframe to link their accounts
3972
			if ( ! Jetpack::is_user_connected() ) {
3973
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3974
3975
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3976
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3977
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3978
3979
				if ( isset( $_GET['notes_iframe'] ) )
3980
					$connect_url .= '&notes_iframe';
3981
				wp_redirect( $connect_url );
3982
				exit;
3983
			} else {
3984
				if ( ! isset( $_GET['calypso_env'] ) ) {
3985
					Jetpack::state( 'message', 'already_authorized' );
3986
					wp_safe_redirect( Jetpack::admin_url() );
3987
					exit;
3988
				} else {
3989
					$connect_url = $this->build_connect_url( true, false, $from );
3990
					$connect_url .= '&already_authorized=true';
3991
					wp_redirect( $connect_url );
3992
					exit;
3993
				}
3994
			}
3995
		}
3996
3997
3998
		if ( isset( $_GET['action'] ) ) {
3999
			switch ( $_GET['action'] ) {
4000
			case 'authorize':
4001
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4002
					Jetpack::state( 'message', 'already_authorized' );
4003
					wp_safe_redirect( Jetpack::admin_url() );
4004
					exit;
4005
				}
4006
				Jetpack::log( 'authorize' );
4007
				$client_server = new Jetpack_Client_Server;
4008
				$client_server->client_authorize();
4009
				exit;
4010
			case 'register' :
4011
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4012
					$error = 'cheatin';
4013
					break;
4014
				}
4015
				check_admin_referer( 'jetpack-register' );
4016
				Jetpack::log( 'register' );
4017
				Jetpack::maybe_set_version_option();
4018
				$registered = Jetpack::try_registration();
4019
				if ( is_wp_error( $registered ) ) {
4020
					$error = $registered->get_error_code();
4021
					Jetpack::state( 'error', $error );
4022
					Jetpack::state( 'error', $registered->get_error_message() );
4023
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
4024
						'error_code' => $error,
4025
						'error_message' => $registered->get_error_message()
4026
					) );
4027
					break;
4028
				}
4029
4030
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4031
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4032
4033
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4034
					'from' => $from
4035
				) );
4036
4037
				$url = $this->build_connect_url( true, $redirect, $from );
4038
4039
				if ( ! empty( $_GET['onboarding'] ) ) {
4040
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4041
				}
4042
4043
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4044
					$url = add_query_arg( 'auth_approved', 'true', $url );
4045
				}
4046
4047
				wp_redirect( $url );
4048
				exit;
4049
			case 'activate' :
4050
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4051
					$error = 'cheatin';
4052
					break;
4053
				}
4054
4055
				$module = stripslashes( $_GET['module'] );
4056
				check_admin_referer( "jetpack_activate-$module" );
4057
				Jetpack::log( 'activate', $module );
4058
				if ( ! Jetpack::activate_module( $module ) ) {
4059
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4060
				}
4061
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4062
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4063
				exit;
4064
			case 'activate_default_modules' :
4065
				check_admin_referer( 'activate_default_modules' );
4066
				Jetpack::log( 'activate_default_modules' );
4067
				Jetpack::restate();
4068
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4069
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4070
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4071
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4072
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4073
				exit;
4074
			case 'disconnect' :
4075
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4076
					$error = 'cheatin';
4077
					break;
4078
				}
4079
4080
				check_admin_referer( 'jetpack-disconnect' );
4081
				Jetpack::log( 'disconnect' );
4082
				Jetpack::disconnect();
4083
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4084
				exit;
4085
			case 'reconnect' :
4086
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4087
					$error = 'cheatin';
4088
					break;
4089
				}
4090
4091
				check_admin_referer( 'jetpack-reconnect' );
4092
				Jetpack::log( 'reconnect' );
4093
				$this->disconnect();
4094
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4095
				exit;
4096 View Code Duplication
			case 'deactivate' :
4097
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4098
					$error = 'cheatin';
4099
					break;
4100
				}
4101
4102
				$modules = stripslashes( $_GET['module'] );
4103
				check_admin_referer( "jetpack_deactivate-$modules" );
4104
				foreach ( explode( ',', $modules ) as $module ) {
4105
					Jetpack::log( 'deactivate', $module );
4106
					Jetpack::deactivate_module( $module );
4107
					Jetpack::state( 'message', 'module_deactivated' );
4108
				}
4109
				Jetpack::state( 'module', $modules );
4110
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4111
				exit;
4112
			case 'unlink' :
4113
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4114
				check_admin_referer( 'jetpack-unlink' );
4115
				Jetpack::log( 'unlink' );
4116
				$this->unlink_user();
4117
				Jetpack::state( 'message', 'unlinked' );
4118
				if ( 'sub-unlink' == $redirect ) {
4119
					wp_safe_redirect( admin_url() );
4120
				} else {
4121
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4122
				}
4123
				exit;
4124
			case 'onboard' :
4125
				if ( ! current_user_can( 'manage_options' ) ) {
4126
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4127
				} else {
4128
					Jetpack::create_onboarding_token();
4129
					$url = $this->build_connect_url( true );
4130
4131
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4132
						$url = add_query_arg( 'onboarding', $token, $url );
4133
					}
4134
4135
					$calypso_env = $this->get_calypso_env();
4136
					if ( ! empty( $calypso_env ) ) {
4137
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4138
					}
4139
4140
					wp_redirect( $url );
4141
					exit;
4142
				}
4143
				exit;
4144
			default:
4145
				/**
4146
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4147
				 *
4148
				 * @since 2.6.0
4149
				 *
4150
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4151
				 */
4152
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4153
			}
4154
		}
4155
4156
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4157
			self::activate_new_modules( true );
4158
		}
4159
4160
		$message_code = Jetpack::state( 'message' );
4161
		if ( Jetpack::state( 'optin-manage' ) ) {
4162
			$activated_manage = $message_code;
4163
			$message_code = 'jetpack-manage';
4164
		}
4165
4166
		switch ( $message_code ) {
4167
		case 'jetpack-manage':
4168
			$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>';
4169
			if ( $activated_manage ) {
4170
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4171
			}
4172
			break;
4173
4174
		}
4175
4176
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4177
4178
		if ( ! empty( $deactivated_plugins ) ) {
4179
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4180
			$deactivated_titles  = array();
4181
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4182
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4183
					continue;
4184
				}
4185
4186
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4187
			}
4188
4189
			if ( $deactivated_titles ) {
4190
				if ( $this->message ) {
4191
					$this->message .= "<br /><br />\n";
4192
				}
4193
4194
				$this->message .= wp_sprintf(
4195
					_n(
4196
						'Jetpack contains the most recent version of the old %l plugin.',
4197
						'Jetpack contains the most recent versions of the old %l plugins.',
4198
						count( $deactivated_titles ),
4199
						'jetpack'
4200
					),
4201
					$deactivated_titles
4202
				);
4203
4204
				$this->message .= "<br />\n";
4205
4206
				$this->message .= _n(
4207
					'The old version has been deactivated and can be removed from your site.',
4208
					'The old versions have been deactivated and can be removed from your site.',
4209
					count( $deactivated_titles ),
4210
					'jetpack'
4211
				);
4212
			}
4213
		}
4214
4215
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4216
4217
		if ( $this->message || $this->error || $this->privacy_checks ) {
4218
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4219
		}
4220
4221
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4222
	}
4223
4224
	function admin_notices() {
4225
4226
		if ( $this->error ) {
4227
?>
4228
<div id="message" class="jetpack-message jetpack-err">
4229
	<div class="squeezer">
4230
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4231
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4232
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4233
<?php	endif; ?>
4234
	</div>
4235
</div>
4236
<?php
4237
		}
4238
4239
		if ( $this->message ) {
4240
?>
4241
<div id="message" class="jetpack-message">
4242
	<div class="squeezer">
4243
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4244
	</div>
4245
</div>
4246
<?php
4247
		}
4248
4249
		if ( $this->privacy_checks ) :
4250
			$module_names = $module_slugs = array();
4251
4252
			$privacy_checks = explode( ',', $this->privacy_checks );
4253
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4254
			foreach ( $privacy_checks as $module_slug ) {
4255
				$module = Jetpack::get_module( $module_slug );
4256
				if ( ! $module ) {
4257
					continue;
4258
				}
4259
4260
				$module_slugs[] = $module_slug;
4261
				$module_names[] = "<strong>{$module['name']}</strong>";
4262
			}
4263
4264
			$module_slugs = join( ',', $module_slugs );
4265
?>
4266
<div id="message" class="jetpack-message jetpack-err">
4267
	<div class="squeezer">
4268
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4269
		<p><?php
4270
			echo wp_kses(
4271
				wptexturize(
4272
					wp_sprintf(
4273
						_nx(
4274
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4275
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4276
							count( $privacy_checks ),
4277
							'%l = list of Jetpack module/feature names',
4278
							'jetpack'
4279
						),
4280
						$module_names
4281
					)
4282
				),
4283
				array( 'strong' => true )
4284
			);
4285
4286
			echo "\n<br />\n";
4287
4288
			echo wp_kses(
4289
				sprintf(
4290
					_nx(
4291
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4292
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4293
						count( $privacy_checks ),
4294
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4295
						'jetpack'
4296
					),
4297
					wp_nonce_url(
4298
						Jetpack::admin_url(
4299
							array(
4300
								'page'   => 'jetpack',
4301
								'action' => 'deactivate',
4302
								'module' => urlencode( $module_slugs ),
4303
							)
4304
						),
4305
						"jetpack_deactivate-$module_slugs"
4306
					),
4307
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4308
				),
4309
				array( 'a' => array( 'href' => true, 'title' => true ) )
4310
			);
4311
		?></p>
4312
	</div>
4313
</div>
4314
<?php endif;
4315
	}
4316
4317
	/**
4318
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4319
	 */
4320
	function stat( $group, $detail ) {
4321
		if ( ! isset( $this->stats[ $group ] ) )
4322
			$this->stats[ $group ] = array();
4323
		$this->stats[ $group ][] = $detail;
4324
	}
4325
4326
	/**
4327
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4328
	 */
4329
	function do_stats( $method = '' ) {
4330
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4331
			foreach ( $this->stats as $group => $stats ) {
4332
				if ( is_array( $stats ) && count( $stats ) ) {
4333
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4334
					if ( 'server_side' === $method ) {
4335
						self::do_server_side_stat( $args );
4336
					} else {
4337
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4338
					}
4339
				}
4340
				unset( $this->stats[ $group ] );
4341
			}
4342
		}
4343
	}
4344
4345
	/**
4346
	 * Runs stats code for a one-off, server-side.
4347
	 *
4348
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4349
	 *
4350
	 * @return bool If it worked.
4351
	 */
4352
	static function do_server_side_stat( $args ) {
4353
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4354
		if ( is_wp_error( $response ) )
4355
			return false;
4356
4357
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4358
			return false;
4359
4360
		return true;
4361
	}
4362
4363
	/**
4364
	 * Builds the stats url.
4365
	 *
4366
	 * @param $args array|string The arguments to append to the URL.
4367
	 *
4368
	 * @return string The URL to be pinged.
4369
	 */
4370
	static function build_stats_url( $args ) {
4371
		$defaults = array(
4372
			'v'    => 'wpcom2',
4373
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4374
		);
4375
		$args     = wp_parse_args( $args, $defaults );
4376
		/**
4377
		 * Filter the URL used as the Stats tracking pixel.
4378
		 *
4379
		 * @since 2.3.2
4380
		 *
4381
		 * @param string $url Base URL used as the Stats tracking pixel.
4382
		 */
4383
		$base_url = apply_filters(
4384
			'jetpack_stats_base_url',
4385
			'https://pixel.wp.com/g.gif'
4386
		);
4387
		$url      = add_query_arg( $args, $base_url );
4388
		return $url;
4389
	}
4390
4391
	static function translate_current_user_to_role() {
4392
		foreach ( self::$capability_translations as $role => $cap ) {
4393
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4394
				return $role;
4395
			}
4396
		}
4397
4398
		return false;
4399
	}
4400
4401
	static function translate_user_to_role( $user ) {
4402
		foreach ( self::$capability_translations as $role => $cap ) {
4403
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4404
				return $role;
4405
			}
4406
		}
4407
4408
		return false;
4409
    }
4410
4411
	static function translate_role_to_cap( $role ) {
4412
		if ( ! isset( self::$capability_translations[$role] ) ) {
4413
			return false;
4414
		}
4415
4416
		return self::$capability_translations[$role];
4417
	}
4418
4419
	static function sign_role( $role, $user_id = null ) {
4420
		if ( empty( $user_id ) ) {
4421
			$user_id = (int) get_current_user_id();
4422
		}
4423
4424
		if ( ! $user_id  ) {
4425
			return false;
4426
		}
4427
4428
		$token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4429
		if ( ! $token || is_wp_error( $token ) ) {
4430
			return false;
4431
		}
4432
4433
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4434
	}
4435
4436
4437
	/**
4438
	 * Builds a URL to the Jetpack connection auth page
4439
	 *
4440
	 * @since 3.9.5
4441
	 *
4442
	 * @param bool $raw If true, URL will not be escaped.
4443
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4444
	 *                              If string, will be a custom redirect.
4445
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4446
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4447
	 *
4448
	 * @return string Connect URL
4449
	 */
4450
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4451
		$site_id = Jetpack_Options::get_option( 'id' );
4452
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4453
4454
		if ( $register || ! $blog_token || ! $site_id ) {
4455
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4456
4457
			if ( ! empty( $redirect ) ) {
4458
				$url = add_query_arg(
4459
					'redirect',
4460
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4461
					$url
4462
				);
4463
			}
4464
4465
			if( is_network_admin() ) {
4466
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4467
			}
4468
		} else {
4469
4470
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4471
			// because otherwise this logic can get us in to a loop.
4472
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4473
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4474
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4475
4476
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4477
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4478
					'1.1'
4479
				);
4480
4481
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4482
4483
					// Generating a register URL instead to refresh the existing token
4484
					return $this->build_connect_url( $raw, $redirect, $from, true );
4485
				}
4486
			}
4487
4488
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4489
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4490
			}
4491
4492
			$role = self::translate_current_user_to_role();
4493
			$signed_role = self::sign_role( $role );
4494
4495
			$user = wp_get_current_user();
4496
4497
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4498
			$redirect = $redirect
4499
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4500
				: $jetpack_admin_page;
4501
4502
			if( isset( $_REQUEST['is_multisite'] ) ) {
4503
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4504
			}
4505
4506
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4507
4508
			/**
4509
			 * Filter the type of authorization.
4510
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4511
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4512
			 *
4513
			 * @since 4.3.3
4514
			 *
4515
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4516
			 */
4517
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4518
4519
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4520
4521
			$args = urlencode_deep(
4522
				array(
4523
					'response_type' => 'code',
4524
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4525
					'redirect_uri'  => add_query_arg(
4526
						array(
4527
							'action'   => 'authorize',
4528
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4529
							'redirect' => urlencode( $redirect ),
4530
						),
4531
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4532
					),
4533
					'state'         => $user->ID,
4534
					'scope'         => $signed_role,
4535
					'user_email'    => $user->user_email,
4536
					'user_login'    => $user->user_login,
4537
					'is_active'     => Jetpack::is_active(),
4538
					'jp_version'    => JETPACK__VERSION,
4539
					'auth_type'     => $auth_type,
4540
					'secret'        => $secrets['secret_1'],
4541
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4542
					'blogname'      => get_option( 'blogname' ),
4543
					'site_url'      => site_url(),
4544
					'home_url'      => home_url(),
4545
					'site_icon'     => get_site_icon_url(),
4546
					'site_lang'     => get_locale(),
4547
					'_ui'           => $tracks_identity['_ui'],
4548
					'_ut'           => $tracks_identity['_ut'],
4549
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4550
				)
4551
			);
4552
4553
			self::apply_activation_source_to_args( $args );
4554
4555
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4556
		}
4557
4558
		if ( $from ) {
4559
			$url = add_query_arg( 'from', $from, $url );
4560
		}
4561
4562
		// Ensure that class to get the affiliate code is loaded
4563
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4564
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4565
		}
4566
		// Get affiliate code and add it to the URL
4567
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4568
4569
		$calypso_env = $this->get_calypso_env();
4570
4571
		if ( ! empty( $calypso_env ) ) {
4572
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4573
		}
4574
4575
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4576
	}
4577
4578
	/**
4579
	 * Get our assumed site creation date.
4580
	 * Calculated based on the earlier date of either:
4581
	 * - Earliest admin user registration date.
4582
	 * - Earliest date of post of any post type.
4583
	 *
4584
	 * @since 7.2.0
4585
	 *
4586
	 * @return string Assumed site creation date and time.
4587
	 */
4588
	public static function get_assumed_site_creation_date() {
4589
		$earliest_registered_users = get_users( array(
4590
			'role'    => 'administrator',
4591
			'orderby' => 'user_registered',
4592
			'order'   => 'ASC',
4593
			'fields'  => array( 'user_registered' ),
4594
			'number'  => 1,
4595
		) );
4596
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4597
4598
		$earliest_posts = get_posts( array(
4599
			'posts_per_page' => 1,
4600
			'post_type'      => 'any',
4601
			'post_status'    => 'any',
4602
			'orderby'        => 'date',
4603
			'order'          => 'ASC',
4604
		) );
4605
4606
		// If there are no posts at all, we'll count only on user registration date.
4607
		if ( $earliest_posts ) {
4608
			$earliest_post_date = $earliest_posts[0]->post_date;
4609
		} else {
4610
			$earliest_post_date = PHP_INT_MAX;
4611
		}
4612
4613
		return min( $earliest_registration_date, $earliest_post_date );
4614
	}
4615
4616
	public static function apply_activation_source_to_args( &$args ) {
4617
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4618
4619
		if ( $activation_source_name ) {
4620
			$args['_as'] = urlencode( $activation_source_name );
4621
		}
4622
4623
		if ( $activation_source_keyword ) {
4624
			$args['_ak'] = urlencode( $activation_source_keyword );
4625
		}
4626
	}
4627
4628
	function build_reconnect_url( $raw = false ) {
4629
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4630
		return $raw ? $url : esc_url( $url );
4631
	}
4632
4633
	public static function admin_url( $args = null ) {
4634
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4635
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4636
		return $url;
4637
	}
4638
4639
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4640
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4641
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4642
	}
4643
4644
	function dismiss_jetpack_notice() {
4645
4646
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4647
			return;
4648
		}
4649
4650
		switch( $_GET['jetpack-notice'] ) {
4651
			case 'dismiss':
4652
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4653
4654
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4655
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4656
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4657
				}
4658
				break;
4659
			case 'jetpack-protect-multisite-opt-out':
4660
4661
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4662
					// Don't show the banner again
4663
4664
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4665
					// redirect back to the page that had the notice
4666
					if ( wp_get_referer() ) {
4667
						wp_safe_redirect( wp_get_referer() );
4668
					} else {
4669
						// Take me to Jetpack
4670
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4671
					}
4672
				}
4673
				break;
4674
		}
4675
	}
4676
4677
	public static function sort_modules( $a, $b ) {
4678
		if ( $a['sort'] == $b['sort'] )
4679
			return 0;
4680
4681
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4682
	}
4683
4684
	function ajax_recheck_ssl() {
4685
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4686
		$result = Jetpack::permit_ssl( true );
4687
		wp_send_json( array(
4688
			'enabled' => $result,
4689
			'message' => get_transient( 'jetpack_https_test_message' )
4690
		) );
4691
	}
4692
4693
/* Client API */
4694
4695
	/**
4696
	 * Returns the requested Jetpack API URL
4697
	 *
4698
	 * @return string
4699
	 */
4700
	public static function api_url( $relative_url ) {
4701
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4702
	}
4703
4704
	/**
4705
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4706
	 */
4707
	public static function fix_url_for_bad_hosts( $url ) {
4708
		if ( 0 !== strpos( $url, 'https://' ) ) {
4709
			return $url;
4710
		}
4711
4712
		switch ( JETPACK_CLIENT__HTTPS ) {
4713
			case 'ALWAYS' :
4714
				return $url;
4715
			case 'NEVER' :
4716
				return set_url_scheme( $url, 'http' );
4717
			// default : case 'AUTO' :
4718
		}
4719
4720
		// we now return the unmodified SSL URL by default, as a security precaution
4721
		return $url;
4722
	}
4723
4724
	/**
4725
	 * Create a random secret for validating onboarding payload
4726
	 *
4727
	 * @return string Secret token
4728
	 */
4729
	public static function create_onboarding_token() {
4730
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4731
			$token = wp_generate_password( 32, false );
4732
			Jetpack_Options::update_option( 'onboarding', $token );
4733
		}
4734
4735
		return $token;
4736
	}
4737
4738
	/**
4739
	 * Remove the onboarding token
4740
	 *
4741
	 * @return bool True on success, false on failure
4742
	 */
4743
	public static function invalidate_onboarding_token() {
4744
		return Jetpack_Options::delete_option( 'onboarding' );
4745
	}
4746
4747
	/**
4748
	 * Validate an onboarding token for a specific action
4749
	 *
4750
	 * @return boolean True if token/action pair is accepted, false if not
4751
	 */
4752
	public static function validate_onboarding_token_action( $token, $action ) {
4753
		// Compare tokens, bail if tokens do not match
4754
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4755
			return false;
4756
		}
4757
4758
		// List of valid actions we can take
4759
		$valid_actions = array(
4760
			'/jetpack/v4/settings',
4761
		);
4762
4763
		// Whitelist the action
4764
		if ( ! in_array( $action, $valid_actions ) ) {
4765
			return false;
4766
		}
4767
4768
		return true;
4769
	}
4770
4771
	/**
4772
	 * Checks to see if the URL is using SSL to connect with Jetpack
4773
	 *
4774
	 * @since 2.3.3
4775
	 * @return boolean
4776
	 */
4777
	public static function permit_ssl( $force_recheck = false ) {
4778
		// Do some fancy tests to see if ssl is being supported
4779
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4780
			$message = '';
4781
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4782
				$ssl = 0;
4783
			} else {
4784
				switch ( JETPACK_CLIENT__HTTPS ) {
4785
					case 'NEVER':
4786
						$ssl = 0;
4787
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4788
						break;
4789
					case 'ALWAYS':
4790
					case 'AUTO':
4791
					default:
4792
						$ssl = 1;
4793
						break;
4794
				}
4795
4796
				// If it's not 'NEVER', test to see
4797
				if ( $ssl ) {
4798
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4799
						$ssl = 0;
4800
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4801
					} else {
4802
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4803
						if ( is_wp_error( $response ) ) {
4804
							$ssl = 0;
4805
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4806
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4807
							$ssl = 0;
4808
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4809
						}
4810
					}
4811
				}
4812
			}
4813
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4814
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4815
		}
4816
4817
		return (bool) $ssl;
4818
	}
4819
4820
	/*
4821
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4822
	 */
4823
	public function alert_auto_ssl_fail() {
4824
		if ( ! current_user_can( 'manage_options' ) )
4825
			return;
4826
4827
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4828
		?>
4829
4830
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4831
			<div class="jp-banner__content">
4832
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4833
				<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>
4834
				<p>
4835
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4836
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4837
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4838
				</p>
4839
				<p>
4840
					<?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' ),
4841
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4842
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4843
				</p>
4844
			</div>
4845
		</div>
4846
		<style>
4847
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4848
		</style>
4849
		<script type="text/javascript">
4850
			jQuery( document ).ready( function( $ ) {
4851
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4852
					var $this = $( this );
4853
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4854
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4855
					e.preventDefault();
4856
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4857
					$.post( ajaxurl, data )
4858
					  .done( function( response ) {
4859
					  	if ( response.enabled ) {
4860
					  		$( '#jetpack-ssl-warning' ).hide();
4861
					  	} else {
4862
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4863
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4864
					  	}
4865
					  }.bind( $this ) );
4866
				} );
4867
			} );
4868
		</script>
4869
4870
		<?php
4871
	}
4872
4873
	/**
4874
	 * Returns the Jetpack XML-RPC API
4875
	 *
4876
	 * @return string
4877
	 */
4878
	public static function xmlrpc_api_url() {
4879
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4880
		return untrailingslashit( $base ) . '/xmlrpc.php';
4881
	}
4882
4883
	public static function connection() {
4884
		return self::init()->connection_manager;
4885
	}
4886
4887
	/**
4888
	 * Creates two secret tokens and the end of life timestamp for them.
4889
	 *
4890
	 * Note these tokens are unique per call, NOT static per site for connecting.
4891
	 *
4892
	 * @since 2.6
4893
	 * @return array
4894
	 */
4895
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4896
		if ( false === $user_id ) {
4897
			$user_id = get_current_user_id();
4898
		}
4899
4900
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4901
	}
4902
4903
	public static function get_secrets( $action, $user_id ) {
4904
		$secrets = self::connection()->get_secrets( $action, $user_id );
4905
4906
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4907
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4908
		}
4909
4910
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4911
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4912
		}
4913
4914
		return $secrets;
4915
	}
4916
4917
	/**
4918
	 * @deprecated 7.5 Use Connection_Manager instead.
4919
	 *
4920
	 * @param $action
4921
	 * @param $user_id
4922
	 */
4923
	public static function delete_secrets( $action, $user_id ) {
4924
		return self::connection()->delete_secrets( $action, $user_id );
4925
	}
4926
4927
	/**
4928
	 * Builds the timeout limit for queries talking with the wpcom servers.
4929
	 *
4930
	 * Based on local php max_execution_time in php.ini
4931
	 *
4932
	 * @since 2.6
4933
	 * @return int
4934
	 * @deprecated
4935
	 **/
4936
	public function get_remote_query_timeout_limit() {
4937
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4938
		return Jetpack::get_max_execution_time();
4939
	}
4940
4941
	/**
4942
	 * Builds the timeout limit for queries talking with the wpcom servers.
4943
	 *
4944
	 * Based on local php max_execution_time in php.ini
4945
	 *
4946
	 * @since 5.4
4947
	 * @return int
4948
	 **/
4949
	public static function get_max_execution_time() {
4950
		$timeout = (int) ini_get( 'max_execution_time' );
4951
4952
		// Ensure exec time set in php.ini
4953
		if ( ! $timeout ) {
4954
			$timeout = 30;
4955
		}
4956
		return $timeout;
4957
	}
4958
4959
	/**
4960
	 * Sets a minimum request timeout, and returns the current timeout
4961
	 *
4962
	 * @since 5.4
4963
	 **/
4964
	public static function set_min_time_limit( $min_timeout ) {
4965
		$timeout = self::get_max_execution_time();
4966
		if ( $timeout < $min_timeout ) {
4967
			$timeout = $min_timeout;
4968
			set_time_limit( $timeout );
4969
		}
4970
		return $timeout;
4971
	}
4972
4973
4974
	/**
4975
	 * Takes the response from the Jetpack register new site endpoint and
4976
	 * verifies it worked properly.
4977
	 *
4978
	 * @since 2.6
4979
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4980
	 **/
4981
	public function validate_remote_register_response( $response ) {
4982
	  if ( is_wp_error( $response ) ) {
4983
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4984
		}
4985
4986
		$code   = wp_remote_retrieve_response_code( $response );
4987
		$entity = wp_remote_retrieve_body( $response );
4988
		if ( $entity )
4989
			$registration_response = json_decode( $entity );
4990
		else
4991
			$registration_response = false;
4992
4993
		$code_type = intval( $code / 100 );
4994
		if ( 5 == $code_type ) {
4995
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4996
		} elseif ( 408 == $code ) {
4997
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4998
		} elseif ( ! empty( $registration_response->error ) ) {
4999
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5000
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
5001
			} else {
5002
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5003
			}
5004
5005
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5006
		} elseif ( 200 != $code ) {
5007
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5008
		}
5009
5010
		// Jetpack ID error block
5011
		if ( empty( $registration_response->jetpack_id ) ) {
5012
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5013
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5014
			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 );
5015
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5016
			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 );
5017
		}
5018
5019
	    return $registration_response;
5020
	}
5021
	/**
5022
	 * @return bool|WP_Error
5023
	 */
5024
	public static function register() {
5025
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5026
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5027
		$secrets = Jetpack::generate_secrets( 'register' );
5028
5029 View Code Duplication
		if (
5030
			empty( $secrets['secret_1'] ) ||
5031
			empty( $secrets['secret_2'] ) ||
5032
			empty( $secrets['exp'] )
5033
		) {
5034
			return new Jetpack_Error( 'missing_secrets' );
5035
		}
5036
5037
		// better to try (and fail) to set a higher timeout than this system
5038
		// supports than to have register fail for more users than it should
5039
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5040
5041
		$gmt_offset = get_option( 'gmt_offset' );
5042
		if ( ! $gmt_offset ) {
5043
			$gmt_offset = 0;
5044
		}
5045
5046
		$stats_options = get_option( 'stats_options' );
5047
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5048
5049
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5050
5051
		$args = array(
5052
			'method'  => 'POST',
5053
			'body'    => array(
5054
				'siteurl'         => site_url(),
5055
				'home'            => home_url(),
5056
				'gmt_offset'      => $gmt_offset,
5057
				'timezone_string' => (string) get_option( 'timezone_string' ),
5058
				'site_name'       => (string) get_option( 'blogname' ),
5059
				'secret_1'        => $secrets['secret_1'],
5060
				'secret_2'        => $secrets['secret_2'],
5061
				'site_lang'       => get_locale(),
5062
				'timeout'         => $timeout,
5063
				'stats_id'        => $stats_id,
5064
				'state'           => get_current_user_id(),
5065
				'_ui'             => $tracks_identity['_ui'],
5066
				'_ut'             => $tracks_identity['_ut'],
5067
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5068
				'jetpack_version' => JETPACK__VERSION
5069
			),
5070
			'headers' => array(
5071
				'Accept' => 'application/json',
5072
			),
5073
			'timeout' => $timeout,
5074
		);
5075
5076
		self::apply_activation_source_to_args( $args['body'] );
5077
5078
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5079
5080
		// Make sure the response is valid and does not contain any Jetpack errors
5081
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5082
		if ( is_wp_error( $registration_details ) ) {
5083
			return $registration_details;
5084
		} elseif ( ! $registration_details ) {
5085
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5086
		}
5087
5088 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5089
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5090
		}
5091
5092
		if ( isset( $registration_details->jetpack_public ) ) {
5093
			$jetpack_public = (int) $registration_details->jetpack_public;
5094
		} else {
5095
			$jetpack_public = false;
5096
		}
5097
5098
		Jetpack_Options::update_options(
5099
			array(
5100
				'id'         => (int)    $registration_details->jetpack_id,
5101
				'blog_token' => (string) $registration_details->jetpack_secret,
5102
				'public'     => $jetpack_public,
5103
			)
5104
		);
5105
5106
		/**
5107
		 * Fires when a site is registered on WordPress.com.
5108
		 *
5109
		 * @since 3.7.0
5110
		 *
5111
		 * @param int $json->jetpack_id Jetpack Blog ID.
5112
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5113
		 * @param int|bool $jetpack_public Is the site public.
5114
		 */
5115
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5116
5117
		// Initialize Jump Start for the first and only time.
5118
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5119
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5120
5121
			$jetpack = Jetpack::init();
5122
5123
			$jetpack->stat( 'jumpstart', 'unique-views' );
5124
			$jetpack->do_stats( 'server_side' );
5125
		};
5126
5127
		return true;
5128
	}
5129
5130
	/**
5131
	 * If the db version is showing something other that what we've got now, bump it to current.
5132
	 *
5133
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5134
	 */
5135
	public static function maybe_set_version_option() {
5136
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5137
		if ( JETPACK__VERSION != $version ) {
5138
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5139
5140
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5141
				/** This action is documented in class.jetpack.php */
5142
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5143
			}
5144
5145
			return true;
5146
		}
5147
		return false;
5148
	}
5149
5150
/* Client Server API */
5151
5152
	/**
5153
	 * Loads the Jetpack XML-RPC client
5154
	 */
5155
	public static function load_xml_rpc_client() {
5156
		require_once ABSPATH . WPINC . '/class-IXR.php';
5157
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5158
	}
5159
5160
	/**
5161
	 * Resets the saved authentication state in between testing requests.
5162
	 */
5163
	public function reset_saved_auth_state() {
5164
		$this->xmlrpc_verification = null;
5165
		$this->rest_authentication_status = null;
5166
	}
5167
5168
	function verify_xml_rpc_signature() {
5169
		if ( $this->xmlrpc_verification ) {
5170
			return $this->xmlrpc_verification;
5171
		}
5172
5173
		// It's not for us
5174
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5175
			return false;
5176
		}
5177
5178
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
5179
		if (
5180
			empty( $token_key )
5181
		||
5182
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5183
		) {
5184
			return false;
5185
		}
5186
5187
		if ( '0' === $user_id ) {
5188
			$token_type = 'blog';
5189
			$user_id = 0;
5190
		} else {
5191
			$token_type = 'user';
5192
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5193
				return false;
5194
			}
5195
			$user_id = (int) $user_id;
5196
5197
			$user = new WP_User( $user_id );
5198
			if ( ! $user || ! $user->exists() ) {
5199
				return false;
5200
			}
5201
		}
5202
5203
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
0 ignored issues
show
$user_id is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
5204
		if ( ! $token ) {
5205
			return false;
5206
		}
5207
5208
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5209
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5210
			$post_data   = $_POST;
5211
			$file_hashes = array();
5212
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5213
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5214
					continue;
5215
				}
5216
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5217
				$file_hashes[$post_data_key] = $post_data_value;
5218
			}
5219
5220
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5221
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5222
				$post_data[$post_data_key] = $post_data_value;
5223
			}
5224
5225
			ksort( $post_data );
5226
5227
			$body = http_build_query( stripslashes_deep( $post_data ) );
5228
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5229
			$body = file_get_contents( 'php://input' );
5230
		} else {
5231
			$body = null;
5232
		}
5233
5234
		$signature = $jetpack_signature->sign_current_request(
5235
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5236
		);
5237
5238
		if ( ! $signature ) {
5239
			return false;
5240
		} else if ( is_wp_error( $signature ) ) {
5241
			return $signature;
5242
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5243
			return false;
5244
		}
5245
5246
		$timestamp = (int) $_GET['timestamp'];
5247
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5248
5249
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5250
			return false;
5251
		}
5252
5253
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5254
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5255
			if ( ! empty( $_GET['onboarding'] ) ) {
5256
				$jpo = $_GET;
5257
			} else {
5258
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5259
			}
5260
5261
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5262
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5263
5264
			if (
5265
				isset( $jpo_user ) && isset( $jpo_token ) &&
5266
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5267
				isset( $_GET['rest_route'] ) &&
5268
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5269
			) {
5270
				$jpUser = get_user_by( 'email', $jpo_user );
5271
				if ( is_a( $jpUser, 'WP_User' ) ) {
5272
					wp_set_current_user( $jpUser->ID );
5273
					$user_can = is_multisite()
5274
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5275
						: current_user_can( 'manage_options' );
5276
					if ( $user_can ) {
5277
						$token_type = 'user';
5278
						$token->external_user_id = $jpUser->ID;
5279
					}
5280
				}
5281
			}
5282
		}
5283
5284
		$this->xmlrpc_verification = array(
5285
			'type'      => $token_type,
5286
			'token_key' => $token_key,
5287
			'user_id'   => $token->external_user_id,
5288
		);
5289
5290
		return $this->xmlrpc_verification;
5291
	}
5292
5293
	/**
5294
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5295
	 */
5296
	function authenticate_jetpack( $user, $username, $password ) {
5297
		if ( is_a( $user, 'WP_User' ) ) {
5298
			return $user;
5299
		}
5300
5301
		$token_details = $this->verify_xml_rpc_signature();
5302
5303
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5304
			return $user;
5305
		}
5306
5307
		if ( 'user' !== $token_details['type'] ) {
5308
			return $user;
5309
		}
5310
5311
		if ( ! $token_details['user_id'] ) {
5312
			return $user;
5313
		}
5314
5315
		nocache_headers();
5316
5317
		return new WP_User( $token_details['user_id'] );
5318
	}
5319
5320
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5321
	// Uses the existing XMLRPC request signing implementation.
5322
	function wp_rest_authenticate( $user ) {
5323
		if ( ! empty( $user ) ) {
5324
			// Another authentication method is in effect.
5325
			return $user;
5326
		}
5327
5328
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5329
			// Nothing to do for this authentication method.
5330
			return null;
5331
		}
5332
5333
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5334
			// Nothing to do for this authentication method.
5335
			return null;
5336
		}
5337
5338
		// Ensure that we always have the request body available.  At this
5339
		// point, the WP REST API code to determine the request body has not
5340
		// run yet.  That code may try to read from 'php://input' later, but
5341
		// this can only be done once per request in PHP versions prior to 5.6.
5342
		// So we will go ahead and perform this read now if needed, and save
5343
		// the request body where both the Jetpack signature verification code
5344
		// and the WP REST API code can see it.
5345
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5346
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5347
		}
5348
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5349
5350
		// Only support specific request parameters that have been tested and
5351
		// are known to work with signature verification.  A different method
5352
		// can be passed to the WP REST API via the '?_method=' parameter if
5353
		// needed.
5354
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5355
			$this->rest_authentication_status = new WP_Error(
5356
				'rest_invalid_request',
5357
				__( 'This request method is not supported.', 'jetpack' ),
5358
				array( 'status' => 400 )
5359
			);
5360
			return null;
5361
		}
5362
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5363
			$this->rest_authentication_status = new WP_Error(
5364
				'rest_invalid_request',
5365
				__( 'This request method does not support body parameters.', 'jetpack' ),
5366
				array( 'status' => 400 )
5367
			);
5368
			return null;
5369
		}
5370
5371
		$verified = $this->verify_xml_rpc_signature();
5372
5373
		if ( is_wp_error( $verified ) ) {
5374
			$this->rest_authentication_status = $verified;
5375
			return null;
5376
		}
5377
5378
		if (
5379
			$verified &&
5380
			isset( $verified['type'] ) &&
5381
			'user' === $verified['type'] &&
5382
			! empty( $verified['user_id'] )
5383
		) {
5384
			// Authentication successful.
5385
			$this->rest_authentication_status = true;
5386
			return $verified['user_id'];
5387
		}
5388
5389
		// Something else went wrong.  Probably a signature error.
5390
		$this->rest_authentication_status = new WP_Error(
5391
			'rest_invalid_signature',
5392
			__( 'The request is not signed correctly.', 'jetpack' ),
5393
			array( 'status' => 400 )
5394
		);
5395
		return null;
5396
	}
5397
5398
	/**
5399
	 * Report authentication status to the WP REST API.
5400
	 *
5401
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5402
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5403
	 */
5404
	public function wp_rest_authentication_errors( $value ) {
5405
		if ( $value !== null ) {
5406
			return $value;
5407
		}
5408
		return $this->rest_authentication_status;
5409
	}
5410
5411
	function add_nonce( $timestamp, $nonce ) {
5412
		global $wpdb;
5413
		static $nonces_used_this_request = array();
5414
5415
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5416
			return $nonces_used_this_request["$timestamp:$nonce"];
5417
		}
5418
5419
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5420
		$timestamp = (int) $timestamp;
5421
		$nonce     = esc_sql( $nonce );
5422
5423
		// Raw query so we can avoid races: add_option will also update
5424
		$show_errors = $wpdb->show_errors( false );
5425
5426
		$old_nonce = $wpdb->get_row(
5427
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5428
		);
5429
5430
		if ( is_null( $old_nonce ) ) {
5431
			$return = $wpdb->query(
5432
				$wpdb->prepare(
5433
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5434
					"jetpack_nonce_{$timestamp}_{$nonce}",
5435
					time(),
5436
					'no'
5437
				)
5438
			);
5439
		} else {
5440
			$return = false;
5441
		}
5442
5443
		$wpdb->show_errors( $show_errors );
5444
5445
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5446
5447
		return $return;
5448
	}
5449
5450
	/**
5451
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5452
	 * Capture it here so we can verify the signature later.
5453
	 */
5454
	function xmlrpc_methods( $methods ) {
5455
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5456
		return $methods;
5457
	}
5458
5459
	function public_xmlrpc_methods( $methods ) {
5460
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5461
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5462
		}
5463
		return $methods;
5464
	}
5465
5466
	function jetpack_getOptions( $args ) {
5467
		global $wp_xmlrpc_server;
5468
5469
		$wp_xmlrpc_server->escape( $args );
5470
5471
		$username	= $args[1];
5472
		$password	= $args[2];
5473
5474
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5475
			return $wp_xmlrpc_server->error;
5476
		}
5477
5478
		$options = array();
5479
		$user_data = $this->get_connected_user_data();
5480
		if ( is_array( $user_data ) ) {
5481
			$options['jetpack_user_id'] = array(
5482
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5483
				'readonly'      => true,
5484
				'value'         => $user_data['ID'],
5485
			);
5486
			$options['jetpack_user_login'] = array(
5487
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5488
				'readonly'      => true,
5489
				'value'         => $user_data['login'],
5490
			);
5491
			$options['jetpack_user_email'] = array(
5492
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5493
				'readonly'      => true,
5494
				'value'         => $user_data['email'],
5495
			);
5496
			$options['jetpack_user_site_count'] = array(
5497
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5498
				'readonly'      => true,
5499
				'value'         => $user_data['site_count'],
5500
			);
5501
		}
5502
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5503
		$args = stripslashes_deep( $args );
5504
		return $wp_xmlrpc_server->wp_getOptions( $args );
5505
	}
5506
5507
	function xmlrpc_options( $options ) {
5508
		$jetpack_client_id = false;
5509
		if ( self::is_active() ) {
5510
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5511
		}
5512
		$options['jetpack_version'] = array(
5513
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5514
				'readonly'      => true,
5515
				'value'         => JETPACK__VERSION,
5516
		);
5517
5518
		$options['jetpack_client_id'] = array(
5519
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5520
				'readonly'      => true,
5521
				'value'         => $jetpack_client_id,
5522
		);
5523
		return $options;
5524
	}
5525
5526
	public static function clean_nonces( $all = false ) {
5527
		global $wpdb;
5528
5529
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5530
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5531
5532
		if ( true !== $all ) {
5533
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5534
			$sql_args[] = time() - 3600;
5535
		}
5536
5537
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5538
5539
		$sql = $wpdb->prepare( $sql, $sql_args );
5540
5541
		for ( $i = 0; $i < 1000; $i++ ) {
5542
			if ( ! $wpdb->query( $sql ) ) {
5543
				break;
5544
			}
5545
		}
5546
	}
5547
5548
	/**
5549
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5550
	 * SET: state( $key, $value );
5551
	 * GET: $value = state( $key );
5552
	 *
5553
	 * @param string $key
5554
	 * @param string $value
5555
	 * @param bool $restate private
5556
	 */
5557
	public static function state( $key = null, $value = null, $restate = false ) {
5558
		static $state = array();
5559
		static $path, $domain;
5560
		if ( ! isset( $path ) ) {
5561
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5562
			$admin_url = Jetpack::admin_url();
5563
			$bits      = wp_parse_url( $admin_url );
5564
5565
			if ( is_array( $bits ) ) {
5566
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5567
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5568
			} else {
5569
				$path = $domain = null;
5570
			}
5571
		}
5572
5573
		// Extract state from cookies and delete cookies
5574
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5575
			$yum = $_COOKIE[ 'jetpackState' ];
5576
			unset( $_COOKIE[ 'jetpackState' ] );
5577
			foreach ( $yum as $k => $v ) {
5578
				if ( strlen( $v ) )
5579
					$state[ $k ] = $v;
5580
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5581
			}
5582
		}
5583
5584
		if ( $restate ) {
5585
			foreach ( $state as $k => $v ) {
5586
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5587
			}
5588
			return;
5589
		}
5590
5591
		// Get a state variable
5592
		if ( isset( $key ) && ! isset( $value ) ) {
5593
			if ( array_key_exists( $key, $state ) )
5594
				return $state[ $key ];
5595
			return null;
5596
		}
5597
5598
		// Set a state variable
5599
		if ( isset ( $key ) && isset( $value ) ) {
5600
			if( is_array( $value ) && isset( $value[0] ) ) {
5601
				$value = $value[0];
5602
			}
5603
			$state[ $key ] = $value;
5604
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5605
		}
5606
	}
5607
5608
	public static function restate() {
5609
		Jetpack::state( null, null, true );
5610
	}
5611
5612
	public static function check_privacy( $file ) {
5613
		static $is_site_publicly_accessible = null;
5614
5615
		if ( is_null( $is_site_publicly_accessible ) ) {
5616
			$is_site_publicly_accessible = false;
5617
5618
			Jetpack::load_xml_rpc_client();
5619
			$rpc = new Jetpack_IXR_Client();
5620
5621
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5622
			if ( $success ) {
5623
				$response = $rpc->getResponse();
5624
				if ( $response ) {
5625
					$is_site_publicly_accessible = true;
5626
				}
5627
			}
5628
5629
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5630
		}
5631
5632
		if ( $is_site_publicly_accessible ) {
5633
			return;
5634
		}
5635
5636
		$module_slug = self::get_module_slug( $file );
5637
5638
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5639
		if ( ! $privacy_checks ) {
5640
			$privacy_checks = $module_slug;
5641
		} else {
5642
			$privacy_checks .= ",$module_slug";
5643
		}
5644
5645
		Jetpack::state( 'privacy_checks', $privacy_checks );
5646
	}
5647
5648
	/**
5649
	 * Helper method for multicall XMLRPC.
5650
	 */
5651
	public static function xmlrpc_async_call() {
5652
		global $blog_id;
5653
		static $clients = array();
5654
5655
		$client_blog_id = is_multisite() ? $blog_id : 0;
5656
5657
		if ( ! isset( $clients[$client_blog_id] ) ) {
5658
			Jetpack::load_xml_rpc_client();
5659
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5660
			if ( function_exists( 'ignore_user_abort' ) ) {
5661
				ignore_user_abort( true );
5662
			}
5663
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5664
		}
5665
5666
		$args = func_get_args();
5667
5668
		if ( ! empty( $args[0] ) ) {
5669
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5670
		} elseif ( is_multisite() ) {
5671
			foreach ( $clients as $client_blog_id => $client ) {
5672
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5673
					continue;
5674
				}
5675
5676
				$switch_success = switch_to_blog( $client_blog_id, true );
5677
				if ( ! $switch_success ) {
5678
					continue;
5679
				}
5680
5681
				flush();
5682
				$client->query();
5683
5684
				restore_current_blog();
5685
			}
5686
		} else {
5687
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5688
				flush();
5689
				$clients[0]->query();
5690
			}
5691
		}
5692
	}
5693
5694
	public static function staticize_subdomain( $url ) {
5695
5696
		// Extract hostname from URL
5697
		$host = parse_url( $url, PHP_URL_HOST );
5698
5699
		// Explode hostname on '.'
5700
		$exploded_host = explode( '.', $host );
5701
5702
		// Retrieve the name and TLD
5703
		if ( count( $exploded_host ) > 1 ) {
5704
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5705
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5706
			// Rebuild domain excluding subdomains
5707
			$domain = $name . '.' . $tld;
5708
		} else {
5709
			$domain = $host;
5710
		}
5711
		// Array of Automattic domains
5712
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5713
5714
		// Return $url if not an Automattic domain
5715
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5716
			return $url;
5717
		}
5718
5719
		if ( is_ssl() ) {
5720
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5721
		}
5722
5723
		srand( crc32( basename( $url ) ) );
5724
		$static_counter = rand( 0, 2 );
5725
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5726
5727
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5728
	}
5729
5730
/* JSON API Authorization */
5731
5732
	/**
5733
	 * Handles the login action for Authorizing the JSON API
5734
	 */
5735
	function login_form_json_api_authorization() {
5736
		$this->verify_json_api_authorization_request();
5737
5738
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5739
5740
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5741
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5742
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5743
	}
5744
5745
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5746
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5747
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5748
			return $url;
5749
		}
5750
5751
		$parsed_url = parse_url( $url );
5752
		$url = strtok( $url, '?' );
5753
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5754
		if ( ! empty( $parsed_url['query'] ) )
5755
			$url .= "&{$parsed_url['query']}";
5756
5757
		return $url;
5758
	}
5759
5760
	// Make sure the POSTed request is handled by the same action
5761
	function preserve_action_in_login_form_for_json_api_authorization() {
5762
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5763
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5764
	}
5765
5766
	// If someone logs in to approve API access, store the Access Code in usermeta
5767
	function store_json_api_authorization_token( $user_login, $user ) {
5768
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5769
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5770
		$token = wp_generate_password( 32, false );
5771
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5772
	}
5773
5774
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5775
	function allow_wpcom_public_api_domain( $domains ) {
5776
		$domains[] = 'public-api.wordpress.com';
5777
		return $domains;
5778
	}
5779
5780
	static function is_redirect_encoded( $redirect_url ) {
5781
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5782
	}
5783
5784
	// Add all wordpress.com environments to the safe redirect whitelist
5785
	function allow_wpcom_environments( $domains ) {
5786
		$domains[] = 'wordpress.com';
5787
		$domains[] = 'wpcalypso.wordpress.com';
5788
		$domains[] = 'horizon.wordpress.com';
5789
		$domains[] = 'calypso.localhost';
5790
		return $domains;
5791
	}
5792
5793
	// Add the Access Code details to the public-api.wordpress.com redirect
5794
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5795
		return add_query_arg(
5796
			urlencode_deep(
5797
				array(
5798
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5799
					'jetpack-user-id' => (int) $user->ID,
5800
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5801
				)
5802
			),
5803
			$redirect_to
5804
		);
5805
	}
5806
5807
5808
	/**
5809
	 * Verifies the request by checking the signature
5810
	 *
5811
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5812
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5813
	 *
5814
	 * @param null|array $environment
5815
	 */
5816
	function verify_json_api_authorization_request( $environment = null ) {
5817
		$environment = is_null( $environment )
5818
			? $_REQUEST
5819
			: $environment;
5820
5821
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5822
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
5823
		if ( ! $token || empty( $token->secret ) ) {
5824
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5825
		}
5826
5827
		$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' );
5828
5829
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5830
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5831
			JetpackTracking::record_user_event( 'error_double_encode' );
5832
5833
			$die_error = sprintf(
5834
				/* translators: %s is a URL */
5835
				__( 'Your site is incorrectly double-encoding redirects from http to https. This is preventing Jetpack from authenticating your connection. Please visit our <a href="%s">support page</a> for details about how to resolve this.', 'jetpack' ),
5836
				'https://jetpack.com/support/double-encoding/'
5837
			);
5838
		}
5839
5840
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5841
5842
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5843
			$signature = $jetpack_signature->sign_request(
5844
				$environment['token'],
5845
				$environment['timestamp'],
5846
				$environment['nonce'],
5847
				'',
5848
				'GET',
5849
				$environment['jetpack_json_api_original_query'],
5850
				null,
5851
				true
5852
			);
5853
		} else {
5854
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5855
		}
5856
5857
		if ( ! $signature ) {
5858
			wp_die( $die_error );
5859
		} else if ( is_wp_error( $signature ) ) {
5860
			wp_die( $die_error );
5861
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5862
			if ( is_ssl() ) {
5863
				// 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
5864
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5865
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5866
					wp_die( $die_error );
5867
				}
5868
			} else {
5869
				wp_die( $die_error );
5870
			}
5871
		}
5872
5873
		$timestamp = (int) $environment['timestamp'];
5874
		$nonce     = stripslashes( (string) $environment['nonce'] );
5875
5876
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5877
			// De-nonce the nonce, at least for 5 minutes.
5878
			// 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)
5879
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5880
			if ( $old_nonce_time < time() - 300 ) {
5881
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5882
			}
5883
		}
5884
5885
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5886
		$data_filters = array(
5887
			'state'        => 'opaque',
5888
			'client_id'    => 'int',
5889
			'client_title' => 'string',
5890
			'client_image' => 'url',
5891
		);
5892
5893
		foreach ( $data_filters as $key => $sanitation ) {
5894
			if ( ! isset( $data->$key ) ) {
5895
				wp_die( $die_error );
5896
			}
5897
5898
			switch ( $sanitation ) {
5899
			case 'int' :
5900
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5901
				break;
5902
			case 'opaque' :
5903
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5904
				break;
5905
			case 'string' :
5906
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5907
				break;
5908
			case 'url' :
5909
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5910
				break;
5911
			}
5912
		}
5913
5914
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5915
			wp_die( $die_error );
5916
		}
5917
	}
5918
5919
	function login_message_json_api_authorization( $message ) {
5920
		return '<p class="message">' . sprintf(
5921
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5922
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5923
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5924
	}
5925
5926
	/**
5927
	 * Get $content_width, but with a <s>twist</s> filter.
5928
	 */
5929
	public static function get_content_width() {
5930
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5931
			? $GLOBALS['content_width']
5932
			: false;
5933
		/**
5934
		 * Filter the Content Width value.
5935
		 *
5936
		 * @since 2.2.3
5937
		 *
5938
		 * @param string $content_width Content Width value.
5939
		 */
5940
		return apply_filters( 'jetpack_content_width', $content_width );
5941
	}
5942
5943
	/**
5944
	 * Pings the WordPress.com Mirror Site for the specified options.
5945
	 *
5946
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5947
	 *
5948
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5949
	 */
5950
	public function get_cloud_site_options( $option_names ) {
5951
		$option_names = array_filter( (array) $option_names, 'is_string' );
5952
5953
		Jetpack::load_xml_rpc_client();
5954
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5955
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5956
		if ( $xml->isError() ) {
5957
			return array(
5958
				'error_code' => $xml->getErrorCode(),
5959
				'error_msg'  => $xml->getErrorMessage(),
5960
			);
5961
		}
5962
		$cloud_site_options = $xml->getResponse();
5963
5964
		return $cloud_site_options;
5965
	}
5966
5967
	/**
5968
	 * Checks if the site is currently in an identity crisis.
5969
	 *
5970
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5971
	 */
5972
	public static function check_identity_crisis() {
5973
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5974
			return false;
5975
		}
5976
5977
		return Jetpack_Options::get_option( 'sync_error_idc' );
5978
	}
5979
5980
	/**
5981
	 * Checks whether the home and siteurl specifically are whitelisted
5982
	 * Written so that we don't have re-check $key and $value params every time
5983
	 * we want to check if this site is whitelisted, for example in footer.php
5984
	 *
5985
	 * @since  3.8.0
5986
	 * @return bool True = already whitelisted False = not whitelisted
5987
	 */
5988
	public static function is_staging_site() {
5989
		$is_staging = false;
5990
5991
		$known_staging = array(
5992
			'urls' => array(
5993
				'#\.staging\.wpengine\.com$#i', // WP Engine
5994
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5995
				),
5996
			'constants' => array(
5997
				'IS_WPE_SNAPSHOT',      // WP Engine
5998
				'KINSTA_DEV_ENV',       // Kinsta.com
5999
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6000
				'JETPACK_STAGING_MODE', // Generic
6001
				)
6002
			);
6003
		/**
6004
		 * Filters the flags of known staging sites.
6005
		 *
6006
		 * @since 3.9.0
6007
		 *
6008
		 * @param array $known_staging {
6009
		 *     An array of arrays that each are used to check if the current site is staging.
6010
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6011
		 *     @type array $constants PHP constants of known staging/developement environments.
6012
		 *  }
6013
		 */
6014
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6015
6016
		if ( isset( $known_staging['urls'] ) ) {
6017
			foreach ( $known_staging['urls'] as $url ){
6018
				if ( preg_match( $url, site_url() ) ) {
6019
					$is_staging = true;
6020
					break;
6021
				}
6022
			}
6023
		}
6024
6025
		if ( isset( $known_staging['constants'] ) ) {
6026
			foreach ( $known_staging['constants'] as $constant ) {
6027
				if ( defined( $constant ) && constant( $constant ) ) {
6028
					$is_staging = true;
6029
				}
6030
			}
6031
		}
6032
6033
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6034
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6035
			$is_staging = true;
6036
		}
6037
6038
		/**
6039
		 * Filters is_staging_site check.
6040
		 *
6041
		 * @since 3.9.0
6042
		 *
6043
		 * @param bool $is_staging If the current site is a staging site.
6044
		 */
6045
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6046
	}
6047
6048
	/**
6049
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6050
	 *
6051
	 * @since 4.4.0
6052
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6053
	 *
6054
	 * @return bool
6055
	 */
6056
	public static function validate_sync_error_idc_option() {
6057
		$is_valid = false;
6058
6059
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6060
		if ( false === $idc_allowed ) {
6061
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6062
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6063
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6064
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6065
				$transient_duration = HOUR_IN_SECONDS;
6066
			} else {
6067
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6068
				$idc_allowed = '1';
6069
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6070
			}
6071
6072
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6073
		}
6074
6075
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6076
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6077
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6078
			$local_options = self::get_sync_error_idc_option();
6079
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6080
				$is_valid = true;
6081
			}
6082
		}
6083
6084
		/**
6085
		 * Filters whether the sync_error_idc option is valid.
6086
		 *
6087
		 * @since 4.4.0
6088
		 *
6089
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6090
		 */
6091
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6092
6093
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6094
			// Since the option exists, and did not validate, delete it
6095
			Jetpack_Options::delete_option( 'sync_error_idc' );
6096
		}
6097
6098
		return $is_valid;
6099
	}
6100
6101
	/**
6102
	 * Normalizes a url by doing three things:
6103
	 *  - Strips protocol
6104
	 *  - Strips www
6105
	 *  - Adds a trailing slash
6106
	 *
6107
	 * @since 4.4.0
6108
	 * @param string $url
6109
	 * @return WP_Error|string
6110
	 */
6111
	public static function normalize_url_protocol_agnostic( $url ) {
6112
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6113
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6114
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6115
		}
6116
6117
		// Strip www and protocols
6118
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6119
		return $url;
6120
	}
6121
6122
	/**
6123
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6124
	 *
6125
	 * @since 4.4.0
6126
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6127
	 *
6128
	 * @param array $response
6129
	 * @return array Array of the local urls, wpcom urls, and error code
6130
	 */
6131
	public static function get_sync_error_idc_option( $response = array() ) {
6132
		// Since the local options will hit the database directly, store the values
6133
		// in a transient to allow for autoloading and caching on subsequent views.
6134
		$local_options = get_transient( 'jetpack_idc_local' );
6135
		if ( false === $local_options ) {
6136
			$local_options = array(
6137
				'home'    => Jetpack_Sync_Functions::home_url(),
6138
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6139
			);
6140
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6141
		}
6142
6143
		$options = array_merge( $local_options, $response );
6144
6145
		$returned_values = array();
6146
		foreach( $options as $key => $option ) {
6147
			if ( 'error_code' === $key ) {
6148
				$returned_values[ $key ] = $option;
6149
				continue;
6150
			}
6151
6152
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6153
				continue;
6154
			}
6155
6156
			$returned_values[ $key ] = $normalized_url;
6157
		}
6158
6159
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6160
6161
		return $returned_values;
6162
	}
6163
6164
	/**
6165
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6166
	 * If set to true, the site will be put into staging mode.
6167
	 *
6168
	 * @since 4.3.2
6169
	 * @return bool
6170
	 */
6171
	public static function sync_idc_optin() {
6172
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6173
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6174
		} else {
6175
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6176
		}
6177
6178
		/**
6179
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6180
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6181
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6182
		 *
6183
		 * @since 4.3.2
6184
		 *
6185
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6186
		 */
6187
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6188
	}
6189
6190
	/**
6191
	 * Maybe Use a .min.css stylesheet, maybe not.
6192
	 *
6193
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6194
	 */
6195
	public static function maybe_min_asset( $url, $path, $plugin ) {
6196
		// Short out on things trying to find actual paths.
6197
		if ( ! $path || empty( $plugin ) ) {
6198
			return $url;
6199
		}
6200
6201
		$path = ltrim( $path, '/' );
6202
6203
		// Strip out the abspath.
6204
		$base = dirname( plugin_basename( $plugin ) );
6205
6206
		// Short out on non-Jetpack assets.
6207
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6208
			return $url;
6209
		}
6210
6211
		// File name parsing.
6212
		$file              = "{$base}/{$path}";
6213
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6214
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6215
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6216
		$extension         = array_shift( $file_name_parts_r );
6217
6218
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6219
			// Already pointing at the minified version.
6220
			if ( 'min' === $file_name_parts_r[0] ) {
6221
				return $url;
6222
			}
6223
6224
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6225
			if ( file_exists( $min_full_path ) ) {
6226
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6227
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6228
				if ( 'css' === $extension ) {
6229
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6230
					self::$min_assets[ $key ] = $path;
6231
				}
6232
			}
6233
		}
6234
6235
		return $url;
6236
	}
6237
6238
	/**
6239
	 * If the asset is minified, let's flag .min as the suffix.
6240
	 *
6241
	 * Attached to `style_loader_src` filter.
6242
	 *
6243
	 * @param string $tag The tag that would link to the external asset.
6244
	 * @param string $handle The registered handle of the script in question.
6245
	 * @param string $href The url of the asset in question.
6246
	 */
6247
	public static function set_suffix_on_min( $src, $handle ) {
6248
		if ( false === strpos( $src, '.min.css' ) ) {
6249
			return $src;
6250
		}
6251
6252
		if ( ! empty( self::$min_assets ) ) {
6253
			foreach ( self::$min_assets as $file => $path ) {
6254
				if ( false !== strpos( $src, $file ) ) {
6255
					wp_style_add_data( $handle, 'suffix', '.min' );
6256
					return $src;
6257
				}
6258
			}
6259
		}
6260
6261
		return $src;
6262
	}
6263
6264
	/**
6265
	 * Maybe inlines a stylesheet.
6266
	 *
6267
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6268
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6269
	 *
6270
	 * Attached to `style_loader_tag` filter.
6271
	 *
6272
	 * @param string $tag The tag that would link to the external asset.
6273
	 * @param string $handle The registered handle of the script in question.
6274
	 *
6275
	 * @return string
6276
	 */
6277
	public static function maybe_inline_style( $tag, $handle ) {
6278
		global $wp_styles;
6279
		$item = $wp_styles->registered[ $handle ];
6280
6281
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6282
			return $tag;
6283
		}
6284
6285
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6286
			$href = $matches[1];
6287
			// Strip off query string
6288
			if ( $pos = strpos( $href, '?' ) ) {
6289
				$href = substr( $href, 0, $pos );
6290
			}
6291
			// Strip off fragment
6292
			if ( $pos = strpos( $href, '#' ) ) {
6293
				$href = substr( $href, 0, $pos );
6294
			}
6295
		} else {
6296
			return $tag;
6297
		}
6298
6299
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6300
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6301
			return $tag;
6302
		}
6303
6304
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6305
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6306
			// And this isn't the pass that actually deals with the RTL version...
6307
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6308
				// Short out, as the RTL version will deal with it in a moment.
6309
				return $tag;
6310
			}
6311
		}
6312
6313
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6314
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6315
		if ( $css ) {
6316
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6317
			if ( empty( $item->extra['after'] ) ) {
6318
				wp_add_inline_style( $handle, $css );
6319
			} else {
6320
				array_unshift( $item->extra['after'], $css );
6321
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6322
			}
6323
		}
6324
6325
		return $tag;
6326
	}
6327
6328
	/**
6329
	 * Loads a view file from the views
6330
	 *
6331
	 * Data passed in with the $data parameter will be available in the
6332
	 * template file as $data['value']
6333
	 *
6334
	 * @param string $template - Template file to load
6335
	 * @param array $data - Any data to pass along to the template
6336
	 * @return boolean - If template file was found
6337
	 **/
6338
	public function load_view( $template, $data = array() ) {
6339
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6340
6341
		if( file_exists( $views_dir . $template ) ) {
6342
			require_once( $views_dir . $template );
6343
			return true;
6344
		}
6345
6346
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6347
		return false;
6348
	}
6349
6350
	/**
6351
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6352
	 */
6353
	public function deprecated_hooks() {
6354
		global $wp_filter;
6355
6356
		/*
6357
		 * Format:
6358
		 * deprecated_filter_name => replacement_name
6359
		 *
6360
		 * If there is no replacement, use null for replacement_name
6361
		 */
6362
		$deprecated_list = array(
6363
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6364
			'wpl_sharing_2014_1'                                     => null,
6365
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6366
			'jetpack_identity_crisis_options_to_check'               => null,
6367
			'update_option_jetpack_single_user_site'                 => null,
6368
			'audio_player_default_colors'                            => null,
6369
			'add_option_jetpack_featured_images_enabled'             => null,
6370
			'add_option_jetpack_update_details'                      => null,
6371
			'add_option_jetpack_updates'                             => null,
6372
			'add_option_jetpack_network_name'                        => null,
6373
			'add_option_jetpack_network_allow_new_registrations'     => null,
6374
			'add_option_jetpack_network_add_new_users'               => null,
6375
			'add_option_jetpack_network_site_upload_space'           => null,
6376
			'add_option_jetpack_network_upload_file_types'           => null,
6377
			'add_option_jetpack_network_enable_administration_menus' => null,
6378
			'add_option_jetpack_is_multi_site'                       => null,
6379
			'add_option_jetpack_is_main_network'                     => null,
6380
			'add_option_jetpack_main_network_site'                   => null,
6381
			'jetpack_sync_all_registered_options'                    => null,
6382
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6383
			'jetpack_is_post_mailable'                               => null,
6384
			'jetpack_seo_site_host'                                  => null,
6385
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6386
			'jetpack_holiday_snow_option_name'                       => null,
6387
			'jetpack_holiday_chance_of_snow'                         => null,
6388
			'jetpack_holiday_snow_js_url'                            => null,
6389
			'jetpack_is_holiday_snow_season'                         => null,
6390
			'jetpack_holiday_snow_option_updated'                    => null,
6391
			'jetpack_holiday_snowing'                                => null,
6392
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6393
			'jetpack_cache_plans'                                    => null,
6394
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6395
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6396
			'jetpack_enable_site_verification'                       => null,
6397
			'can_display_jetpack_manage_notice'                      => null,
6398
			// Removed in Jetpack 7.3.0
6399
			'atd_load_scripts'                                       => null,
6400
			'atd_http_post_timeout'                                  => null,
6401
			'atd_http_post_error'                                    => null,
6402
			'atd_service_domain'                                     => null,
6403
		);
6404
6405
		// This is a silly loop depth. Better way?
6406
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6407
			if ( has_action( $hook ) ) {
6408
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6409
					foreach( $values AS $hooked ) {
6410
						if ( is_callable( $hooked['function'] ) ) {
6411
							$function_name = 'an anonymous function';
6412
						} else {
6413
							$function_name = $hooked['function'];
6414
						}
6415
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6416
					}
6417
				}
6418
			}
6419
		}
6420
	}
6421
6422
	/**
6423
	 * Converts any url in a stylesheet, to the correct absolute url.
6424
	 *
6425
	 * Considerations:
6426
	 *  - Normal, relative URLs     `feh.png`
6427
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6428
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6429
	 *  - Absolute URLs             `http://domain.com/feh.png`
6430
	 *  - Domain root relative URLs `/feh.png`
6431
	 *
6432
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6433
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6434
	 *
6435
	 * @return mixed|string
6436
	 */
6437
	public static function absolutize_css_urls( $css, $css_file_url ) {
6438
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6439
		$css_dir = dirname( $css_file_url );
6440
		$p       = parse_url( $css_dir );
6441
		$domain  = sprintf(
6442
					'%1$s//%2$s%3$s%4$s',
6443
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6444
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6445
					$p['host'],
6446
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6447
				);
6448
6449
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6450
			$find = $replace = array();
6451
			foreach ( $matches as $match ) {
6452
				$url = trim( $match['path'], "'\" \t" );
6453
6454
				// If this is a data url, we don't want to mess with it.
6455
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6456
					continue;
6457
				}
6458
6459
				// If this is an absolute or protocol-agnostic url,
6460
				// we don't want to mess with it.
6461
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6462
					continue;
6463
				}
6464
6465
				switch ( substr( $url, 0, 1 ) ) {
6466
					case '/':
6467
						$absolute = $domain . $url;
6468
						break;
6469
					default:
6470
						$absolute = $css_dir . '/' . $url;
6471
				}
6472
6473
				$find[]    = $match[0];
6474
				$replace[] = sprintf( 'url("%s")', $absolute );
6475
			}
6476
			$css = str_replace( $find, $replace, $css );
6477
		}
6478
6479
		return $css;
6480
	}
6481
6482
	/**
6483
	 * This methods removes all of the registered css files on the front end
6484
	 * from Jetpack in favor of using a single file. In effect "imploding"
6485
	 * all the files into one file.
6486
	 *
6487
	 * Pros:
6488
	 * - Uses only ONE css asset connection instead of 15
6489
	 * - Saves a minimum of 56k
6490
	 * - Reduces server load
6491
	 * - Reduces time to first painted byte
6492
	 *
6493
	 * Cons:
6494
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6495
	 *		should not cause any issues with themes.
6496
	 * - Plugins/themes dequeuing styles no longer do anything. See
6497
	 *		jetpack_implode_frontend_css filter for a workaround
6498
	 *
6499
	 * For some situations developers may wish to disable css imploding and
6500
	 * instead operate in legacy mode where each file loads seperately and
6501
	 * can be edited individually or dequeued. This can be accomplished with
6502
	 * the following line:
6503
	 *
6504
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6505
	 *
6506
	 * @since 3.2
6507
	 **/
6508
	public function implode_frontend_css( $travis_test = false ) {
6509
		$do_implode = true;
6510
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6511
			$do_implode = false;
6512
		}
6513
6514
		// Do not implode CSS when the page loads via the AMP plugin.
6515
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6516
			$do_implode = false;
6517
		}
6518
6519
		/**
6520
		 * Allow CSS to be concatenated into a single jetpack.css file.
6521
		 *
6522
		 * @since 3.2.0
6523
		 *
6524
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6525
		 */
6526
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6527
6528
		// Do not use the imploded file when default behavior was altered through the filter
6529
		if ( ! $do_implode ) {
6530
			return;
6531
		}
6532
6533
		// We do not want to use the imploded file in dev mode, or if not connected
6534
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6535
			if ( ! $travis_test ) {
6536
				return;
6537
			}
6538
		}
6539
6540
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6541
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6542
			return;
6543
		}
6544
6545
		/*
6546
		 * Now we assume Jetpack is connected and able to serve the single
6547
		 * file.
6548
		 *
6549
		 * In the future there will be a check here to serve the file locally
6550
		 * or potentially from the Jetpack CDN
6551
		 *
6552
		 * For now:
6553
		 * - Enqueue a single imploded css file
6554
		 * - Zero out the style_loader_tag for the bundled ones
6555
		 * - Be happy, drink scotch
6556
		 */
6557
6558
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6559
6560
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6561
6562
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6563
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6564
	}
6565
6566
	function concat_remove_style_loader_tag( $tag, $handle ) {
6567
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6568
			$tag = '';
6569
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6570
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6571
			}
6572
		}
6573
6574
		return $tag;
6575
	}
6576
6577
	/*
6578
	 * Check the heartbeat data
6579
	 *
6580
	 * Organizes the heartbeat data by severity.  For example, if the site
6581
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6582
	 *
6583
	 * Data will be added to "caution" array, if it either:
6584
	 *  - Out of date Jetpack version
6585
	 *  - Out of date WP version
6586
	 *  - Out of date PHP version
6587
	 *
6588
	 * $return array $filtered_data
6589
	 */
6590
	public static function jetpack_check_heartbeat_data() {
6591
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6592
6593
		$good    = array();
6594
		$caution = array();
6595
		$bad     = array();
6596
6597
		foreach ( $raw_data as $stat => $value ) {
6598
6599
			// Check jetpack version
6600
			if ( 'version' == $stat ) {
6601
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6602
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6603
					continue;
6604
				}
6605
			}
6606
6607
			// Check WP version
6608
			if ( 'wp-version' == $stat ) {
6609
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6610
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6611
					continue;
6612
				}
6613
			}
6614
6615
			// Check PHP version
6616
			if ( 'php-version' == $stat ) {
6617
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6618
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6619
					continue;
6620
				}
6621
			}
6622
6623
			// Check ID crisis
6624
			if ( 'identitycrisis' == $stat ) {
6625
				if ( 'yes' == $value ) {
6626
					$bad[ $stat ] = $value;
6627
					continue;
6628
				}
6629
			}
6630
6631
			// The rest are good :)
6632
			$good[ $stat ] = $value;
6633
		}
6634
6635
		$filtered_data = array(
6636
			'good'    => $good,
6637
			'caution' => $caution,
6638
			'bad'     => $bad
6639
		);
6640
6641
		return $filtered_data;
6642
	}
6643
6644
6645
	/*
6646
	 * This method is used to organize all options that can be reset
6647
	 * without disconnecting Jetpack.
6648
	 *
6649
	 * It is used in class.jetpack-cli.php to reset options
6650
	 *
6651
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6652
	 *
6653
	 * @return array of options to delete.
6654
	 */
6655
	public static function get_jetpack_options_for_reset() {
6656
		return Jetpack_Options::get_options_for_reset();
6657
	}
6658
6659
	/*
6660
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6661
	 * so we can bring them directly to their site in calypso.
6662
	 *
6663
	 * @param string | url
6664
	 * @return string | url without the guff
6665
	 */
6666
	public static function build_raw_urls( $url ) {
6667
		$strip_http = '/.*?:\/\//i';
6668
		$url = preg_replace( $strip_http, '', $url  );
6669
		$url = str_replace( '/', '::', $url );
6670
		return $url;
6671
	}
6672
6673
	/**
6674
	 * Stores and prints out domains to prefetch for page speed optimization.
6675
	 *
6676
	 * @param mixed $new_urls
6677
	 */
6678
	public static function dns_prefetch( $new_urls = null ) {
6679
		static $prefetch_urls = array();
6680
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6681
			echo "\r\n";
6682
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6683
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6684
			}
6685
		} elseif ( ! empty( $new_urls ) ) {
6686
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6687
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6688
			}
6689
			foreach ( (array) $new_urls as $this_new_url ) {
6690
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6691
			}
6692
			$prefetch_urls = array_unique( $prefetch_urls );
6693
		}
6694
	}
6695
6696
	public function wp_dashboard_setup() {
6697
		if ( self::is_active() ) {
6698
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6699
		}
6700
6701
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6702
			$jetpack_logo = new Jetpack_Logo();
6703
			$widget_title = sprintf(
6704
				wp_kses(
6705
					/* translators: Placeholder is a Jetpack logo. */
6706
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6707
					array( 'span' => array() )
6708
				),
6709
				$jetpack_logo->get_jp_emblem( true )
6710
			);
6711
6712
			wp_add_dashboard_widget(
6713
				'jetpack_summary_widget',
6714
				$widget_title,
6715
				array( __CLASS__, 'dashboard_widget' )
6716
			);
6717
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6718
6719
			// If we're inactive and not in development mode, sort our box to the top.
6720
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6721
				global $wp_meta_boxes;
6722
6723
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6724
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6725
6726
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6727
			}
6728
		}
6729
	}
6730
6731
	/**
6732
	 * @param mixed $result Value for the user's option
6733
	 * @return mixed
6734
	 */
6735
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6736
		if ( ! is_array( $sorted ) ) {
6737
			return $sorted;
6738
		}
6739
6740
		foreach ( $sorted as $box_context => $ids ) {
6741
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6742
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6743
				continue;
6744
			}
6745
6746
			$ids_array = explode( ',', $ids );
6747
			$key = array_search( 'dashboard_stats', $ids_array );
6748
6749
			if ( false !== $key ) {
6750
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6751
				$ids_array[ $key ] = 'jetpack_summary_widget';
6752
				$sorted[ $box_context ] = implode( ',', $ids_array );
6753
				// We've found it, stop searching, and just return.
6754
				break;
6755
			}
6756
		}
6757
6758
		return $sorted;
6759
	}
6760
6761
	public static function dashboard_widget() {
6762
		/**
6763
		 * Fires when the dashboard is loaded.
6764
		 *
6765
		 * @since 3.4.0
6766
		 */
6767
		do_action( 'jetpack_dashboard_widget' );
6768
	}
6769
6770
	public static function dashboard_widget_footer() {
6771
		?>
6772
		<footer>
6773
6774
		<div class="protect">
6775
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6776
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6777
				<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>
6778
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6779
				<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' ); ?>">
6780
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6781
				</a>
6782
			<?php else : ?>
6783
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6784
			<?php endif; ?>
6785
		</div>
6786
6787
		<div class="akismet">
6788
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6789
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6790
				<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>
6791
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6792
				<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">
6793
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6794
				</a>
6795
			<?php else : ?>
6796
				<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>
6797
			<?php endif; ?>
6798
		</div>
6799
6800
		</footer>
6801
		<?php
6802
	}
6803
6804
	/*
6805
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6806
	 */
6807
	function jetpack_icon_user_connected( $columns ) {
6808
		$columns['user_jetpack'] = '';
6809
		return $columns;
6810
	}
6811
6812
	/*
6813
	 * Show Jetpack icon if the user is linked.
6814
	 */
6815
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6816
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6817
			$jetpack_logo = new Jetpack_Logo();
6818
			$emblem_html = sprintf(
6819
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6820
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6821
				$jetpack_logo->get_jp_emblem()
6822
			);
6823
			return $emblem_html;
6824
		}
6825
6826
		return $val;
6827
	}
6828
6829
	/*
6830
	 * Style the Jetpack user column
6831
	 */
6832
	function jetpack_user_col_style() {
6833
		global $current_screen;
6834
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6835
			<style>
6836
				.fixed .column-user_jetpack {
6837
					width: 21px;
6838
				}
6839
				.jp-emblem-user-admin svg {
6840
					width: 20px;
6841
					height: 20px;
6842
				}
6843
				.jp-emblem-user-admin path {
6844
					fill: #00BE28;
6845
				}
6846
			</style>
6847
		<?php }
6848
	}
6849
6850
	/**
6851
	 * Checks if Akismet is active and working.
6852
	 *
6853
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6854
	 * that implied usage of methods present since more recent version.
6855
	 * See https://github.com/Automattic/jetpack/pull/9585
6856
	 *
6857
	 * @since  5.1.0
6858
	 *
6859
	 * @return bool True = Akismet available. False = Aksimet not available.
6860
	 */
6861
	public static function is_akismet_active() {
6862
		static $status = null;
6863
6864
		if ( ! is_null( $status ) ) {
6865
			return $status;
6866
		}
6867
6868
		// Check if a modern version of Akismet is active.
6869
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6870
			$status = false;
6871
			return $status;
6872
		}
6873
6874
		// Make sure there is a key known to Akismet at all before verifying key.
6875
		$akismet_key = Akismet::get_api_key();
6876
		if ( ! $akismet_key ) {
6877
			$status = false;
6878
			return $status;
6879
		}
6880
6881
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6882
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6883
6884
		// Do not used the cache result in wp-admin or REST API requests if the key isn't valid, in case someone is actively renewing, etc.
6885
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6886
		// We cache the result of the Akismet key verification for ten minutes.
6887
		if ( ! $akismet_key_state || $recheck ) {
6888
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6889
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6890
		}
6891
6892
		$status = 'valid' === $akismet_key_state;
6893
6894
		return $status;
6895
	}
6896
6897
	/**
6898
	 * Checks if one or more function names is in debug_backtrace
6899
	 *
6900
	 * @param $names Mixed string name of function or array of string names of functions
6901
	 *
6902
	 * @return bool
6903
	 */
6904
	public static function is_function_in_backtrace( $names ) {
6905
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6906
		if ( ! is_array( $names ) ) {
6907
			$names = array( $names );
6908
		}
6909
		$names_as_keys = array_flip( $names );
6910
6911
		//Do check in constant O(1) time for PHP5.5+
6912
		if ( function_exists( 'array_column' ) ) {
6913
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6914
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6915
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6916
			return ! empty ( $intersection );
6917
		}
6918
6919
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6920
		foreach ( $backtrace as $call ) {
6921
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6922
				return true;
6923
			}
6924
		}
6925
		return false;
6926
	}
6927
6928
	/**
6929
	 * Given a minified path, and a non-minified path, will return
6930
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6931
	 *
6932
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6933
	 * root Jetpack directory.
6934
	 *
6935
	 * @since 5.6.0
6936
	 *
6937
	 * @param string $min_path
6938
	 * @param string $non_min_path
6939
	 * @return string The URL to the file
6940
	 */
6941
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6942
		$path = ( Constants::is_defined( 'SCRIPT_DEBUG' ) && Constants::get_constant( 'SCRIPT_DEBUG' ) )
6943
			? $non_min_path
6944
			: $min_path;
6945
6946
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6947
	}
6948
6949
	/**
6950
	 * Checks for whether Jetpack Backup & Scan is enabled.
6951
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6952
	 * @return bool|int|mixed
6953
	 */
6954
	public static function is_rewind_enabled() {
6955
		if ( ! Jetpack::is_active() ) {
6956
			return false;
6957
		}
6958
6959
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6960
		if ( false === $rewind_enabled ) {
6961
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6962
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6963
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6964
				&& ! empty( $rewind_data['state'] )
6965
				&& 'active' === $rewind_data['state'] )
6966
				? 1
6967
				: 0;
6968
6969
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6970
		}
6971
		return $rewind_enabled;
6972
	}
6973
6974
	/**
6975
	 * Return Calypso environment value; used for developing Jetpack and pairing
6976
	 * it with different Calypso enrionments, such as localhost.
6977
	 *
6978
	 * @since 7.4.0
6979
	 *
6980
	 * @return string Calypso environment
6981
	 */
6982
	public static function get_calypso_env() {
6983
		if ( isset( $_GET['calypso_env'] ) ) {
6984
			return sanitize_key( $_GET['calypso_env'] );
6985
		}
6986
6987
		if ( getenv( 'CALYPSO_ENV' ) ) {
6988
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6989
		}
6990
6991
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6992
			return sanitize_key( CALYPSO_ENV );
6993
		}
6994
6995
		return '';
6996
	}
6997
6998
	/**
6999
	 * Checks whether or not TOS has been agreed upon.
7000
	 * Will return true if a user has clicked to register, or is already connected.
7001
	 */
7002
	public static function jetpack_tos_agreed() {
7003
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7004
	}
7005
7006
	/**
7007
	 * Handles activating default modules as well general cleanup for the new connection.
7008
	 *
7009
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7010
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7011
	 * @param boolean $send_state_messages          Whether to send state messages.
7012
	 * @return void
7013
	 */
7014
	public static function handle_post_authorization_actions(
7015
		$activate_sso = false,
7016
		$redirect_on_activation_error = false,
7017
		$send_state_messages = true
7018
	) {
7019
		$other_modules = $activate_sso
7020
			? array( 'sso' )
7021
			: array();
7022
7023
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7024
			Jetpack::delete_active_modules();
7025
7026
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7027
		} else {
7028
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7029
		}
7030
7031
		// Since this is a fresh connection, be sure to clear out IDC options
7032
		Jetpack_IDC::clear_all_idc_options();
7033
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7034
7035
		// Start nonce cleaner
7036
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7037
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7038
7039
		if ( $send_state_messages ) {
7040
			Jetpack::state( 'message', 'authorized' );
7041
		}
7042
	}
7043
7044
	/**
7045
	 * Returns a boolean for whether backups UI should be displayed or not.
7046
	 *
7047
	 * @return bool Should backups UI be displayed?
7048
	 */
7049
	public static function show_backups_ui() {
7050
		/**
7051
		 * Whether UI for backups should be displayed.
7052
		 *
7053
		 * @since 6.5.0
7054
		 *
7055
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7056
		 */
7057
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7058
	}
7059
7060
	/*
7061
	 * Deprecated manage functions
7062
	 */
7063
	function prepare_manage_jetpack_notice() {
7064
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7065
	}
7066
	function manage_activate_screen() {
7067
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7068
	}
7069
	function admin_jetpack_manage_notice() {
7070
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7071
	}
7072
	function opt_out_jetpack_manage_url() {
7073
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7074
	}
7075
	function opt_in_jetpack_manage_url() {
7076
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7077
	}
7078
	function opt_in_jetpack_manage_notice() {
7079
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7080
	}
7081
	function can_display_jetpack_manage_notice() {
7082
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7083
	}
7084
7085
	/**
7086
	 * Clean leftoveruser meta.
7087
	 *
7088
	 * Delete Jetpack-related user meta when it is no longer needed.
7089
	 *
7090
	 * @since 7.3.0
7091
	 *
7092
	 * @param int $user_id User ID being updated.
7093
	 */
7094
	public static function user_meta_cleanup( $user_id ) {
7095
		$meta_keys = array(
7096
			// AtD removed from Jetpack 7.3
7097
			'AtD_options',
7098
			'AtD_check_when',
7099
			'AtD_guess_lang',
7100
			'AtD_ignored_phrases',
7101
		);
7102
7103
		foreach ( $meta_keys as $meta_key ) {
7104
			if ( get_user_meta( $user_id, $meta_key ) ) {
7105
				delete_user_meta( $user_id, $meta_key );
7106
			}
7107
		}
7108
	}
7109
7110
	function is_active_and_not_development_mode( $maybe ) {
7111
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7112
			return false;
7113
		}
7114
		return true;
7115
	}
7116
}
7117