Completed
Push — update/sync-package ( 660c46 )
by
unknown
08:05
created

Jetpack::validate_onboarding_token_action()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 2
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
5
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
6
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
7
use Automattic\Jetpack\Constants;
8
use Automattic\Jetpack\Tracking;
9
use Automattic\Jetpack\Sync;
10
11
/*
12
Options:
13
jetpack_options (array)
14
	An array of options.
15
	@see Jetpack_Options::get_option_names()
16
17
jetpack_register (string)
18
	Temporary verification secrets.
19
20
jetpack_activated (int)
21
	1: the plugin was activated normally
22
	2: the plugin was activated on this site because of a network-wide activation
23
	3: the plugin was auto-installed
24
	4: the plugin was manually disconnected (but is still installed)
25
26
jetpack_active_modules (array)
27
	Array of active module slugs.
28
29
jetpack_do_activate (bool)
30
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
31
*/
32
33
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
34
35
class Jetpack {
36
	public $xmlrpc_server = null;
37
38
	private $xmlrpc_verification = null;
39
	private $rest_authentication_status = null;
40
41
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
42
43
	/**
44
	 * @var array The handles of styles that are concatenated into jetpack.css.
45
	 *
46
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
47
	 */
48
	public $concatenated_style_handles = array(
49
		'jetpack-carousel',
50
		'grunion.css',
51
		'the-neverending-homepage',
52
		'jetpack_likes',
53
		'jetpack_related-posts',
54
		'sharedaddy',
55
		'jetpack-slideshow',
56
		'presentations',
57
		'quiz',
58
		'jetpack-subscriptions',
59
		'jetpack-responsive-videos-style',
60
		'jetpack-social-menu',
61
		'tiled-gallery',
62
		'jetpack_display_posts_widget',
63
		'gravatar-profile-widget',
64
		'goodreads-widget',
65
		'jetpack_social_media_icons_widget',
66
		'jetpack-top-posts-widget',
67
		'jetpack_image_widget',
68
		'jetpack-my-community-widget',
69
		'jetpack-authors-widget',
70
		'wordads',
71
		'eu-cookie-law-style',
72
		'flickr-widget-style',
73
		'jetpack-search-widget',
74
		'jetpack-simple-payments-widget-style',
75
		'jetpack-widget-social-icons-styles',
76
	);
77
78
	/**
79
	 * Contains all assets that have had their URL rewritten to minified versions.
80
	 *
81
	 * @var array
82
	 */
83
	static $min_assets = array();
84
85
	public $plugins_to_deactivate = array(
86
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
87
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
88
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
89
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
90
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
91
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
92
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
93
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
94
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
95
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
96
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
97
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
98
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
99
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
100
	);
101
102
	static $capability_translations = array(
103
		'administrator' => 'manage_options',
104
		'editor'        => 'edit_others_posts',
105
		'author'        => 'publish_posts',
106
		'contributor'   => 'edit_posts',
107
		'subscriber'    => 'read',
108
	);
109
110
	/**
111
	 * Map of modules that have conflicts with plugins and should not be auto-activated
112
	 * if the plugins are active.  Used by filter_default_modules
113
	 *
114
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
115
	 * change `module-slug` and add this to your plugin:
116
	 *
117
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
118
	 * function my_jetpack_get_default_modules( $modules ) {
119
	 *     return array_diff( $modules, array( 'module-slug' ) );
120
	 * }
121
	 *
122
	 * @var array
123
	 */
124
	private $conflicting_plugins = array(
125
		'comments'          => array(
126
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
127
			'Disqus'                               => 'disqus-comment-system/disqus.php',
128
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
129
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
130
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
131
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
132
		),
133
		'comment-likes' => array(
134
			'Epoch'                                => 'epoch/plugincore.php',
135
		),
136
		'contact-form'      => array(
137
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
138
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
139
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
140
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
141
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
142
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
143
		),
144
		'minileven'         => array(
145
			'WPtouch'                              => 'wptouch/wptouch.php',
146
		),
147
		'latex'             => array(
148
			'LaTeX for WordPress'                  => 'latex/latex.php',
149
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
150
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
151
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
152
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
153
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
154
		),
155
		'protect'           => array(
156
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
157
			'Captcha'                              => 'captcha/captcha.php',
158
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
159
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
160
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
161
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
162
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
163
			'Security-protection'                  => 'security-protection/security-protection.php',
164
			'Login Security'                       => 'login-security/login-security.php',
165
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
166
			'Wordfence Security'                   => 'wordfence/wordfence.php',
167
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
168
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
169
		),
170
		'random-redirect'   => array(
171
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
172
		),
173
		'related-posts'     => array(
174
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
175
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
176
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
177
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
178
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
179
			'outbrain'                             => 'outbrain/outbrain.php',
180
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
181
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
182
		),
183
		'sharedaddy'        => array(
184
			'AddThis'                              => 'addthis/addthis_social_widget.php',
185
			'Add To Any'                           => 'add-to-any/add-to-any.php',
186
			'ShareThis'                            => 'share-this/sharethis.php',
187
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
188
		),
189
		'seo-tools' => array(
190
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
191
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
192
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
193
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
194
			'The SEO Framework'                    => 'autodescription/autodescription.php',
195
		),
196
		'verification-tools' => array(
197
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
198
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
199
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
200
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
201
			'The SEO Framework'                    => 'autodescription/autodescription.php',
202
		),
203
		'widget-visibility' => array(
204
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
205
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
206
		),
207
		'sitemaps' => array(
208
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
209
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
210
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
211
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
212
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
213
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
214
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
215
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
216
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
217
			'The SEO Framework'                    => 'autodescription/autodescription.php',
218
			'Sitemap'                              => 'sitemap/sitemap.php',
219
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
220
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
221
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
222
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
223
		),
224
		'lazy-images' => array(
225
			'Lazy Load'              => 'lazy-load/lazy-load.php',
226
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
227
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
228
		),
229
	);
230
231
	/**
232
	 * Plugins for which we turn off our Facebook OG Tags implementation.
233
	 *
234
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
235
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
236
	 *
237
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
238
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
239
	 */
240
	private $open_graph_conflicting_plugins = array(
241
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
242
		                                                         // 2 Click Social Media Buttons
243
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
244
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
245
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
246
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
247
		                                                         // Open Graph Meta Tags by Heateor
248
		'facebook/facebook.php',                                 // Facebook (official plugin)
249
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
250
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
251
		                                                         // Facebook Featured Image & OG Meta Tags
252
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
253
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
254
		                                                         // Facebook Open Graph Meta Tags for WordPress
255
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
256
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
257
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
258
		                                                         // Fedmich's Facebook Open Graph Meta
259
		'network-publisher/networkpub.php',                      // Network Publisher
260
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
261
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
262
		                                                         // NextScripts SNAP
263
		'og-tags/og-tags.php',                                   // OG Tags
264
		'opengraph/opengraph.php',                               // Open Graph
265
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
266
		                                                         // Open Graph Protocol Framework
267
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
268
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
269
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
270
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
271
		'sharepress/sharepress.php',                             // SharePress
272
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
273
		'social-discussions/social-discussions.php',             // Social Discussions
274
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
275
		'socialize/socialize.php',                               // Socialize
276
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
277
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
278
		                                                         // Tweet, Like, Google +1 and Share
279
		'wordbooker/wordbooker.php',                             // Wordbooker
280
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
281
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
282
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
283
		                                                         // WP Facebook Like Send & Open Graph Meta
284
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
285
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
286
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
287
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
288
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
289
	);
290
291
	/**
292
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
293
	 */
294
	private $twitter_cards_conflicting_plugins = array(
295
	//	'twitter/twitter.php',                       // The official one handles this on its own.
296
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
297
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
298
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
299
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
300
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
301
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
302
		'twitter-cards/twitter-cards.php',           // Twitter Cards
303
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
304
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
305
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
306
	);
307
308
	/**
309
	 * Message to display in admin_notice
310
	 * @var string
311
	 */
312
	public $message = '';
313
314
	/**
315
	 * Error to display in admin_notice
316
	 * @var string
317
	 */
318
	public $error = '';
319
320
	/**
321
	 * Modules that need more privacy description.
322
	 * @var string
323
	 */
324
	public $privacy_checks = '';
325
326
	/**
327
	 * Stats to record once the page loads
328
	 *
329
	 * @var array
330
	 */
331
	public $stats = array();
332
333
	/**
334
	 * Jetpack_Sync object
335
	 */
336
	public $sync;
337
338
	/**
339
	 * Verified data for JSON authorization request
340
	 */
341
	public $json_api_authorization_request = array();
342
343
	/**
344
	 * @var \Automattic\Jetpack\Connection\Manager
345
	 */
346
	protected $connection_manager;
347
348
	/**
349
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
350
	 */
351
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
352
353
	/**
354
	 * Holds the singleton instance of this class
355
	 * @since 2.3.3
356
	 * @var Jetpack
357
	 */
358
	static $instance = false;
359
360
	/**
361
	 * Singleton
362
	 * @static
363
	 */
364
	public static function init() {
365
		if ( ! self::$instance ) {
366
			self::$instance = new Jetpack;
367
368
			self::$instance->plugin_upgrade();
369
		}
370
371
		return self::$instance;
372
	}
373
374
	/**
375
	 * Must never be called statically
376
	 */
377
	function plugin_upgrade() {
378
		if ( Jetpack::is_active() ) {
379
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
380
			if ( JETPACK__VERSION != $version ) {
381
				// Prevent multiple upgrades at once - only a single process should trigger
382
				// an upgrade to avoid stampedes
383
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
384
					return;
385
				}
386
387
				// Set a short lock to prevent multiple instances of the upgrade
388
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
389
390
				// check which active modules actually exist and remove others from active_modules list
391
				$unfiltered_modules = Jetpack::get_active_modules();
392
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
393
				if ( array_diff( $unfiltered_modules, $modules ) ) {
394
					Jetpack::update_active_modules( $modules );
395
				}
396
397
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
398
399
				// Upgrade to 4.3.0
400
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
401
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
402
				}
403
404
				// Make sure Markdown for posts gets turned back on
405
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
406
					update_option( 'wpcom_publish_posts_with_markdown', true );
407
				}
408
409
				if ( did_action( 'wp_loaded' ) ) {
410
					self::upgrade_on_load();
411
				} else {
412
					add_action(
413
						'wp_loaded',
414
						array( __CLASS__, 'upgrade_on_load' )
415
					);
416
				}
417
			}
418
		}
419
	}
420
421
	/**
422
	 * Runs upgrade routines that need to have modules loaded.
423
	 */
424
	static function upgrade_on_load() {
425
426
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
427
		// This can happen in case Jetpack has been just upgraded and is
428
		// being initialized late during the page load. In this case we wait
429
		// until the next proper admin page load with Jetpack active.
430
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
431
			delete_transient( self::$plugin_upgrade_lock_key );
432
433
			return;
434
		}
435
436
		Jetpack::maybe_set_version_option();
437
438
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
439
			Jetpack_Widget_Conditions::migrate_post_type_rules();
440
		}
441
442
		if (
443
			class_exists( 'Jetpack_Sitemap_Manager' )
444
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
445
		) {
446
			do_action( 'jetpack_sitemaps_purge_data' );
447
		}
448
449
		delete_transient( self::$plugin_upgrade_lock_key );
450
	}
451
452
	/**
453
	 * Saves all the currently active modules to options.
454
	 * Also fires Action hooks for each newly activated and deactivated module.
455
	 *
456
	 * @param $modules Array Array of active modules to be saved in options.
457
	 *
458
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
Documentation introduced by
The doc-type $success could not be parsed: Unknown type name "$success" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
459
	 */
460
	static function update_active_modules( $modules ) {
461
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
462
		$active_modules       = Jetpack::get_active_modules();
463
		$new_active_modules   = array_diff( $modules, $current_modules );
464
465
		$new_inactive_modules = array_diff( $active_modules, $modules );
466
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
467
468
		$reindexed_modules    = array_values( $new_current_modules );
469
470
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
471
472
		foreach ( $new_active_modules as $module ) {
473
			/**
474
			 * Fires when a specific module is activated.
475
			 *
476
			 * @since 1.9.0
477
			 *
478
			 * @param string $module Module slug.
479
			 * @param boolean $success whether the module was activated. @since 4.2
480
			 */
481
			do_action( 'jetpack_activate_module', $module, $success );
482
			/**
483
			 * Fires when a module is activated.
484
			 * The dynamic part of the filter, $module, is the module slug.
485
			 *
486
			 * @since 1.9.0
487
			 *
488
			 * @param string $module Module slug.
489
			 */
490
			do_action( "jetpack_activate_module_$module", $module );
491
		}
492
493
		foreach ( $new_inactive_modules as $module ) {
494
			/**
495
			 * Fired after a module has been deactivated.
496
			 *
497
			 * @since 4.2.0
498
			 *
499
			 * @param string $module Module slug.
500
			 * @param boolean $success whether the module was deactivated.
501
			 */
502
			do_action( 'jetpack_deactivate_module', $module, $success );
503
			/**
504
			 * Fires when a module is deactivated.
505
			 * The dynamic part of the filter, $module, is the module slug.
506
			 *
507
			 * @since 1.9.0
508
			 *
509
			 * @param string $module Module slug.
510
			 */
511
			do_action( "jetpack_deactivate_module_$module", $module );
512
		}
513
514
		return $success;
515
	}
516
517
	static function delete_active_modules() {
518
		self::update_active_modules( array() );
519
	}
520
521
	/**
522
	 * Constructor.  Initializes WordPress hooks
523
	 */
524
	private function __construct() {
525
	    $this->sync = new Sync();
526
		/*
527
		 * Check for and alert any deprecated hooks
528
		 */
529
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
530
531
		/*
532
		 * Enable enhanced handling of previewing sites in Calypso
533
		 */
534
		if ( Jetpack::is_active() ) {
535
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
536
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
537
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
538
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
539
		}
540
541
		if ( self::jetpack_tos_agreed() ) {
542
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
543
			add_action( 'init', array( $tracking, 'init' ) );
544
		}
545
546
		/*
547
		 * Load things that should only be in Network Admin.
548
		 *
549
		 * For now blow away everything else until a more full
550
		 * understanding of what is needed at the network level is
551
		 * available
552
		 */
553
		if ( is_multisite() ) {
554
			Jetpack_Network::init();
555
		}
556
557
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
558
			return function() {
559
				return wp_generate_password( 32, false );
560
			};
561
		} );
562
563
		$this->connection_manager = new Connection_Manager( );
564
565
		/**
566
		 * Prepare Gutenberg Editor functionality
567
		 */
568
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
569
		Jetpack_Gutenberg::init();
570
		Jetpack_Gutenberg::load_independent_blocks();
571
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
572
573
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
574
575
		// Unlink user before deleting the user from .com
576
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
577
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
578
579
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
580
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
581
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
582
				define( 'XMLRPC_REQUEST', true );
583
			}
584
585
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
586
587
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
588
		}
589
590
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
591
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
592
593
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
594
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
595
596
			$this->require_jetpack_authentication();
597
598
			if ( Jetpack::is_active() ) {
599
				// Hack to preserve $HTTP_RAW_POST_DATA
600
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
601
602
				$signed = $this->verify_xml_rpc_signature();
603
				if ( $signed && ! is_wp_error( $signed ) ) {
604
					// The actual API methods.
605
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
606
				} else {
607
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
608
					// active Jetpack connection, so that additional users can link their account.
609
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
610
				}
611
			} else {
612
				new XMLRPC_Connector( $this->connection_manager );
613
614
				// The bootstrap API methods.
615
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
616
				$signed = $this->verify_xml_rpc_signature();
617
				if ( $signed && ! is_wp_error( $signed ) ) {
618
					// the jetpack Provision method is available for blog-token-signed requests
619
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
620
				}
621
			}
622
623
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
624
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
625
		} elseif (
626
			is_admin() &&
627
			isset( $_POST['action'] ) && (
628
				'jetpack_upload_file' == $_POST['action'] ||
629
				'jetpack_update_file' == $_POST['action']
630
			)
631
		) {
632
			$this->require_jetpack_authentication();
633
			$this->add_remote_request_handlers();
634
		} else {
635
			if ( Jetpack::is_active() ) {
636
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
637
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
638
			} else {
639
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
640
			}
641
		}
642
643
		if ( Jetpack::is_active() ) {
644
			Jetpack_Heartbeat::init();
645
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
646
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
647
				Jetpack_Search_Performance_Logger::init();
648
			}
649
		}
650
651
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
652
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
653
654
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
655
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
656
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
657
		}
658
659
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
660
661
		add_action( 'admin_init', array( $this, 'admin_init' ) );
662
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
663
664
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
665
666
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
667
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
668
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
669
670
		// returns HTTPS support status
671
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
672
673
		// JITM AJAX callback function
674
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
675
676
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
677
678
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
679
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
680
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
681
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
682
683
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
684
685
		/**
686
		 * These actions run checks to load additional files.
687
		 * They check for external files or plugins, so they need to run as late as possible.
688
		 */
689
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
690
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
691
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
692
693
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
694
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
695
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
696
697
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
698
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
699
700
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
701
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
702
703
		// A filter to control all just in time messages
704
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
705
706
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
707
708
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
709
		// We should make sure to only do this for front end links.
710
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
711
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
712
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
713
714
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
715
			//so they point moderation links on emails to Calypso
716
			jetpack_require_lib( 'functions.wp-notify' );
717
		}
718
719
		// Update the Jetpack plan from API on heartbeats
720
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
721
722
		/**
723
		 * This is the hack to concatenate all css files into one.
724
		 * For description and reasoning see the implode_frontend_css method
725
		 *
726
		 * Super late priority so we catch all the registered styles
727
		 */
728
		if( !is_admin() ) {
729
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
730
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
731
		}
732
733
734
		/**
735
		 * These are sync actions that we need to keep track of for jitms
736
		 */
737
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
738
739
		// Actually push the stats on shutdown.
740
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
741
			add_action( 'shutdown', array( $this, 'push_stats' ) );
742
		}
743
744
	}
745
746
	function initialize_rest_api_registration_connector() {
747
		new REST_Connector( $this->connection_manager );
748
	}
749
750
	/**
751
	 * This is ported over from the manage module, which has been deprecated and baked in here.
752
	 *
753
	 * @param $domains
754
	 */
755
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
756
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
757
	}
758
759
	/**
760
	 * Return $domains, with 'wordpress.com' appended.
761
	 * This is ported over from the manage module, which has been deprecated and baked in here.
762
	 *
763
	 * @param $domains
764
	 * @return array
765
	 */
766
	function allow_wpcom_domain( $domains ) {
767
		if ( empty( $domains ) ) {
768
			$domains = array();
769
		}
770
		$domains[] = 'wordpress.com';
771
		return array_unique( $domains );
772
	}
773
774
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
775
		$post = get_post( $post_id );
776
777
		if ( empty( $post ) ) {
778
			return $default_url;
779
		}
780
781
		$post_type = $post->post_type;
782
783
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
784
		// https://en.support.wordpress.com/custom-post-types/
785
		$allowed_post_types = array(
786
			'post' => 'post',
787
			'page' => 'page',
788
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
789
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
790
		);
791
792
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
793
			return $default_url;
794
		}
795
796
		$path_prefix = $allowed_post_types[ $post_type ];
797
798
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
799
800
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
801
	}
802
803
	function point_edit_comment_links_to_calypso( $url ) {
804
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
805
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
The variable $query_args does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
806
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
807
			Jetpack::build_raw_urls( get_home_url() ),
808
			$query_args['amp;c']
809
		) );
810
	}
811
812
	function jetpack_track_last_sync_callback( $params ) {
813
		/**
814
		 * Filter to turn off jitm caching
815
		 *
816
		 * @since 5.4.0
817
		 *
818
		 * @param bool false Whether to cache just in time messages
819
		 */
820
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
821
			return $params;
822
		}
823
824
		if ( is_array( $params ) && isset( $params[0] ) ) {
825
			$option = $params[0];
826
			if ( 'active_plugins' === $option ) {
827
				// use the cache if we can, but not terribly important if it gets evicted
828
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
829
			}
830
		}
831
832
		return $params;
833
	}
834
835
	function jetpack_connection_banner_callback() {
836
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
837
838
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
839
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
840
			wp_send_json_success();
841
		}
842
843
		wp_die();
844
	}
845
846
	/**
847
	 * Removes all XML-RPC methods that are not `jetpack.*`.
848
	 * Only used in our alternate XML-RPC endpoint, where we want to
849
	 * ensure that Core and other plugins' methods are not exposed.
850
	 *
851
	 * @param array $methods
852
	 * @return array filtered $methods
853
	 */
854
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
855
		$jetpack_methods = array();
856
857
		foreach ( $methods as $method => $callback ) {
858
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
859
				$jetpack_methods[ $method ] = $callback;
860
			}
861
		}
862
863
		return $jetpack_methods;
864
	}
865
866
	/**
867
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
868
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
869
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
870
	 * which is accessible via a different URI. Most of the below is copied directly
871
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
872
	 */
873
	function alternate_xmlrpc() {
874
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
875
		global $HTTP_RAW_POST_DATA;
876
877
		// Some browser-embedded clients send cookies. We don't want them.
878
		$_COOKIE = array();
879
880
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
881
		// but we can do it ourself.
882
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
883
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
884
		}
885
886
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
887
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
888
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
889
		}
890
891
		// phpcs:enable
892
893
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
894
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
895
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
896
897
		/**
898
		 * Filters the class used for handling XML-RPC requests.
899
		 *
900
		 * @since 3.1.0
901
		 *
902
		 * @param string $class The name of the XML-RPC server class.
903
		 */
904
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
905
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
906
907
		// Fire off the request
908
		nocache_headers();
909
		$wp_xmlrpc_server->serve_request();
910
911
		exit;
912
	}
913
914
	/**
915
	 * The callback for the JITM ajax requests.
916
	 */
917
	function jetpack_jitm_ajax_callback() {
918
		// Check for nonce
919
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
920
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
921
		}
922
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
923
			$module_slug = $_REQUEST['jitmModule'];
924
			Jetpack::log( 'activate', $module_slug );
925
			Jetpack::activate_module( $module_slug, false, false );
926
			Jetpack::state( 'message', 'no_message' );
927
928
			//A Jetpack module is being activated through a JITM, track it
929
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
930
			$this->do_stats( 'server_side' );
931
932
			wp_send_json_success();
933
		}
934
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
935
			// get the hide_jitm options array
936
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
937
			$module_slug = $_REQUEST['jitmModule'];
938
939
			if( ! $jetpack_hide_jitm ) {
940
				$jetpack_hide_jitm = array(
941
					$module_slug => 'hide'
942
				);
943
			} else {
944
				$jetpack_hide_jitm[$module_slug] = 'hide';
945
			}
946
947
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
948
949
			//jitm is being dismissed forever, track it
950
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
951
			$this->do_stats( 'server_side' );
952
953
			wp_send_json_success();
954
		}
955 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
956
			$module_slug = $_REQUEST['jitmModule'];
957
958
			// User went to WordPress.com, track this
959
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
960
			$this->do_stats( 'server_side' );
961
962
			wp_send_json_success();
963
		}
964 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
965
			$track = $_REQUEST['jitmModule'];
966
967
			// User is viewing JITM, track it.
968
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
969
			$this->do_stats( 'server_side' );
970
971
			wp_send_json_success();
972
		}
973
	}
974
975
	/**
976
	 * If there are any stats that need to be pushed, but haven't been, push them now.
977
	 */
978
	function push_stats() {
979
		if ( ! empty( $this->stats ) ) {
980
			$this->do_stats( 'server_side' );
981
		}
982
	}
983
984
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
985
		switch( $cap ) {
986
			case 'jetpack_connect' :
987
			case 'jetpack_reconnect' :
988
				if ( Jetpack::is_development_mode() ) {
989
					$caps = array( 'do_not_allow' );
990
					break;
991
				}
992
				/**
993
				 * Pass through. If it's not development mode, these should match disconnect.
994
				 * Let users disconnect if it's development mode, just in case things glitch.
995
				 */
996
			case 'jetpack_disconnect' :
997
				/**
998
				 * In multisite, can individual site admins manage their own connection?
999
				 *
1000
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1001
				 */
1002
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1003
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1004
						/**
1005
						 * We need to update the option name -- it's terribly unclear which
1006
						 * direction the override goes.
1007
						 *
1008
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1009
						 */
1010
						$caps = array( 'do_not_allow' );
1011
						break;
1012
					}
1013
				}
1014
1015
				$caps = array( 'manage_options' );
1016
				break;
1017
			case 'jetpack_manage_modules' :
1018
			case 'jetpack_activate_modules' :
1019
			case 'jetpack_deactivate_modules' :
1020
				$caps = array( 'manage_options' );
1021
				break;
1022
			case 'jetpack_configure_modules' :
1023
				$caps = array( 'manage_options' );
1024
				break;
1025
			case 'jetpack_manage_autoupdates' :
1026
				$caps = array(
1027
					'manage_options',
1028
					'update_plugins',
1029
				);
1030
				break;
1031
			case 'jetpack_network_admin_page':
1032
			case 'jetpack_network_settings_page':
1033
				$caps = array( 'manage_network_plugins' );
1034
				break;
1035
			case 'jetpack_network_sites_page':
1036
				$caps = array( 'manage_sites' );
1037
				break;
1038
			case 'jetpack_admin_page' :
1039
				if ( Jetpack::is_development_mode() ) {
1040
					$caps = array( 'manage_options' );
1041
					break;
1042
				} else {
1043
					$caps = array( 'read' );
1044
				}
1045
				break;
1046
			case 'jetpack_connect_user' :
1047
				if ( Jetpack::is_development_mode() ) {
1048
					$caps = array( 'do_not_allow' );
1049
					break;
1050
				}
1051
				$caps = array( 'read' );
1052
				break;
1053
		}
1054
		return $caps;
1055
	}
1056
1057
	function require_jetpack_authentication() {
1058
		// Don't let anyone authenticate
1059
		$_COOKIE = array();
1060
		remove_all_filters( 'authenticate' );
1061
		remove_all_actions( 'wp_login_failed' );
1062
1063
		if ( Jetpack::is_active() ) {
1064
			// Allow Jetpack authentication
1065
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1066
		}
1067
	}
1068
1069
	/**
1070
	 * Load language files
1071
	 * @action plugins_loaded
1072
	 */
1073
	public static function plugin_textdomain() {
1074
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1075
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1076
	}
1077
1078
	/**
1079
	 * Register assets for use in various modules and the Jetpack admin page.
1080
	 *
1081
	 * @uses wp_script_is, wp_register_script, plugins_url
1082
	 * @action wp_loaded
1083
	 * @return null
1084
	 */
1085
	public function register_assets() {
1086
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1087
			wp_register_script(
1088
				'spin',
1089
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1090
				false,
1091
				'1.3'
1092
			);
1093
		}
1094
1095
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1096
			wp_register_script(
1097
				'jquery.spin',
1098
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1099
				array( 'jquery', 'spin' ),
1100
				'1.3'
1101
			);
1102
		}
1103
1104 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1105
			wp_register_script(
1106
				'jetpack-gallery-settings',
1107
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1108
				array( 'media-views' ),
1109
				'20121225'
1110
			);
1111
		}
1112
1113
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1114
			wp_register_script(
1115
				'jetpack-twitter-timeline',
1116
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1117
				array( 'jquery' ),
1118
				'4.0.0',
1119
				true
1120
			);
1121
		}
1122
1123
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1124
			wp_register_script(
1125
				'jetpack-facebook-embed',
1126
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1127
				array( 'jquery' ),
1128
				null,
1129
				true
1130
			);
1131
1132
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1133
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1134
			if ( ! is_numeric( $fb_app_id ) ) {
1135
				$fb_app_id = '';
1136
			}
1137
			wp_localize_script(
1138
				'jetpack-facebook-embed',
1139
				'jpfbembed',
1140
				array(
1141
					'appid' => $fb_app_id,
1142
					'locale' => $this->get_locale(),
1143
				)
1144
			);
1145
		}
1146
1147
		/**
1148
		 * As jetpack_register_genericons is by default fired off a hook,
1149
		 * the hook may have already fired by this point.
1150
		 * So, let's just trigger it manually.
1151
		 */
1152
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1153
		jetpack_register_genericons();
1154
1155
		/**
1156
		 * Register the social logos
1157
		 */
1158
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1159
		jetpack_register_social_logos();
1160
1161 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1162
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1163
	}
1164
1165
	/**
1166
	 * Guess locale from language code.
1167
	 *
1168
	 * @param string $lang Language code.
1169
	 * @return string|bool
1170
	 */
1171 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1172
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1173
			return 'en_US';
1174
		}
1175
1176
		if ( ! class_exists( 'GP_Locales' ) ) {
1177
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1178
				return false;
1179
			}
1180
1181
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1182
		}
1183
1184
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1185
			// WP.com: get_locale() returns 'it'
1186
			$locale = GP_Locales::by_slug( $lang );
1187
		} else {
1188
			// Jetpack: get_locale() returns 'it_IT';
1189
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1190
		}
1191
1192
		if ( ! $locale ) {
1193
			return false;
1194
		}
1195
1196
		if ( empty( $locale->facebook_locale ) ) {
1197
			if ( empty( $locale->wp_locale ) ) {
1198
				return false;
1199
			} else {
1200
				// Facebook SDK is smart enough to fall back to en_US if a
1201
				// locale isn't supported. Since supported Facebook locales
1202
				// can fall out of sync, we'll attempt to use the known
1203
				// wp_locale value and rely on said fallback.
1204
				return $locale->wp_locale;
1205
			}
1206
		}
1207
1208
		return $locale->facebook_locale;
1209
	}
1210
1211
	/**
1212
	 * Get the locale.
1213
	 *
1214
	 * @return string|bool
1215
	 */
1216
	function get_locale() {
1217
		$locale = $this->guess_locale_from_lang( get_locale() );
1218
1219
		if ( ! $locale ) {
1220
			$locale = 'en_US';
1221
		}
1222
1223
		return $locale;
1224
	}
1225
1226
	/**
1227
	 * Device Pixels support
1228
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1229
	 */
1230
	function devicepx() {
1231
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1232
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1233
		}
1234
	}
1235
1236
	/**
1237
	 * Return the network_site_url so that .com knows what network this site is a part of.
1238
	 * @param  bool $option
1239
	 * @return string
1240
	 */
1241
	public function jetpack_main_network_site_option( $option ) {
1242
		return network_site_url();
1243
	}
1244
	/**
1245
	 * Network Name.
1246
	 */
1247
	static function network_name( $option = null ) {
1248
		global $current_site;
1249
		return $current_site->site_name;
1250
	}
1251
	/**
1252
	 * Does the network allow new user and site registrations.
1253
	 * @return string
1254
	 */
1255
	static function network_allow_new_registrations( $option = null ) {
1256
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1257
	}
1258
	/**
1259
	 * Does the network allow admins to add new users.
1260
	 * @return boolian
1261
	 */
1262
	static function network_add_new_users( $option = null ) {
1263
		return (bool) get_site_option( 'add_new_users' );
1264
	}
1265
	/**
1266
	 * File upload psace left per site in MB.
1267
	 *  -1 means NO LIMIT.
1268
	 * @return number
1269
	 */
1270
	static function network_site_upload_space( $option = null ) {
1271
		// value in MB
1272
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1273
	}
1274
1275
	/**
1276
	 * Network allowed file types.
1277
	 * @return string
1278
	 */
1279
	static function network_upload_file_types( $option = null ) {
1280
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1281
	}
1282
1283
	/**
1284
	 * Maximum file upload size set by the network.
1285
	 * @return number
1286
	 */
1287
	static function network_max_upload_file_size( $option = null ) {
1288
		// value in KB
1289
		return get_site_option( 'fileupload_maxk', 300 );
1290
	}
1291
1292
	/**
1293
	 * Lets us know if a site allows admins to manage the network.
1294
	 * @return array
1295
	 */
1296
	static function network_enable_administration_menus( $option = null ) {
1297
		return get_site_option( 'menu_items' );
1298
	}
1299
1300
	/**
1301
	 * If a user has been promoted to or demoted from admin, we need to clear the
1302
	 * jetpack_other_linked_admins transient.
1303
	 *
1304
	 * @since 4.3.2
1305
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1306
	 *
1307
	 * @param int    $user_id   The user ID whose role changed.
1308
	 * @param string $role      The new role.
1309
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_roles not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1310
	 */
1311
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1312
		if ( 'administrator' == $role
1313
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1314
			|| is_null( $old_roles )
1315
		) {
1316
			delete_transient( 'jetpack_other_linked_admins' );
1317
		}
1318
	}
1319
1320
	/**
1321
	 * Checks to see if there are any other users available to become primary
1322
	 * Users must both:
1323
	 * - Be linked to wpcom
1324
	 * - Be an admin
1325
	 *
1326
	 * @return mixed False if no other users are linked, Int if there are.
1327
	 */
1328
	static function get_other_linked_admins() {
1329
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1330
1331
		if ( false === $other_linked_users ) {
1332
			$admins = get_users( array( 'role' => 'administrator' ) );
1333
			if ( count( $admins ) > 1 ) {
1334
				$available = array();
1335
				foreach ( $admins as $admin ) {
1336
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1337
						$available[] = $admin->ID;
1338
					}
1339
				}
1340
1341
				$count_connected_admins = count( $available );
1342
				if ( count( $available ) > 1 ) {
1343
					$other_linked_users = $count_connected_admins;
1344
				} else {
1345
					$other_linked_users = 0;
1346
				}
1347
			} else {
1348
				$other_linked_users = 0;
1349
			}
1350
1351
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1352
		}
1353
1354
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1355
	}
1356
1357
	/**
1358
	 * Return whether we are dealing with a multi network setup or not.
1359
	 * The reason we are type casting this is because we want to avoid the situation where
1360
	 * the result is false since when is_main_network_option return false it cases
1361
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1362
	 * database which could be set to anything as opposed to what this function returns.
1363
	 * @param  bool  $option
1364
	 *
1365
	 * @return boolean
1366
	 */
1367
	public function is_main_network_option( $option ) {
1368
		// return '1' or ''
1369
		return (string) (bool) Jetpack::is_multi_network();
1370
	}
1371
1372
	/**
1373
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1374
	 *
1375
	 * @param  string  $option
1376
	 * @return boolean
1377
	 */
1378
	public function is_multisite( $option ) {
1379
		return (string) (bool) is_multisite();
1380
	}
1381
1382
	/**
1383
	 * Implemented since there is no core is multi network function
1384
	 * Right now there is no way to tell if we which network is the dominant network on the system
1385
	 *
1386
	 * @since  3.3
1387
	 * @return boolean
1388
	 */
1389
	public static function is_multi_network() {
1390
		global  $wpdb;
1391
1392
		// if we don't have a multi site setup no need to do any more
1393
		if ( ! is_multisite() ) {
1394
			return false;
1395
		}
1396
1397
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1398
		if ( $num_sites > 1 ) {
1399
			return true;
1400
		} else {
1401
			return false;
1402
		}
1403
	}
1404
1405
	/**
1406
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1407
	 * @return null
1408
	 */
1409
	function update_jetpack_main_network_site_option() {
1410
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1411
	}
1412
	/**
1413
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1414
	 *
1415
	 */
1416
	function update_jetpack_network_settings() {
1417
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1418
		// Only sync this info for the main network site.
1419
	}
1420
1421
	/**
1422
	 * Get back if the current site is single user site.
1423
	 *
1424
	 * @return bool
1425
	 */
1426
	public static function is_single_user_site() {
1427
		global $wpdb;
1428
1429 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1430
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1431
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1432
		}
1433
		return 1 === (int) $some_users;
1434
	}
1435
1436
	/**
1437
	 * Returns true if the site has file write access false otherwise.
1438
	 * @return string ( '1' | '0' )
1439
	 **/
1440
	public static function file_system_write_access() {
1441
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1442
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1443
		}
1444
1445
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1446
1447
		$filesystem_method = get_filesystem_method();
1448
		if ( $filesystem_method === 'direct' ) {
1449
			return 1;
1450
		}
1451
1452
		ob_start();
1453
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1454
		ob_end_clean();
1455
		if ( $filesystem_credentials_are_stored ) {
1456
			return 1;
1457
		}
1458
		return 0;
1459
	}
1460
1461
	/**
1462
	 * Finds out if a site is using a version control system.
1463
	 * @return string ( '1' | '0' )
1464
	 **/
1465
	public static function is_version_controlled() {
1466
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1467
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1468
	}
1469
1470
	/**
1471
	 * Determines whether the current theme supports featured images or not.
1472
	 * @return string ( '1' | '0' )
1473
	 */
1474
	public static function featured_images_enabled() {
1475
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1476
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1477
	}
1478
1479
	/**
1480
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1481
	 *
1482
	 * @deprecated 4.7 use get_avatar_url instead.
1483
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1484
	 * @param int $size Size of the avatar image
1485
	 * @param string $default URL to a default image to use if no avatar is available
1486
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1487
	 *
1488
	 * @return array
1489
	 */
1490
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1491
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1492
		return get_avatar_url( $id_or_email, array(
1493
			'size' => $size,
1494
			'default' => $default,
1495
			'force_default' => $force_display,
1496
		) );
1497
	}
1498
1499
	/**
1500
	 * jetpack_updates is saved in the following schema:
1501
	 *
1502
	 * array (
1503
	 *      'plugins'                       => (int) Number of plugin updates available.
1504
	 *      'themes'                        => (int) Number of theme updates available.
1505
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1506
	 *      'translations'                  => (int) Number of translation updates available.
1507
	 *      'total'                         => (int) Total of all available updates.
1508
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1509
	 * )
1510
	 * @return array
1511
	 */
1512
	public static function get_updates() {
1513
		$update_data = wp_get_update_data();
1514
1515
		// Stores the individual update counts as well as the total count.
1516
		if ( isset( $update_data['counts'] ) ) {
1517
			$updates = $update_data['counts'];
1518
		}
1519
1520
		// If we need to update WordPress core, let's find the latest version number.
1521 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1522
			$cur = get_preferred_from_update_core();
1523
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1524
				$updates['wp_update_version'] = $cur->current;
1525
			}
1526
		}
1527
		return isset( $updates ) ? $updates : array();
1528
	}
1529
1530
	public static function get_update_details() {
1531
		$update_details = array(
1532
			'update_core' => get_site_transient( 'update_core' ),
1533
			'update_plugins' => get_site_transient( 'update_plugins' ),
1534
			'update_themes' => get_site_transient( 'update_themes' ),
1535
		);
1536
		return $update_details;
1537
	}
1538
1539
	public static function refresh_update_data() {
1540
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1541
1542
	}
1543
1544
	public static function refresh_theme_data() {
1545
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1546
	}
1547
1548
	/**
1549
	 * Is Jetpack active?
1550
	 */
1551
	public static function is_active() {
1552
		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...
1553
	}
1554
1555
	/**
1556
	 * Make an API call to WordPress.com for plan status
1557
	 *
1558
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1559
	 *
1560
	 * @return bool True if plan is updated, false if no update
1561
	 */
1562
	public static function refresh_active_plan_from_wpcom() {
1563
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1564
		return Jetpack_Plan::refresh_from_wpcom();
1565
	}
1566
1567
	/**
1568
	 * Get the plan that this Jetpack site is currently using
1569
	 *
1570
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1571
	 * @return array Active Jetpack plan details.
1572
	 */
1573
	public static function get_active_plan() {
1574
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1575
		return Jetpack_Plan::get();
1576
	}
1577
1578
	/**
1579
	 * Determine whether the active plan supports a particular feature
1580
	 *
1581
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1582
	 * @return bool True if plan supports feature, false if not.
1583
	 */
1584
	public static function active_plan_supports( $feature ) {
1585
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1586
		return Jetpack_Plan::supports( $feature );
1587
	}
1588
1589
	/**
1590
	 * Is Jetpack in development (offline) mode?
1591
	 */
1592
	public static function is_development_mode() {
1593
		$development_mode = false;
1594
1595
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1596
			$development_mode = JETPACK_DEV_DEBUG;
1597
		} elseif ( $site_url = site_url() ) {
1598
			$development_mode = false === strpos( $site_url, '.' );
1599
		}
1600
1601
		/**
1602
		 * Filters Jetpack's development mode.
1603
		 *
1604
		 * @see https://jetpack.com/support/development-mode/
1605
		 *
1606
		 * @since 2.2.1
1607
		 *
1608
		 * @param bool $development_mode Is Jetpack's development mode active.
1609
		 */
1610
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1611
		return $development_mode;
1612
	}
1613
1614
	/**
1615
	 * Whether the site is currently onboarding or not.
1616
	 * A site is considered as being onboarded if it currently has an onboarding token.
1617
	 *
1618
	 * @since 5.8
1619
	 *
1620
	 * @access public
1621
	 * @static
1622
	 *
1623
	 * @return bool True if the site is currently onboarding, false otherwise
1624
	 */
1625
	public static function is_onboarding() {
1626
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1627
	}
1628
1629
	/**
1630
	 * Determines reason for Jetpack development mode.
1631
	 */
1632
	public static function development_mode_trigger_text() {
1633
		if ( ! Jetpack::is_development_mode() ) {
1634
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1635
		}
1636
1637
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1638
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1639
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1640
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1641
		} else {
1642
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1643
		}
1644
1645
		return $notice;
1646
1647
	}
1648
	/**
1649
	* Get Jetpack development mode notice text and notice class.
1650
	*
1651
	* Mirrors the checks made in Jetpack::is_development_mode
1652
	*
1653
	*/
1654
	public static function show_development_mode_notice() {
1655 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1656
			$notice = sprintf(
1657
			/* translators: %s is a URL */
1658
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1659
				'https://jetpack.com/support/development-mode/'
1660
			);
1661
1662
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1663
1664
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1665
		}
1666
1667
		// Throw up a notice if using a development version and as for feedback.
1668
		if ( Jetpack::is_development_version() ) {
1669
			/* translators: %s is a URL */
1670
			$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/' );
1671
1672
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1673
		}
1674
		// Throw up a notice if using staging mode
1675
		if ( Jetpack::is_staging_site() ) {
1676
			/* translators: %s is a URL */
1677
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1678
1679
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1680
		}
1681
	}
1682
1683
	/**
1684
	 * Whether Jetpack's version maps to a public release, or a development version.
1685
	 */
1686
	public static function is_development_version() {
1687
		/**
1688
		 * Allows filtering whether this is a development version of Jetpack.
1689
		 *
1690
		 * This filter is especially useful for tests.
1691
		 *
1692
		 * @since 4.3.0
1693
		 *
1694
		 * @param bool $development_version Is this a develoment version of Jetpack?
1695
		 */
1696
		return (bool) apply_filters(
1697
			'jetpack_development_version',
1698
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1699
		);
1700
	}
1701
1702
	/**
1703
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1704
	 */
1705
	public static function is_user_connected( $user_id = false ) {
1706
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1707
		if ( ! $user_id ) {
1708
			return false;
1709
		}
1710
1711
		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...
1712
	}
1713
1714
	/**
1715
	 * Get the wpcom user data of the current|specified connected user.
1716
	 */
1717 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1718
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1719
		if ( ! $user_id ) {
1720
			$user_id = get_current_user_id();
1721
		}
1722
1723
		$transient_key = "jetpack_connected_user_data_$user_id";
1724
1725
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1726
			return $cached_user_data;
1727
		}
1728
1729
		Jetpack::load_xml_rpc_client();
1730
		$xml = new Jetpack_IXR_Client( array(
1731
			'user_id' => $user_id,
1732
		) );
1733
		$xml->query( 'wpcom.getUser' );
1734
		if ( ! $xml->isError() ) {
1735
			$user_data = $xml->getResponse();
1736
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1737
			return $user_data;
1738
		}
1739
1740
		return false;
1741
	}
1742
1743
	/**
1744
	 * Get the wpcom email of the current|specified connected user.
1745
	 */
1746 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1747
		if ( ! $user_id ) {
1748
			$user_id = get_current_user_id();
1749
		}
1750
		Jetpack::load_xml_rpc_client();
1751
		$xml = new Jetpack_IXR_Client( array(
1752
			'user_id' => $user_id,
1753
		) );
1754
		$xml->query( 'wpcom.getUserEmail' );
1755
		if ( ! $xml->isError() ) {
1756
			return $xml->getResponse();
1757
		}
1758
		return false;
1759
	}
1760
1761
	/**
1762
	 * Get the wpcom email of the master user.
1763
	 */
1764
	public static function get_master_user_email() {
1765
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1766
		if ( $master_user_id ) {
1767
			return self::get_connected_user_email( $master_user_id );
1768
		}
1769
		return '';
1770
	}
1771
1772
	function current_user_is_connection_owner() {
1773
		$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...
1774
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1775
	}
1776
1777
	/**
1778
	 * Gets current user IP address.
1779
	 *
1780
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1781
	 *
1782
	 * @return string                  Current user IP address.
1783
	 */
1784
	public static function current_user_ip( $check_all_headers = false ) {
1785
		if ( $check_all_headers ) {
1786
			foreach ( array(
1787
				'HTTP_CF_CONNECTING_IP',
1788
				'HTTP_CLIENT_IP',
1789
				'HTTP_X_FORWARDED_FOR',
1790
				'HTTP_X_FORWARDED',
1791
				'HTTP_X_CLUSTER_CLIENT_IP',
1792
				'HTTP_FORWARDED_FOR',
1793
				'HTTP_FORWARDED',
1794
				'HTTP_VIA',
1795
			) as $key ) {
1796
				if ( ! empty( $_SERVER[ $key ] ) ) {
1797
					return $_SERVER[ $key ];
1798
				}
1799
			}
1800
		}
1801
1802
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1803
	}
1804
1805
	/**
1806
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1807
	 */
1808
	function extra_oembed_providers() {
1809
		// Cloudup: https://dev.cloudup.com/#oembed
1810
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1811
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1812
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1813
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1814
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1815
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1816
	}
1817
1818
	/**
1819
	 * Synchronize connected user role changes
1820
	 */
1821
	function user_role_change( $user_id ) {
1822
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1823
		Jetpack_Sync_Users::user_role_change( $user_id );
1824
	}
1825
1826
	/**
1827
	 * Loads the currently active modules.
1828
	 */
1829
	public static function load_modules() {
1830
		if (
1831
			! self::is_active()
1832
			&& ! self::is_development_mode()
1833
			&& ! self::is_onboarding()
1834
			&& (
1835
				! is_multisite()
1836
				|| ! get_site_option( 'jetpack_protect_active' )
1837
			)
1838
		) {
1839
			return;
1840
		}
1841
1842
		$version = Jetpack_Options::get_option( 'version' );
1843 View Code Duplication
		if ( ! $version ) {
1844
			$version = $old_version = JETPACK__VERSION . ':' . time();
1845
			/** This action is documented in class.jetpack.php */
1846
			do_action( 'updating_jetpack_version', $version, false );
1847
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1848
		}
1849
		list( $version ) = explode( ':', $version );
1850
1851
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1852
1853
		$modules_data = array();
1854
1855
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1856
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1857
			$updated_modules = array();
1858
			foreach ( $modules as $module ) {
1859
				$modules_data[ $module ] = Jetpack::get_module( $module );
1860
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1861
					continue;
1862
				}
1863
1864
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1865
					continue;
1866
				}
1867
1868
				$updated_modules[] = $module;
1869
			}
1870
1871
			$modules = array_diff( $modules, $updated_modules );
1872
		}
1873
1874
		$is_development_mode = Jetpack::is_development_mode();
1875
1876
		foreach ( $modules as $index => $module ) {
1877
			// If we're in dev mode, disable modules requiring a connection
1878
			if ( $is_development_mode ) {
1879
				// Prime the pump if we need to
1880
				if ( empty( $modules_data[ $module ] ) ) {
1881
					$modules_data[ $module ] = Jetpack::get_module( $module );
1882
				}
1883
				// If the module requires a connection, but we're in local mode, don't include it.
1884
				if ( $modules_data[ $module ]['requires_connection'] ) {
1885
					continue;
1886
				}
1887
			}
1888
1889
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1890
				continue;
1891
			}
1892
1893
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1894
				unset( $modules[ $index ] );
1895
				self::update_active_modules( array_values( $modules ) );
1896
				continue;
1897
			}
1898
1899
			/**
1900
			 * Fires when a specific module is loaded.
1901
			 * The dynamic part of the hook, $module, is the module slug.
1902
			 *
1903
			 * @since 1.1.0
1904
			 */
1905
			do_action( 'jetpack_module_loaded_' . $module );
1906
		}
1907
1908
		/**
1909
		 * Fires when all the modules are loaded.
1910
		 *
1911
		 * @since 1.1.0
1912
		 */
1913
		do_action( 'jetpack_modules_loaded' );
1914
1915
		// 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.
1916
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1917
	}
1918
1919
	/**
1920
	 * Check if Jetpack's REST API compat file should be included
1921
	 * @action plugins_loaded
1922
	 * @return null
1923
	 */
1924
	public function check_rest_api_compat() {
1925
		/**
1926
		 * Filters the list of REST API compat files to be included.
1927
		 *
1928
		 * @since 2.2.5
1929
		 *
1930
		 * @param array $args Array of REST API compat files to include.
1931
		 */
1932
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1933
1934
		if ( function_exists( 'bbpress' ) )
1935
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1936
1937
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1938
			require_once $_jetpack_rest_api_compat_include;
1939
	}
1940
1941
	/**
1942
	 * Gets all plugins currently active in values, regardless of whether they're
1943
	 * traditionally activated or network activated.
1944
	 *
1945
	 * @todo Store the result in core's object cache maybe?
1946
	 */
1947
	public static function get_active_plugins() {
1948
		$active_plugins = (array) get_option( 'active_plugins', array() );
1949
1950
		if ( is_multisite() ) {
1951
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1952
			// whereas active_plugins stores them in the values.
1953
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1954
			if ( $network_plugins ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $network_plugins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1955
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1956
			}
1957
		}
1958
1959
		sort( $active_plugins );
1960
1961
		return array_unique( $active_plugins );
1962
	}
1963
1964
	/**
1965
	 * Gets and parses additional plugin data to send with the heartbeat data
1966
	 *
1967
	 * @since 3.8.1
1968
	 *
1969
	 * @return array Array of plugin data
1970
	 */
1971
	public static function get_parsed_plugin_data() {
1972
		if ( ! function_exists( 'get_plugins' ) ) {
1973
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1974
		}
1975
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1976
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1977
		$active_plugins = Jetpack::get_active_plugins();
1978
1979
		$plugins = array();
1980
		foreach ( $all_plugins as $path => $plugin_data ) {
1981
			$plugins[ $path ] = array(
1982
					'is_active' => in_array( $path, $active_plugins ),
1983
					'file'      => $path,
1984
					'name'      => $plugin_data['Name'],
1985
					'version'   => $plugin_data['Version'],
1986
					'author'    => $plugin_data['Author'],
1987
			);
1988
		}
1989
1990
		return $plugins;
1991
	}
1992
1993
	/**
1994
	 * Gets and parses theme data to send with the heartbeat data
1995
	 *
1996
	 * @since 3.8.1
1997
	 *
1998
	 * @return array Array of theme data
1999
	 */
2000
	public static function get_parsed_theme_data() {
2001
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2002
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2003
2004
		$themes = array();
2005
		foreach ( $all_themes as $slug => $theme_data ) {
2006
			$theme_headers = array();
2007
			foreach ( $header_keys as $header_key ) {
2008
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2009
			}
2010
2011
			$themes[ $slug ] = array(
2012
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2013
					'slug' => $slug,
2014
					'theme_root' => $theme_data->get_theme_root_uri(),
2015
					'parent' => $theme_data->parent(),
2016
					'headers' => $theme_headers
2017
			);
2018
		}
2019
2020
		return $themes;
2021
	}
2022
2023
	/**
2024
	 * Checks whether a specific plugin is active.
2025
	 *
2026
	 * We don't want to store these in a static variable, in case
2027
	 * there are switch_to_blog() calls involved.
2028
	 */
2029
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2030
		return in_array( $plugin, self::get_active_plugins() );
2031
	}
2032
2033
	/**
2034
	 * Check if Jetpack's Open Graph tags should be used.
2035
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2036
	 *
2037
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2038
	 * @action plugins_loaded
2039
	 * @return null
2040
	 */
2041
	public function check_open_graph() {
2042
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2043
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2044
		}
2045
2046
		$active_plugins = self::get_active_plugins();
2047
2048
		if ( ! empty( $active_plugins ) ) {
2049
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2050
				if ( in_array( $plugin, $active_plugins ) ) {
2051
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2052
					break;
2053
				}
2054
			}
2055
		}
2056
2057
		/**
2058
		 * Allow the addition of Open Graph Meta Tags to all pages.
2059
		 *
2060
		 * @since 2.0.3
2061
		 *
2062
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2063
		 */
2064
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2065
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2066
		}
2067
	}
2068
2069
	/**
2070
	 * Check if Jetpack's Twitter tags should be used.
2071
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2072
	 *
2073
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2074
	 * @action plugins_loaded
2075
	 * @return null
2076
	 */
2077
	public function check_twitter_tags() {
2078
2079
		$active_plugins = self::get_active_plugins();
2080
2081
		if ( ! empty( $active_plugins ) ) {
2082
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2083
				if ( in_array( $plugin, $active_plugins ) ) {
2084
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2085
					break;
2086
				}
2087
			}
2088
		}
2089
2090
		/**
2091
		 * Allow Twitter Card Meta tags to be disabled.
2092
		 *
2093
		 * @since 2.6.0
2094
		 *
2095
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2096
		 */
2097
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2098
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2099
		}
2100
	}
2101
2102
	/**
2103
	 * Allows plugins to submit security reports.
2104
 	 *
2105
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2106
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2107
	 * @param array   $args         See definitions above
2108
	 */
2109
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2110
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2111
	}
2112
2113
/* Jetpack Options API */
2114
2115
	public static function get_option_names( $type = 'compact' ) {
2116
		return Jetpack_Options::get_option_names( $type );
2117
	}
2118
2119
	/**
2120
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2121
 	 *
2122
	 * @param string $name    Option name
2123
	 * @param mixed  $default (optional)
2124
	 */
2125
	public static function get_option( $name, $default = false ) {
2126
		return Jetpack_Options::get_option( $name, $default );
2127
	}
2128
2129
	/**
2130
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2131
 	 *
2132
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2133
	 * @param string $name  Option name
2134
	 * @param mixed  $value Option value
2135
	 */
2136
	public static function update_option( $name, $value ) {
2137
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2138
		return Jetpack_Options::update_option( $name, $value );
2139
	}
2140
2141
	/**
2142
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2143
 	 *
2144
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2145
	 * @param array $array array( option name => option value, ... )
2146
	 */
2147
	public static function update_options( $array ) {
2148
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2149
		return Jetpack_Options::update_options( $array );
2150
	}
2151
2152
	/**
2153
	 * Deletes the given option.  May be passed multiple option names as an array.
2154
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2155
	 *
2156
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2157
	 * @param string|array $names
2158
	 */
2159
	public static function delete_option( $names ) {
2160
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2161
		return Jetpack_Options::delete_option( $names );
2162
	}
2163
2164
	/**
2165
	 * Enters a user token into the user_tokens option
2166
	 *
2167
	 * @param int $user_id
2168
	 * @param string $token
2169
	 * return bool
2170
	 */
2171
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2172
		// not designed for concurrent updates
2173
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2174
		if ( ! is_array( $user_tokens ) )
2175
			$user_tokens = array();
2176
		$user_tokens[$user_id] = $token;
2177
		if ( $is_master_user ) {
2178
			$master_user = $user_id;
2179
			$options     = compact( 'user_tokens', 'master_user' );
2180
		} else {
2181
			$options = compact( 'user_tokens' );
2182
		}
2183
		return Jetpack_Options::update_options( $options );
2184
	}
2185
2186
	/**
2187
	 * Returns an array of all PHP files in the specified absolute path.
2188
	 * Equivalent to glob( "$absolute_path/*.php" ).
2189
	 *
2190
	 * @param string $absolute_path The absolute path of the directory to search.
2191
	 * @return array Array of absolute paths to the PHP files.
2192
	 */
2193
	public static function glob_php( $absolute_path ) {
2194
		if ( function_exists( 'glob' ) ) {
2195
			return glob( "$absolute_path/*.php" );
2196
		}
2197
2198
		$absolute_path = untrailingslashit( $absolute_path );
2199
		$files = array();
2200
		if ( ! $dir = @opendir( $absolute_path ) ) {
2201
			return $files;
2202
		}
2203
2204
		while ( false !== $file = readdir( $dir ) ) {
2205
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2206
				continue;
2207
			}
2208
2209
			$file = "$absolute_path/$file";
2210
2211
			if ( ! is_file( $file ) ) {
2212
				continue;
2213
			}
2214
2215
			$files[] = $file;
2216
		}
2217
2218
		closedir( $dir );
2219
2220
		return $files;
2221
	}
2222
2223
	public static function activate_new_modules( $redirect = false ) {
2224
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2225
			return;
2226
		}
2227
2228
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2229 View Code Duplication
		if ( ! $jetpack_old_version ) {
2230
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2231
			/** This action is documented in class.jetpack.php */
2232
			do_action( 'updating_jetpack_version', $version, false );
2233
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2234
		}
2235
2236
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2237
2238
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2239
			return;
2240
		}
2241
2242
		$active_modules     = Jetpack::get_active_modules();
2243
		$reactivate_modules = array();
2244
		foreach ( $active_modules as $active_module ) {
2245
			$module = Jetpack::get_module( $active_module );
2246
			if ( ! isset( $module['changed'] ) ) {
2247
				continue;
2248
			}
2249
2250
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2251
				continue;
2252
			}
2253
2254
			$reactivate_modules[] = $active_module;
2255
			Jetpack::deactivate_module( $active_module );
2256
		}
2257
2258
		$new_version = JETPACK__VERSION . ':' . time();
2259
		/** This action is documented in class.jetpack.php */
2260
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2261
		Jetpack_Options::update_options(
2262
			array(
2263
				'version'     => $new_version,
2264
				'old_version' => $jetpack_old_version,
2265
			)
2266
		);
2267
2268
		Jetpack::state( 'message', 'modules_activated' );
2269
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, 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...
2270
2271
		if ( $redirect ) {
2272
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2273
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2274
				$page = $_GET['page'];
2275
			}
2276
2277
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2278
			exit;
2279
		}
2280
	}
2281
2282
	/**
2283
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2284
	 * Make sure to tuck away module "library" files in a sub-directory.
2285
	 */
2286
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2287
		static $modules = null;
2288
2289
		if ( ! isset( $modules ) ) {
2290
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2291
			// Use the cache if we're on the front-end and it's available...
2292
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2293
				$modules = $available_modules_option[ JETPACK__VERSION ];
2294
			} else {
2295
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2296
2297
				$modules = array();
2298
2299
				foreach ( $files as $file ) {
2300
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2301
						continue;
2302
					}
2303
2304
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2305
				}
2306
2307
				Jetpack_Options::update_option( 'available_modules', array(
2308
					JETPACK__VERSION => $modules,
2309
				) );
2310
			}
2311
		}
2312
2313
		/**
2314
		 * Filters the array of modules available to be activated.
2315
		 *
2316
		 * @since 2.4.0
2317
		 *
2318
		 * @param array $modules Array of available modules.
2319
		 * @param string $min_version Minimum version number required to use modules.
2320
		 * @param string $max_version Maximum version number required to use modules.
2321
		 */
2322
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2323
2324
		if ( ! $min_version && ! $max_version ) {
2325
			return array_keys( $mods );
2326
		}
2327
2328
		$r = array();
2329
		foreach ( $mods as $slug => $introduced ) {
2330
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2331
				continue;
2332
			}
2333
2334
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2335
				continue;
2336
			}
2337
2338
			$r[] = $slug;
2339
		}
2340
2341
		return $r;
2342
	}
2343
2344
	/**
2345
	 * Default modules loaded on activation.
2346
	 */
2347
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2348
		$return = array();
2349
2350
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2351
			$module_data = Jetpack::get_module( $module );
2352
2353
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2354
				case 'yes' :
2355
					$return[] = $module;
2356
					break;
2357
				case 'public' :
2358
					if ( Jetpack_Options::get_option( 'public' ) ) {
2359
						$return[] = $module;
2360
					}
2361
					break;
2362
				case 'no' :
2363
				default :
2364
					break;
2365
			}
2366
		}
2367
		/**
2368
		 * Filters the array of default modules.
2369
		 *
2370
		 * @since 2.5.0
2371
		 *
2372
		 * @param array $return Array of default modules.
2373
		 * @param string $min_version Minimum version number required to use modules.
2374
		 * @param string $max_version Maximum version number required to use modules.
2375
		 */
2376
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2377
	}
2378
2379
	/**
2380
	 * Checks activated modules during auto-activation to determine
2381
	 * if any of those modules are being deprecated.  If so, close
2382
	 * them out, and add any replacement modules.
2383
	 *
2384
	 * Runs at priority 99 by default.
2385
	 *
2386
	 * This is run late, so that it can still activate a module if
2387
	 * the new module is a replacement for another that the user
2388
	 * currently has active, even if something at the normal priority
2389
	 * would kibosh everything.
2390
	 *
2391
	 * @since 2.6
2392
	 * @uses jetpack_get_default_modules filter
2393
	 * @param array $modules
2394
	 * @return array
2395
	 */
2396
	function handle_deprecated_modules( $modules ) {
2397
		$deprecated_modules = array(
2398
			'debug'            => null,  // Closed out and moved to the debugger library.
2399
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2400
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2401
		);
2402
2403
		// Don't activate SSO if they never completed activating WPCC.
2404
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2405
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2406
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2407
				$deprecated_modules['wpcc'] = null;
2408
			}
2409
		}
2410
2411
		foreach ( $deprecated_modules as $module => $replacement ) {
2412
			if ( Jetpack::is_module_active( $module ) ) {
2413
				self::deactivate_module( $module );
2414
				if ( $replacement ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $replacement of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2415
					$modules[] = $replacement;
2416
				}
2417
			}
2418
		}
2419
2420
		return array_unique( $modules );
2421
	}
2422
2423
	/**
2424
	 * Checks activated plugins during auto-activation to determine
2425
	 * if any of those plugins are in the list with a corresponding module
2426
	 * that is not compatible with the plugin. The module will not be allowed
2427
	 * to auto-activate.
2428
	 *
2429
	 * @since 2.6
2430
	 * @uses jetpack_get_default_modules filter
2431
	 * @param array $modules
2432
	 * @return array
2433
	 */
2434
	function filter_default_modules( $modules ) {
2435
2436
		$active_plugins = self::get_active_plugins();
2437
2438
		if ( ! empty( $active_plugins ) ) {
2439
2440
			// For each module we'd like to auto-activate...
2441
			foreach ( $modules as $key => $module ) {
2442
				// If there are potential conflicts for it...
2443
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2444
					// For each potential conflict...
2445
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2446
						// If that conflicting plugin is active...
2447
						if ( in_array( $plugin, $active_plugins ) ) {
2448
							// Remove that item from being auto-activated.
2449
							unset( $modules[ $key ] );
2450
						}
2451
					}
2452
				}
2453
			}
2454
		}
2455
2456
		return $modules;
2457
	}
2458
2459
	/**
2460
	 * Extract a module's slug from its full path.
2461
	 */
2462
	public static function get_module_slug( $file ) {
2463
		return str_replace( '.php', '', basename( $file ) );
2464
	}
2465
2466
	/**
2467
	 * Generate a module's path from its slug.
2468
	 */
2469
	public static function get_module_path( $slug ) {
2470
		/**
2471
		 * Filters the path of a modules.
2472
		 *
2473
		 * @since 7.4.0
2474
		 *
2475
		 * @param array $return The absolute path to a module's root php file
2476
		 * @param string $slug The module slug
2477
		 */
2478
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2479
	}
2480
2481
	/**
2482
	 * Load module data from module file. Headers differ from WordPress
2483
	 * plugin headers to avoid them being identified as standalone
2484
	 * plugins on the WordPress plugins page.
2485
	 */
2486
	public static function get_module( $module ) {
2487
		$headers = array(
2488
			'name'                      => 'Module Name',
2489
			'description'               => 'Module Description',
2490
			'jumpstart_desc'            => 'Jumpstart Description',
2491
			'sort'                      => 'Sort Order',
2492
			'recommendation_order'      => 'Recommendation Order',
2493
			'introduced'                => 'First Introduced',
2494
			'changed'                   => 'Major Changes In',
2495
			'deactivate'                => 'Deactivate',
2496
			'free'                      => 'Free',
2497
			'requires_connection'       => 'Requires Connection',
2498
			'auto_activate'             => 'Auto Activate',
2499
			'module_tags'               => 'Module Tags',
2500
			'feature'                   => 'Feature',
2501
			'additional_search_queries' => 'Additional Search Queries',
2502
			'plan_classes'              => 'Plans',
2503
		);
2504
2505
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2506
2507
		$mod = Jetpack::get_file_data( $file, $headers );
2508
		if ( empty( $mod['name'] ) ) {
2509
			return false;
2510
		}
2511
2512
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2513
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2514
		$mod['deactivate']              = empty( $mod['deactivate'] );
2515
		$mod['free']                    = empty( $mod['free'] );
2516
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2517
2518
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2519
			$mod['auto_activate'] = 'No';
2520
		} else {
2521
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2522
		}
2523
2524
		if ( $mod['module_tags'] ) {
2525
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2526
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2527
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2528
		} else {
2529
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2530
		}
2531
2532 View Code Duplication
		if ( $mod['plan_classes'] ) {
2533
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2534
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2535
		} else {
2536
			$mod['plan_classes'] = array( 'free' );
2537
		}
2538
2539 View Code Duplication
		if ( $mod['feature'] ) {
2540
			$mod['feature'] = explode( ',', $mod['feature'] );
2541
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2542
		} else {
2543
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2544
		}
2545
2546
		/**
2547
		 * Filters the feature array on a module.
2548
		 *
2549
		 * This filter allows you to control where each module is filtered: Recommended,
2550
		 * Jumpstart, and the default "Other" listing.
2551
		 *
2552
		 * @since 3.5.0
2553
		 *
2554
		 * @param array   $mod['feature'] The areas to feature this module:
2555
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2556
		 *     'Recommended' shows on the main Jetpack admin screen.
2557
		 *     'Other' should be the default if no other value is in the array.
2558
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2559
		 * @param array   $mod All the currently assembled module data.
2560
		 */
2561
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2562
2563
		/**
2564
		 * Filter the returned data about a module.
2565
		 *
2566
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2567
		 * so please be careful.
2568
		 *
2569
		 * @since 3.6.0
2570
		 *
2571
		 * @param array   $mod    The details of the requested module.
2572
		 * @param string  $module The slug of the module, e.g. sharedaddy
2573
		 * @param string  $file   The path to the module source file.
2574
		 */
2575
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2576
	}
2577
2578
	/**
2579
	 * Like core's get_file_data implementation, but caches the result.
2580
	 */
2581
	public static function get_file_data( $file, $headers ) {
2582
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2583
		$file_name = basename( $file );
2584
2585
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2586
2587
		$file_data_option = get_transient( $cache_key );
2588
2589
		if ( false === $file_data_option ) {
2590
			$file_data_option = array();
2591
		}
2592
2593
		$key           = md5( $file_name . serialize( $headers ) );
2594
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2595
2596
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2597
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2598
			return $file_data_option[ $key ];
2599
		}
2600
2601
		$data = get_file_data( $file, $headers );
2602
2603
		$file_data_option[ $key ] = $data;
2604
2605
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2606
2607
		return $data;
2608
	}
2609
2610
2611
	/**
2612
	 * Return translated module tag.
2613
	 *
2614
	 * @param string $tag Tag as it appears in each module heading.
2615
	 *
2616
	 * @return mixed
2617
	 */
2618
	public static function translate_module_tag( $tag ) {
2619
		return jetpack_get_module_i18n_tag( $tag );
2620
	}
2621
2622
	/**
2623
	 * Get i18n strings as a JSON-encoded string
2624
	 *
2625
	 * @return string The locale as JSON
2626
	 */
2627
	public static function get_i18n_data_json() {
2628
2629
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2630
		// JSON files with the file they should be included for. This is an md5
2631
		// of '_inc/build/admin.js'.
2632
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2633
2634
		$i18n_json =
2635
				   JETPACK__PLUGIN_DIR
2636
				   . 'languages/json/jetpack-'
2637
				   . get_user_locale()
2638
				   . '-'
2639
				   . $path_md5
2640
				   . '.json';
2641
2642
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2643
			$locale_data = @file_get_contents( $i18n_json );
2644
			if ( $locale_data ) {
2645
				return $locale_data;
2646
			}
2647
		}
2648
2649
		// Return valid empty Jed locale
2650
		return '{ "locale_data": { "messages": { "": {} } } }';
2651
	}
2652
2653
	/**
2654
	 * Add locale data setup to wp-i18n
2655
	 *
2656
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2657
	 *
2658
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2659
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2660
	 *
2661
	 * This method provides a safe way to request the setup multiple times but add the script at
2662
	 * most once.
2663
	 *
2664
	 * @since 6.7.0
2665
	 *
2666
	 * @return void
2667
	 */
2668
	public static function setup_wp_i18n_locale_data() {
2669
		static $script_added = false;
2670
		if ( ! $script_added ) {
2671
			$script_added = true;
2672
			wp_add_inline_script(
2673
				'wp-i18n',
2674
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2675
			);
2676
		}
2677
	}
2678
2679
	/**
2680
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2681
	 *
2682
	 * @since 3.9.2
2683
	 *
2684
	 * @param array $modules
2685
	 *
2686
	 * @return string|void
2687
	 */
2688
	public static function get_translated_modules( $modules ) {
2689
		foreach ( $modules as $index => $module ) {
2690
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2691
			if ( isset( $module['name'] ) ) {
2692
				$modules[ $index ]['name'] = $i18n_module['name'];
2693
			}
2694
			if ( isset( $module['description'] ) ) {
2695
				$modules[ $index ]['description'] = $i18n_module['description'];
2696
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2697
			}
2698
		}
2699
		return $modules;
2700
	}
2701
2702
	/**
2703
	 * Get a list of activated modules as an array of module slugs.
2704
	 */
2705
	public static function get_active_modules() {
2706
		$active = Jetpack_Options::get_option( 'active_modules' );
2707
2708
		if ( ! is_array( $active ) ) {
2709
			$active = array();
2710
		}
2711
2712
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2713
			$active[] = 'vaultpress';
2714
		} else {
2715
			$active = array_diff( $active, array( 'vaultpress' ) );
2716
		}
2717
2718
		//If protect is active on the main site of a multisite, it should be active on all sites.
2719
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2720
			$active[] = 'protect';
2721
		}
2722
2723
		/**
2724
		 * Allow filtering of the active modules.
2725
		 *
2726
		 * Gives theme and plugin developers the power to alter the modules that
2727
		 * are activated on the fly.
2728
		 *
2729
		 * @since 5.8.0
2730
		 *
2731
		 * @param array $active Array of active module slugs.
2732
		 */
2733
		$active = apply_filters( 'jetpack_active_modules', $active );
2734
2735
		return array_unique( $active );
2736
	}
2737
2738
	/**
2739
	 * Check whether or not a Jetpack module is active.
2740
	 *
2741
	 * @param string $module The slug of a Jetpack module.
2742
	 * @return bool
2743
	 *
2744
	 * @static
2745
	 */
2746
	public static function is_module_active( $module ) {
2747
		return in_array( $module, self::get_active_modules() );
2748
	}
2749
2750
	public static function is_module( $module ) {
2751
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2752
	}
2753
2754
	/**
2755
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2756
	 *
2757
	 * @param bool $catch True to start catching, False to stop.
2758
	 *
2759
	 * @static
2760
	 */
2761
	public static function catch_errors( $catch ) {
2762
		static $display_errors, $error_reporting;
2763
2764
		if ( $catch ) {
2765
			$display_errors  = @ini_set( 'display_errors', 1 );
2766
			$error_reporting = @error_reporting( E_ALL );
2767
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2768
		} else {
2769
			@ini_set( 'display_errors', $display_errors );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2770
			@error_reporting( $error_reporting );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2771
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2772
		}
2773
	}
2774
2775
	/**
2776
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2777
	 */
2778
	public static function catch_errors_on_shutdown() {
2779
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2780
	}
2781
2782
	/**
2783
	 * Rewrite any string to make paths easier to read.
2784
	 *
2785
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2786
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2787
	 *
2788
	 * @param $string
2789
	 * @return mixed
2790
	 */
2791
	public static function alias_directories( $string ) {
2792
		// ABSPATH has a trailing slash.
2793
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2794
		// WP_CONTENT_DIR does not have a trailing slash.
2795
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2796
2797
		return $string;
2798
	}
2799
2800
	public static function activate_default_modules(
2801
		$min_version = false,
2802
		$max_version = false,
2803
		$other_modules = array(),
2804
		$redirect = true,
2805
		$send_state_messages = true
2806
	) {
2807
		$jetpack = Jetpack::init();
2808
2809
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2810
		$modules = array_merge( $other_modules, $modules );
2811
2812
		// Look for standalone plugins and disable if active.
2813
2814
		$to_deactivate = array();
2815
		foreach ( $modules as $module ) {
2816
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2817
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2818
			}
2819
		}
2820
2821
		$deactivated = array();
2822
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2823
			list( $probable_file, $probable_title ) = $deactivate_me;
2824
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2825
				$deactivated[] = $module;
2826
			}
2827
		}
2828
2829
		if ( $deactivated && $redirect ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2830
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2831
2832
			$url = add_query_arg(
2833
				array(
2834
					'action'   => 'activate_default_modules',
2835
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2836
				),
2837
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2838
			);
2839
			wp_safe_redirect( $url );
2840
			exit;
2841
		}
2842
2843
		/**
2844
		 * Fires before default modules are activated.
2845
		 *
2846
		 * @since 1.9.0
2847
		 *
2848
		 * @param string $min_version Minimum version number required to use modules.
2849
		 * @param string $max_version Maximum version number required to use modules.
2850
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2851
		 */
2852
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2853
2854
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2855
		if ( $send_state_messages ) {
2856
			Jetpack::restate();
2857
			Jetpack::catch_errors( true );
2858
		}
2859
2860
		$active = Jetpack::get_active_modules();
2861
2862
		foreach ( $modules as $module ) {
2863
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2864
				$active[] = $module;
2865
				self::update_active_modules( $active );
2866
				continue;
2867
			}
2868
2869
			if ( $send_state_messages && in_array( $module, $active ) ) {
2870
				$module_info = Jetpack::get_module( $module );
2871 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2872
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2873
					if ( $active_state = Jetpack::state( $state ) ) {
2874
						$active_state = explode( ',', $active_state );
2875
					} else {
2876
						$active_state = array();
2877
					}
2878
					$active_state[] = $module;
2879
					Jetpack::state( $state, implode( ',', $active_state ) );
2880
				}
2881
				continue;
2882
			}
2883
2884
			$file = Jetpack::get_module_path( $module );
2885
			if ( ! file_exists( $file ) ) {
2886
				continue;
2887
			}
2888
2889
			// we'll override this later if the plugin can be included without fatal error
2890
			if ( $redirect ) {
2891
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2892
			}
2893
2894
			if ( $send_state_messages ) {
2895
				Jetpack::state( 'error', 'module_activation_failed' );
2896
				Jetpack::state( 'module', $module );
2897
			}
2898
2899
			ob_start();
2900
			require_once $file;
2901
2902
			$active[] = $module;
2903
2904 View Code Duplication
			if ( $send_state_messages ) {
2905
2906
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2907
				if ( $active_state = Jetpack::state( $state ) ) {
2908
					$active_state = explode( ',', $active_state );
2909
				} else {
2910
					$active_state = array();
2911
				}
2912
				$active_state[] = $module;
2913
				Jetpack::state( $state, implode( ',', $active_state ) );
2914
			}
2915
2916
			Jetpack::update_active_modules( $active );
2917
2918
			ob_end_clean();
2919
		}
2920
2921
		if ( $send_state_messages ) {
2922
			Jetpack::state( 'error', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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...
2923
			Jetpack::state( 'module', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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...
2924
		}
2925
2926
		Jetpack::catch_errors( false );
2927
		/**
2928
		 * Fires when default modules are activated.
2929
		 *
2930
		 * @since 1.9.0
2931
		 *
2932
		 * @param string $min_version Minimum version number required to use modules.
2933
		 * @param string $max_version Maximum version number required to use modules.
2934
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2935
		 */
2936
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2937
	}
2938
2939
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2940
		/**
2941
		 * Fires before a module is activated.
2942
		 *
2943
		 * @since 2.6.0
2944
		 *
2945
		 * @param string $module Module slug.
2946
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2947
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2948
		 */
2949
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2950
2951
		$jetpack = Jetpack::init();
2952
2953
		if ( ! strlen( $module ) )
2954
			return false;
2955
2956
		if ( ! Jetpack::is_module( $module ) )
2957
			return false;
2958
2959
		// If it's already active, then don't do it again
2960
		$active = Jetpack::get_active_modules();
2961
		foreach ( $active as $act ) {
2962
			if ( $act == $module )
2963
				return true;
2964
		}
2965
2966
		$module_data = Jetpack::get_module( $module );
2967
2968
		if ( ! Jetpack::is_active() ) {
2969
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2970
				return false;
2971
2972
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2973
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2974
				return false;
2975
		}
2976
2977
		// Check and see if the old plugin is active
2978
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2979
			// Deactivate the old plugin
2980
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2981
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2982
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2983
				Jetpack::state( 'deactivated_plugins', $module );
2984
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2985
				exit;
2986
			}
2987
		}
2988
2989
		// Protect won't work with mis-configured IPs
2990
		if ( 'protect' === $module ) {
2991
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2992
			if ( ! jetpack_protect_get_ip() ) {
2993
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2994
				return false;
2995
			}
2996
		}
2997
2998
		if ( ! Jetpack_Plan::supports( $module ) ) {
2999
			return false;
3000
		}
3001
3002
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3003
		Jetpack::state( 'module', $module );
3004
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3005
3006
		Jetpack::catch_errors( true );
3007
		ob_start();
3008
		require Jetpack::get_module_path( $module );
3009
		/** This action is documented in class.jetpack.php */
3010
		do_action( 'jetpack_activate_module', $module );
3011
		$active[] = $module;
3012
		Jetpack::update_active_modules( $active );
3013
3014
		Jetpack::state( 'error', false ); // the override
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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...
3015
		ob_end_clean();
3016
		Jetpack::catch_errors( false );
3017
3018
		if ( $redirect ) {
3019
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3020
		}
3021
		if ( $exit ) {
3022
			exit;
3023
		}
3024
		return true;
3025
	}
3026
3027
	function activate_module_actions( $module ) {
3028
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3029
	}
3030
3031
	public static function deactivate_module( $module ) {
3032
		/**
3033
		 * Fires when a module is deactivated.
3034
		 *
3035
		 * @since 1.9.0
3036
		 *
3037
		 * @param string $module Module slug.
3038
		 */
3039
		do_action( 'jetpack_pre_deactivate_module', $module );
3040
3041
		$jetpack = Jetpack::init();
0 ignored issues
show
Unused Code introduced by
$jetpack is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3042
3043
		$active = Jetpack::get_active_modules();
3044
		$new    = array_filter( array_diff( $active, (array) $module ) );
3045
3046
		return self::update_active_modules( $new );
3047
	}
3048
3049
	public static function enable_module_configurable( $module ) {
3050
		$module = Jetpack::get_module_slug( $module );
3051
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3052
	}
3053
3054
	/**
3055
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3056
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3057
	 *
3058
	 * @param string $module Module slug
3059
	 * @return string $url module configuration URL
3060
	 */
3061
	public static function module_configuration_url( $module ) {
3062
		$module = Jetpack::get_module_slug( $module );
3063
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3064
		/**
3065
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3066
		 *
3067
		 * @since 6.9.0
3068
		 *
3069
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3070
		 */
3071
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3072
3073
		return $url;
3074
	}
3075
3076
/* Installation */
3077
	public static function bail_on_activation( $message, $deactivate = true ) {
3078
?>
3079
<!doctype html>
3080
<html>
3081
<head>
3082
<meta charset="<?php bloginfo( 'charset' ); ?>">
3083
<style>
3084
* {
3085
	text-align: center;
3086
	margin: 0;
3087
	padding: 0;
3088
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3089
}
3090
p {
3091
	margin-top: 1em;
3092
	font-size: 18px;
3093
}
3094
</style>
3095
<body>
3096
<p><?php echo esc_html( $message ); ?></p>
3097
</body>
3098
</html>
3099
<?php
3100
		if ( $deactivate ) {
3101
			$plugins = get_option( 'active_plugins' );
3102
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3103
			$update  = false;
3104
			foreach ( $plugins as $i => $plugin ) {
3105
				if ( $plugin === $jetpack ) {
3106
					$plugins[$i] = false;
3107
					$update = true;
3108
				}
3109
			}
3110
3111
			if ( $update ) {
3112
				update_option( 'active_plugins', array_filter( $plugins ) );
3113
			}
3114
		}
3115
		exit;
3116
	}
3117
3118
	/**
3119
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3120
	 * @static
3121
	 */
3122
	public static function plugin_activation( $network_wide ) {
3123
		Jetpack_Options::update_option( 'activated', 1 );
3124
3125
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3126
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3127
		}
3128
3129
		if ( $network_wide )
3130
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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...
3131
3132
		// For firing one-off events (notices) immediately after activation
3133
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3134
3135
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3136
3137
		Jetpack::plugin_initialize();
3138
	}
3139
3140
	public static function get_activation_source( $referer_url ) {
3141
3142
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3143
			return array( 'wp-cli', null );
3144
		}
3145
3146
		$referer = parse_url( $referer_url );
3147
3148
		$source_type = 'unknown';
3149
		$source_query = null;
3150
3151
		if ( ! is_array( $referer ) ) {
3152
			return array( $source_type, $source_query );
3153
		}
3154
3155
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3156
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3157
3158
		if ( isset( $referer['query'] ) ) {
3159
			parse_str( $referer['query'], $query_parts );
3160
		} else {
3161
			$query_parts = array();
3162
		}
3163
3164
		if ( $plugins_path === $referer['path'] ) {
3165
			$source_type = 'list';
3166
		} elseif ( $plugins_install_path === $referer['path'] ) {
3167
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3168
			switch( $tab ) {
3169
				case 'popular':
3170
					$source_type = 'popular';
3171
					break;
3172
				case 'recommended':
3173
					$source_type = 'recommended';
3174
					break;
3175
				case 'favorites':
3176
					$source_type = 'favorites';
3177
					break;
3178
				case 'search':
3179
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3180
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3181
					break;
3182
				default:
3183
					$source_type = 'featured';
3184
			}
3185
		}
3186
3187
		return array( $source_type, $source_query );
3188
	}
3189
3190
	/**
3191
	 * Runs before bumping version numbers up to a new version
3192
	 * @param  string $version    Version:timestamp
3193
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3194
	 * @return null              [description]
3195
	 */
3196
	public static function do_version_bump( $version, $old_version ) {
3197
		if ( ! $old_version ) { // For new sites
3198
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3199
		}
3200
	}
3201
3202
	/**
3203
	 * Sets the internal version number and activation state.
3204
	 * @static
3205
	 */
3206
	public static function plugin_initialize() {
3207
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3208
			Jetpack_Options::update_option( 'activated', 2 );
3209
		}
3210
3211 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3212
			$version = $old_version = JETPACK__VERSION . ':' . time();
3213
			/** This action is documented in class.jetpack.php */
3214
			do_action( 'updating_jetpack_version', $version, false );
3215
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3216
		}
3217
3218
		Jetpack::load_modules();
3219
3220
		Jetpack_Options::delete_option( 'do_activate' );
3221
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3222
	}
3223
3224
	/**
3225
	 * Removes all connection options
3226
	 * @static
3227
	 */
3228
	public static function plugin_deactivation( ) {
3229
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3230
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3231
			Jetpack_Network::init()->deactivate();
3232
		} else {
3233
			Jetpack::disconnect( false );
3234
			//Jetpack_Heartbeat::init()->deactivate();
3235
		}
3236
	}
3237
3238
	/**
3239
	 * Disconnects from the Jetpack servers.
3240
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3241
	 * @static
3242
	 */
3243
	public static function disconnect( $update_activated_state = true ) {
3244
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3245
		Jetpack::clean_nonces( true );
3246
3247
		// If the site is in an IDC because sync is not allowed,
3248
		// let's make sure to not disconnect the production site.
3249
		if ( ! self::validate_sync_error_idc_option() ) {
3250
			$tracking = new Tracking();
3251
			$tracking->record_user_event( 'disconnect_site', array() );
3252
			Jetpack::load_xml_rpc_client();
3253
			$xml = new Jetpack_IXR_Client();
3254
			$xml->query( 'jetpack.deregister' );
3255
		}
3256
3257
		Jetpack_Options::delete_option(
3258
			array(
3259
				'blog_token',
3260
				'user_token',
3261
				'user_tokens',
3262
				'master_user',
3263
				'time_diff',
3264
				'fallback_no_verify_ssl_certs',
3265
			)
3266
		);
3267
3268
		Jetpack_IDC::clear_all_idc_options();
3269
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3270
3271
		if ( $update_activated_state ) {
3272
			Jetpack_Options::update_option( 'activated', 4 );
3273
		}
3274
3275
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3276
			// Check then record unique disconnection if site has never been disconnected previously
3277
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3278
				$jetpack_unique_connection['disconnected'] = 1;
3279
			} else {
3280
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3281
					//track unique disconnect
3282
					$jetpack = Jetpack::init();
3283
3284
					$jetpack->stat( 'connections', 'unique-disconnect' );
3285
					$jetpack->do_stats( 'server_side' );
3286
				}
3287
				// increment number of times disconnected
3288
				$jetpack_unique_connection['disconnected'] += 1;
3289
			}
3290
3291
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3292
		}
3293
3294
		// Delete cached connected user data
3295
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3296
		delete_transient( $transient_key );
3297
3298
		// Delete all the sync related data. Since it could be taking up space.
3299
		Jetpack_Sync_Sender::get_instance()->uninstall();
3300
3301
		// Disable the Heartbeat cron
3302
		Jetpack_Heartbeat::init()->deactivate();
3303
	}
3304
3305
	/**
3306
	 * Unlinks the current user from the linked WordPress.com user
3307
	 */
3308
	public static function unlink_user( $user_id = null ) {
3309
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3310
			return false;
3311
3312
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3313
3314
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3315
			return false;
3316
3317
		if ( ! isset( $tokens[ $user_id ] ) )
3318
			return false;
3319
3320
		Jetpack::load_xml_rpc_client();
3321
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3322
		$xml->query( 'jetpack.unlink_user', $user_id );
3323
3324
		unset( $tokens[ $user_id ] );
3325
3326
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3327
3328
		/**
3329
		 * Fires after the current user has been unlinked from WordPress.com.
3330
		 *
3331
		 * @since 4.1.0
3332
		 *
3333
		 * @param int $user_id The current user's ID.
3334
		 */
3335
		do_action( 'jetpack_unlinked_user', $user_id );
3336
3337
		return true;
3338
	}
3339
3340
	/**
3341
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3342
	 */
3343
	public static function try_registration() {
3344
		// The user has agreed to the TOS at some point by now.
3345
		Jetpack_Options::update_option( 'tos_agreed', true );
3346
3347
		// Let's get some testing in beta versions and such.
3348
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3349
			// Before attempting to connect, let's make sure that the domains are viable.
3350
			$domains_to_check = array_unique( array(
3351
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3352
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3353
			) );
3354
			foreach ( $domains_to_check as $domain ) {
3355
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3354 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...
3356
				if ( is_wp_error( $result ) ) {
3357
					return $result;
3358
				}
3359
			}
3360
		}
3361
3362
		$result = Jetpack::register();
3363
3364
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3365
		if ( ! $result || is_wp_error( $result ) ) {
3366
			return $result;
3367
		} else {
3368
			return true;
3369
		}
3370
	}
3371
3372
	/**
3373
	 * Tracking an internal event log. Try not to put too much chaff in here.
3374
	 *
3375
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3376
	 */
3377
	public static function log( $code, $data = null ) {
3378
		// only grab the latest 200 entries
3379
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3380
3381
		// Append our event to the log
3382
		$log_entry = array(
3383
			'time'    => time(),
3384
			'user_id' => get_current_user_id(),
3385
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3386
			'code'    => $code,
3387
		);
3388
		// Don't bother storing it unless we've got some.
3389
		if ( ! is_null( $data ) ) {
3390
			$log_entry['data'] = $data;
3391
		}
3392
		$log[] = $log_entry;
3393
3394
		// Try add_option first, to make sure it's not autoloaded.
3395
		// @todo: Add an add_option method to Jetpack_Options
3396
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3397
			Jetpack_Options::update_option( 'log', $log );
3398
		}
3399
3400
		/**
3401
		 * Fires when Jetpack logs an internal event.
3402
		 *
3403
		 * @since 3.0.0
3404
		 *
3405
		 * @param array $log_entry {
3406
		 *	Array of details about the log entry.
3407
		 *
3408
		 *	@param string time Time of the event.
3409
		 *	@param int user_id ID of the user who trigerred the event.
3410
		 *	@param int blog_id Jetpack Blog ID.
3411
		 *	@param string code Unique name for the event.
3412
		 *	@param string data Data about the event.
3413
		 * }
3414
		 */
3415
		do_action( 'jetpack_log_entry', $log_entry );
3416
	}
3417
3418
	/**
3419
	 * Get the internal event log.
3420
	 *
3421
	 * @param $event (string) - only return the specific log events
3422
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3423
	 *
3424
	 * @return array of log events || WP_Error for invalid params
3425
	 */
3426
	public static function get_log( $event = false, $num = false ) {
3427
		if ( $event && ! is_string( $event ) ) {
3428
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3429
		}
3430
3431
		if ( $num && ! is_numeric( $num ) ) {
3432
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3433
		}
3434
3435
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3436
3437
		// If nothing set - act as it did before, otherwise let's start customizing the output
3438
		if ( ! $num && ! $event ) {
3439
			return $entire_log;
3440
		} else {
3441
			$entire_log = array_reverse( $entire_log );
3442
		}
3443
3444
		$custom_log_output = array();
3445
3446
		if ( $event ) {
3447
			foreach ( $entire_log as $log_event ) {
3448
				if ( $event == $log_event[ 'code' ] ) {
3449
					$custom_log_output[] = $log_event;
3450
				}
3451
			}
3452
		} else {
3453
			$custom_log_output = $entire_log;
3454
		}
3455
3456
		if ( $num ) {
3457
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3458
		}
3459
3460
		return $custom_log_output;
3461
	}
3462
3463
	/**
3464
	 * Log modification of important settings.
3465
	 */
3466
	public static function log_settings_change( $option, $old_value, $value ) {
3467
		switch( $option ) {
3468
			case 'jetpack_sync_non_public_post_stati':
3469
				self::log( $option, $value );
3470
				break;
3471
		}
3472
	}
3473
3474
	/**
3475
	 * Return stat data for WPCOM sync
3476
	 */
3477
	public static function get_stat_data( $encode = true, $extended = true ) {
3478
		$data = Jetpack_Heartbeat::generate_stats_array();
3479
3480
		if ( $extended ) {
3481
			$additional_data = self::get_additional_stat_data();
3482
			$data = array_merge( $data, $additional_data );
3483
		}
3484
3485
		if ( $encode ) {
3486
			return json_encode( $data );
3487
		}
3488
3489
		return $data;
3490
	}
3491
3492
	/**
3493
	 * Get additional stat data to sync to WPCOM
3494
	 */
3495
	public static function get_additional_stat_data( $prefix = '' ) {
3496
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
3497
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3498
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3499
		$return["{$prefix}site-count"]     = 0;
3500
3501
		if ( function_exists( 'get_blog_count' ) ) {
3502
			$return["{$prefix}site-count"] = get_blog_count();
3503
		}
3504
		return $return;
3505
	}
3506
3507
	private static function get_site_user_count() {
3508
		global $wpdb;
3509
3510
		if ( function_exists( 'wp_is_large_network' ) ) {
3511
			if ( wp_is_large_network( 'users' ) ) {
3512
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3513
			}
3514
		}
3515 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3516
			// It wasn't there, so regenerate the data and save the transient
3517
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3518
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3519
		}
3520
		return $user_count;
3521
	}
3522
3523
	/* Admin Pages */
3524
3525
	function admin_init() {
3526
		// If the plugin is not connected, display a connect message.
3527
		if (
3528
			// the plugin was auto-activated and needs its candy
3529
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3530
		||
3531
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3532
			! Jetpack_Options::get_option( 'activated' )
3533
		) {
3534
			Jetpack::plugin_initialize();
3535
		}
3536
3537
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3538
			Jetpack_Connection_Banner::init();
3539
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3540
			// Upgrade: 1.1 -> 1.1.1
3541
			// Check and see if host can verify the Jetpack servers' SSL certificate
3542
			$args = array();
3543
			Jetpack_Client::_wp_remote_request(
3544
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3545
				$args,
3546
				true
3547
			);
3548
		}
3549
3550
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3551
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3552
		}
3553
3554
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3555
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3556
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3557
3558
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3559
			// Artificially throw errors in certain whitelisted cases during plugin activation
3560
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3561
		}
3562
3563
		// Add custom column in wp-admin/users.php to show whether user is linked.
3564
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3565
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3566
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3567
	}
3568
3569
	function admin_body_class( $admin_body_class = '' ) {
3570
		$classes = explode( ' ', trim( $admin_body_class ) );
3571
3572
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3573
3574
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3575
		return " $admin_body_class ";
3576
	}
3577
3578
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3579
		return $admin_body_class . ' jetpack-pagestyles ';
3580
	}
3581
3582
	/**
3583
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3584
	 * This function artificially throws errors for such cases (whitelisted).
3585
	 *
3586
	 * @param string $plugin The activated plugin.
3587
	 */
3588
	function throw_error_on_activate_plugin( $plugin ) {
3589
		$active_modules = Jetpack::get_active_modules();
3590
3591
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3592
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3593
			$throw = false;
3594
3595
			// Try and make sure it really was the stats plugin
3596
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3597
				if ( 'stats.php' == basename( $plugin ) ) {
3598
					$throw = true;
3599
				}
3600
			} else {
3601
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3602
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3603
					$throw = true;
3604
				}
3605
			}
3606
3607
			if ( $throw ) {
3608
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3609
			}
3610
		}
3611
	}
3612
3613
	function intercept_plugin_error_scrape_init() {
3614
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3615
	}
3616
3617
	function intercept_plugin_error_scrape( $action, $result ) {
3618
		if ( ! $result ) {
3619
			return;
3620
		}
3621
3622
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3623
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3624
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3625
			}
3626
		}
3627
	}
3628
3629
	function add_remote_request_handlers() {
3630
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3631
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3632
	}
3633
3634
	function remote_request_handlers() {
3635
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3636
3637
		switch ( current_filter() ) {
3638
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3639
			$response = $this->upload_handler();
3640
			break;
3641
3642
		case 'wp_ajax_nopriv_jetpack_update_file' :
3643
			$response = $this->upload_handler( true );
3644
			break;
3645
		default :
3646
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3647
			break;
3648
		}
3649
3650
		if ( ! $response ) {
3651
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3652
		}
3653
3654
		if ( is_wp_error( $response ) ) {
3655
			$status_code       = $response->get_error_data();
3656
			$error             = $response->get_error_code();
3657
			$error_description = $response->get_error_message();
3658
3659
			if ( ! is_int( $status_code ) ) {
3660
				$status_code = 400;
3661
			}
3662
3663
			status_header( $status_code );
3664
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3665
		}
3666
3667
		status_header( 200 );
3668
		if ( true === $response ) {
3669
			exit;
3670
		}
3671
3672
		die( json_encode( (object) $response ) );
3673
	}
3674
3675
	/**
3676
	 * Uploads a file gotten from the global $_FILES.
3677
	 * If `$update_media_item` is true and `post_id` is defined
3678
	 * the attachment file of the media item (gotten through of the post_id)
3679
	 * will be updated instead of add a new one.
3680
	 *
3681
	 * @param  boolean $update_media_item - update media attachment
3682
	 * @return array - An array describing the uploadind files process
3683
	 */
3684
	function upload_handler( $update_media_item = false ) {
3685
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3686
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3687
		}
3688
3689
		$user = wp_authenticate( '', '' );
3690
		if ( ! $user || is_wp_error( $user ) ) {
3691
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3692
		}
3693
3694
		wp_set_current_user( $user->ID );
3695
3696
		if ( ! current_user_can( 'upload_files' ) ) {
3697
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3698
		}
3699
3700
		if ( empty( $_FILES ) ) {
3701
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3702
		}
3703
3704
		foreach ( array_keys( $_FILES ) as $files_key ) {
3705
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3706
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3707
			}
3708
		}
3709
3710
		$media_keys = array_keys( $_FILES['media'] );
3711
3712
		$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...
3713
		if ( ! $token || is_wp_error( $token ) ) {
3714
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3715
		}
3716
3717
		$uploaded_files = array();
3718
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3719
		unset( $GLOBALS['post'] );
3720
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3721
			$file = array();
3722
			foreach ( $media_keys as $media_key ) {
3723
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3724
			}
3725
3726
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3727
3728
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3729
			if ( $hmac_provided !== $hmac_file ) {
3730
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3731
				continue;
3732
			}
3733
3734
			$_FILES['.jetpack.upload.'] = $file;
3735
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3736
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3737
				$post_id = 0;
3738
			}
3739
3740
			if ( $update_media_item ) {
3741
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3742
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3743
				}
3744
3745
				$media_array = $_FILES['media'];
3746
3747
				$file_array['name'] = $media_array['name'][0];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$file_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $file_array = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
3748
				$file_array['type'] = $media_array['type'][0];
3749
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3750
				$file_array['error'] = $media_array['error'][0];
3751
				$file_array['size'] = $media_array['size'][0];
3752
3753
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3754
3755
				if ( is_wp_error( $edited_media_item ) ) {
3756
					return $edited_media_item;
3757
				}
3758
3759
				$response = (object) array(
3760
					'id'   => (string) $post_id,
3761
					'file' => (string) $edited_media_item->post_title,
3762
					'url'  => (string) wp_get_attachment_url( $post_id ),
3763
					'type' => (string) $edited_media_item->post_mime_type,
3764
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3765
				);
3766
3767
				return (array) array( $response );
3768
			}
3769
3770
			$attachment_id = media_handle_upload(
3771
				'.jetpack.upload.',
3772
				$post_id,
3773
				array(),
3774
				array(
3775
					'action' => 'jetpack_upload_file',
3776
				)
3777
			);
3778
3779
			if ( ! $attachment_id ) {
3780
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3781
			} elseif ( is_wp_error( $attachment_id ) ) {
3782
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3783
			} else {
3784
				$attachment = get_post( $attachment_id );
3785
				$uploaded_files[$index] = (object) array(
3786
					'id'   => (string) $attachment_id,
3787
					'file' => $attachment->post_title,
3788
					'url'  => wp_get_attachment_url( $attachment_id ),
3789
					'type' => $attachment->post_mime_type,
3790
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3791
				);
3792
				// Zip files uploads are not supported unless they are done for installation purposed
3793
				// lets delete them in case something goes wrong in this whole process
3794
				if ( 'application/zip' === $attachment->post_mime_type ) {
3795
					// Schedule a cleanup for 2 hours from now in case of failed install.
3796
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3797
				}
3798
			}
3799
		}
3800
		if ( ! is_null( $global_post ) ) {
3801
			$GLOBALS['post'] = $global_post;
3802
		}
3803
3804
		return $uploaded_files;
3805
	}
3806
3807
	/**
3808
	 * Add help to the Jetpack page
3809
	 *
3810
	 * @since Jetpack (1.2.3)
3811
	 * @return false if not the Jetpack page
3812
	 */
3813
	function admin_help() {
3814
		$current_screen = get_current_screen();
3815
3816
		// Overview
3817
		$current_screen->add_help_tab(
3818
			array(
3819
				'id'		=> 'home',
3820
				'title'		=> __( 'Home', 'jetpack' ),
3821
				'content'	=>
3822
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3823
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3824
					'<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>',
3825
			)
3826
		);
3827
3828
		// Screen Content
3829
		if ( current_user_can( 'manage_options' ) ) {
3830
			$current_screen->add_help_tab(
3831
				array(
3832
					'id'		=> 'settings',
3833
					'title'		=> __( 'Settings', 'jetpack' ),
3834
					'content'	=>
3835
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3836
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3837
						'<ol>' .
3838
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3839
							'<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>' .
3840
						'</ol>' .
3841
						'<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>'
3842
				)
3843
			);
3844
		}
3845
3846
		// Help Sidebar
3847
		$current_screen->set_help_sidebar(
3848
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3849
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3850
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3851
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3852
		);
3853
	}
3854
3855
	function admin_menu_css() {
3856
		wp_enqueue_style( 'jetpack-icons' );
3857
	}
3858
3859
	function admin_menu_order() {
3860
		return true;
3861
	}
3862
3863 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3864
		$jp_menu_order = array();
3865
3866
		foreach ( $menu_order as $index => $item ) {
3867
			if ( $item != 'jetpack' ) {
3868
				$jp_menu_order[] = $item;
3869
			}
3870
3871
			if ( $index == 0 ) {
3872
				$jp_menu_order[] = 'jetpack';
3873
			}
3874
		}
3875
3876
		return $jp_menu_order;
3877
	}
3878
3879
	function admin_banner_styles() {
3880
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3881
3882
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3883
			wp_register_style(
3884
				'jetpack-dops-style',
3885
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3886
				array(),
3887
				JETPACK__VERSION
3888
			);
3889
		}
3890
3891
		wp_enqueue_style(
3892
			'jetpack',
3893
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3894
			array( 'jetpack-dops-style' ),
3895
			 JETPACK__VERSION . '-20121016'
3896
		);
3897
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3898
		wp_style_add_data( 'jetpack', 'suffix', $min );
3899
	}
3900
3901
	function plugin_action_links( $actions ) {
3902
3903
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3904
3905
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3906
			return array_merge(
3907
				$jetpack_home,
3908
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3909
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3910
				$actions
3911
				);
3912
			}
3913
3914
		return array_merge( $jetpack_home, $actions );
3915
	}
3916
3917
	/*
3918
	 * Registration flow:
3919
	 * 1 - ::admin_page_load() action=register
3920
	 * 2 - ::try_registration()
3921
	 * 3 - ::register()
3922
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3923
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3924
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3925
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3926
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3927
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3928
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3929
	 *       jetpack_id, jetpack_secret, jetpack_public
3930
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3931
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3932
	 * 5 - user logs in with WP.com account
3933
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3934
	 *		- Jetpack_Client_Server::authorize()
3935
	 *		- Jetpack_Client_Server::get_token()
3936
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3937
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3938
	 *			- which responds with access_token, token_type, scope
3939
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3940
	 *		- Jetpack::activate_default_modules()
3941
	 *     		- Deactivates deprecated plugins
3942
	 *     		- Activates all default modules
3943
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3944
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3945
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3946
	 *     Done!
3947
	 */
3948
3949
	/**
3950
	 * Handles the page load events for the Jetpack admin page
3951
	 */
3952
	function admin_page_load() {
3953
		$error = false;
3954
3955
		// Make sure we have the right body class to hook stylings for subpages off of.
3956
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3957
3958
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3959
			// Should only be used in intermediate redirects to preserve state across redirects
3960
			Jetpack::restate();
3961
		}
3962
3963
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3964
			// @todo: Add validation against a known whitelist
3965
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3966
			// User clicked in the iframe to link their accounts
3967
			if ( ! Jetpack::is_user_connected() ) {
3968
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3969
3970
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3971
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3972
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3973
3974
				if ( isset( $_GET['notes_iframe'] ) )
3975
					$connect_url .= '&notes_iframe';
3976
				wp_redirect( $connect_url );
3977
				exit;
3978
			} else {
3979
				if ( ! isset( $_GET['calypso_env'] ) ) {
3980
					Jetpack::state( 'message', 'already_authorized' );
3981
					wp_safe_redirect( Jetpack::admin_url() );
3982
					exit;
3983
				} else {
3984
					$connect_url = $this->build_connect_url( true, false, $from );
3985
					$connect_url .= '&already_authorized=true';
3986
					wp_redirect( $connect_url );
3987
					exit;
3988
				}
3989
			}
3990
		}
3991
3992
3993
		if ( isset( $_GET['action'] ) ) {
3994
			switch ( $_GET['action'] ) {
3995
			case 'authorize':
3996
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3997
					Jetpack::state( 'message', 'already_authorized' );
3998
					wp_safe_redirect( Jetpack::admin_url() );
3999
					exit;
4000
				}
4001
				Jetpack::log( 'authorize' );
4002
				$client_server = new Jetpack_Client_Server;
4003
				$client_server->client_authorize();
4004
				exit;
4005
			case 'register' :
4006
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4007
					$error = 'cheatin';
4008
					break;
4009
				}
4010
				check_admin_referer( 'jetpack-register' );
4011
				Jetpack::log( 'register' );
4012
				Jetpack::maybe_set_version_option();
4013
				$registered = Jetpack::try_registration();
4014
				if ( is_wp_error( $registered ) ) {
4015
					$error = $registered->get_error_code();
4016
					Jetpack::state( 'error', $error );
4017
					Jetpack::state( 'error', $registered->get_error_message() );
4018
4019
					/**
4020
					 * Jetpack registration Error.
4021
					 *
4022
					 * @since 7.5.0
4023
					 *
4024
					 * @param string|int $error The error code.
4025
					 * @param \WP_Error $registered The error object.
4026
					 */
4027
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4028
					break;
4029
				}
4030
4031
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4032
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4033
4034
				/**
4035
				 * Jetpack registration Success.
4036
				 *
4037
				 * @since 7.5.0
4038
				 *
4039
				 * @param string $from 'from' GET parameter;
4040
				 */
4041
				do_action( 'jetpack_connection_register_success', $from );
4042
4043
				$url = $this->build_connect_url( true, $redirect, $from );
4044
4045
				if ( ! empty( $_GET['onboarding'] ) ) {
4046
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4047
				}
4048
4049
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4050
					$url = add_query_arg( 'auth_approved', 'true', $url );
4051
				}
4052
4053
				wp_redirect( $url );
4054
				exit;
4055
			case 'activate' :
4056
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4057
					$error = 'cheatin';
4058
					break;
4059
				}
4060
4061
				$module = stripslashes( $_GET['module'] );
4062
				check_admin_referer( "jetpack_activate-$module" );
4063
				Jetpack::log( 'activate', $module );
4064
				if ( ! Jetpack::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \Jetpack::activate_module($module) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
4065
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4066
				}
4067
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4068
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4069
				exit;
4070
			case 'activate_default_modules' :
4071
				check_admin_referer( 'activate_default_modules' );
4072
				Jetpack::log( 'activate_default_modules' );
4073
				Jetpack::restate();
4074
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4075
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4076
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4077
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4078
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4079
				exit;
4080
			case 'disconnect' :
4081
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4082
					$error = 'cheatin';
4083
					break;
4084
				}
4085
4086
				check_admin_referer( 'jetpack-disconnect' );
4087
				Jetpack::log( 'disconnect' );
4088
				Jetpack::disconnect();
4089
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4090
				exit;
4091
			case 'reconnect' :
4092
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4093
					$error = 'cheatin';
4094
					break;
4095
				}
4096
4097
				check_admin_referer( 'jetpack-reconnect' );
4098
				Jetpack::log( 'reconnect' );
4099
				$this->disconnect();
4100
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4101
				exit;
4102 View Code Duplication
			case 'deactivate' :
4103
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4104
					$error = 'cheatin';
4105
					break;
4106
				}
4107
4108
				$modules = stripslashes( $_GET['module'] );
4109
				check_admin_referer( "jetpack_deactivate-$modules" );
4110
				foreach ( explode( ',', $modules ) as $module ) {
4111
					Jetpack::log( 'deactivate', $module );
4112
					Jetpack::deactivate_module( $module );
4113
					Jetpack::state( 'message', 'module_deactivated' );
4114
				}
4115
				Jetpack::state( 'module', $modules );
4116
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4117
				exit;
4118
			case 'unlink' :
4119
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4120
				check_admin_referer( 'jetpack-unlink' );
4121
				Jetpack::log( 'unlink' );
4122
				$this->unlink_user();
4123
				Jetpack::state( 'message', 'unlinked' );
4124
				if ( 'sub-unlink' == $redirect ) {
4125
					wp_safe_redirect( admin_url() );
4126
				} else {
4127
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4128
				}
4129
				exit;
4130
			case 'onboard' :
4131
				if ( ! current_user_can( 'manage_options' ) ) {
4132
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4133
				} else {
4134
					Jetpack::create_onboarding_token();
4135
					$url = $this->build_connect_url( true );
4136
4137
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4138
						$url = add_query_arg( 'onboarding', $token, $url );
4139
					}
4140
4141
					$calypso_env = $this->get_calypso_env();
4142
					if ( ! empty( $calypso_env ) ) {
4143
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4144
					}
4145
4146
					wp_redirect( $url );
4147
					exit;
4148
				}
4149
				exit;
4150
			default:
4151
				/**
4152
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4153
				 *
4154
				 * @since 2.6.0
4155
				 *
4156
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4157
				 */
4158
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4159
			}
4160
		}
4161
4162
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4163
			self::activate_new_modules( true );
4164
		}
4165
4166
		$message_code = Jetpack::state( 'message' );
4167
		if ( Jetpack::state( 'optin-manage' ) ) {
4168
			$activated_manage = $message_code;
4169
			$message_code = 'jetpack-manage';
4170
		}
4171
4172
		switch ( $message_code ) {
4173
		case 'jetpack-manage':
4174
			$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>';
4175
			if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4176
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4177
			}
4178
			break;
4179
4180
		}
4181
4182
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4183
4184
		if ( ! empty( $deactivated_plugins ) ) {
4185
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4186
			$deactivated_titles  = array();
4187
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4188
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4189
					continue;
4190
				}
4191
4192
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4193
			}
4194
4195
			if ( $deactivated_titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated_titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
4196
				if ( $this->message ) {
4197
					$this->message .= "<br /><br />\n";
4198
				}
4199
4200
				$this->message .= wp_sprintf(
4201
					_n(
4202
						'Jetpack contains the most recent version of the old %l plugin.',
4203
						'Jetpack contains the most recent versions of the old %l plugins.',
4204
						count( $deactivated_titles ),
4205
						'jetpack'
4206
					),
4207
					$deactivated_titles
4208
				);
4209
4210
				$this->message .= "<br />\n";
4211
4212
				$this->message .= _n(
4213
					'The old version has been deactivated and can be removed from your site.',
4214
					'The old versions have been deactivated and can be removed from your site.',
4215
					count( $deactivated_titles ),
4216
					'jetpack'
4217
				);
4218
			}
4219
		}
4220
4221
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4222
4223
		if ( $this->message || $this->error || $this->privacy_checks ) {
4224
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4225
		}
4226
4227
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4228
	}
4229
4230
	function admin_notices() {
4231
4232
		if ( $this->error ) {
4233
?>
4234
<div id="message" class="jetpack-message jetpack-err">
4235
	<div class="squeezer">
4236
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4237
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4238
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4239
<?php	endif; ?>
4240
	</div>
4241
</div>
4242
<?php
4243
		}
4244
4245
		if ( $this->message ) {
4246
?>
4247
<div id="message" class="jetpack-message">
4248
	<div class="squeezer">
4249
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4250
	</div>
4251
</div>
4252
<?php
4253
		}
4254
4255
		if ( $this->privacy_checks ) :
4256
			$module_names = $module_slugs = array();
4257
4258
			$privacy_checks = explode( ',', $this->privacy_checks );
4259
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4260
			foreach ( $privacy_checks as $module_slug ) {
4261
				$module = Jetpack::get_module( $module_slug );
4262
				if ( ! $module ) {
4263
					continue;
4264
				}
4265
4266
				$module_slugs[] = $module_slug;
4267
				$module_names[] = "<strong>{$module['name']}</strong>";
4268
			}
4269
4270
			$module_slugs = join( ',', $module_slugs );
4271
?>
4272
<div id="message" class="jetpack-message jetpack-err">
4273
	<div class="squeezer">
4274
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4275
		<p><?php
4276
			echo wp_kses(
4277
				wptexturize(
4278
					wp_sprintf(
4279
						_nx(
4280
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4281
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4282
							count( $privacy_checks ),
4283
							'%l = list of Jetpack module/feature names',
4284
							'jetpack'
4285
						),
4286
						$module_names
4287
					)
4288
				),
4289
				array( 'strong' => true )
4290
			);
4291
4292
			echo "\n<br />\n";
4293
4294
			echo wp_kses(
4295
				sprintf(
4296
					_nx(
4297
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4298
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4299
						count( $privacy_checks ),
4300
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4301
						'jetpack'
4302
					),
4303
					wp_nonce_url(
4304
						Jetpack::admin_url(
4305
							array(
4306
								'page'   => 'jetpack',
4307
								'action' => 'deactivate',
4308
								'module' => urlencode( $module_slugs ),
4309
							)
4310
						),
4311
						"jetpack_deactivate-$module_slugs"
4312
					),
4313
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4314
				),
4315
				array( 'a' => array( 'href' => true, 'title' => true ) )
4316
			);
4317
		?></p>
4318
	</div>
4319
</div>
4320
<?php endif;
4321
	}
4322
4323
	/**
4324
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4325
	 */
4326
	function stat( $group, $detail ) {
4327
		if ( ! isset( $this->stats[ $group ] ) )
4328
			$this->stats[ $group ] = array();
4329
		$this->stats[ $group ][] = $detail;
4330
	}
4331
4332
	/**
4333
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4334
	 */
4335
	function do_stats( $method = '' ) {
4336
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4337
			foreach ( $this->stats as $group => $stats ) {
4338
				if ( is_array( $stats ) && count( $stats ) ) {
4339
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4340
					if ( 'server_side' === $method ) {
4341
						self::do_server_side_stat( $args );
4342
					} else {
4343
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4344
					}
4345
				}
4346
				unset( $this->stats[ $group ] );
4347
			}
4348
		}
4349
	}
4350
4351
	/**
4352
	 * Runs stats code for a one-off, server-side.
4353
	 *
4354
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4355
	 *
4356
	 * @return bool If it worked.
4357
	 */
4358
	static function do_server_side_stat( $args ) {
4359
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4360
		if ( is_wp_error( $response ) )
4361
			return false;
4362
4363
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4364
			return false;
4365
4366
		return true;
4367
	}
4368
4369
	/**
4370
	 * Builds the stats url.
4371
	 *
4372
	 * @param $args array|string The arguments to append to the URL.
4373
	 *
4374
	 * @return string The URL to be pinged.
4375
	 */
4376
	static function build_stats_url( $args ) {
4377
		$defaults = array(
4378
			'v'    => 'wpcom2',
4379
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4380
		);
4381
		$args     = wp_parse_args( $args, $defaults );
4382
		/**
4383
		 * Filter the URL used as the Stats tracking pixel.
4384
		 *
4385
		 * @since 2.3.2
4386
		 *
4387
		 * @param string $url Base URL used as the Stats tracking pixel.
4388
		 */
4389
		$base_url = apply_filters(
4390
			'jetpack_stats_base_url',
4391
			'https://pixel.wp.com/g.gif'
4392
		);
4393
		$url      = add_query_arg( $args, $base_url );
4394
		return $url;
4395
	}
4396
4397
	static function translate_current_user_to_role() {
4398
		foreach ( self::$capability_translations as $role => $cap ) {
4399
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4400
				return $role;
4401
			}
4402
		}
4403
4404
		return false;
4405
	}
4406
4407
	static function translate_user_to_role( $user ) {
4408
		foreach ( self::$capability_translations as $role => $cap ) {
4409
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4410
				return $role;
4411
			}
4412
		}
4413
4414
		return false;
4415
    }
4416
4417
	static function translate_role_to_cap( $role ) {
4418
		if ( ! isset( self::$capability_translations[$role] ) ) {
4419
			return false;
4420
		}
4421
4422
		return self::$capability_translations[$role];
4423
	}
4424
4425
	static function sign_role( $role, $user_id = null ) {
4426
		if ( empty( $user_id ) ) {
4427
			$user_id = (int) get_current_user_id();
4428
		}
4429
4430
		if ( ! $user_id  ) {
4431
			return false;
4432
		}
4433
4434
		$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...
4435
		if ( ! $token || is_wp_error( $token ) ) {
4436
			return false;
4437
		}
4438
4439
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4440
	}
4441
4442
4443
	/**
4444
	 * Builds a URL to the Jetpack connection auth page
4445
	 *
4446
	 * @since 3.9.5
4447
	 *
4448
	 * @param bool $raw If true, URL will not be escaped.
4449
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4450
	 *                              If string, will be a custom redirect.
4451
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4452
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4453
	 *
4454
	 * @return string Connect URL
4455
	 */
4456
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4457
		$site_id = Jetpack_Options::get_option( 'id' );
4458
		$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...
4459
4460
		if ( $register || ! $blog_token || ! $site_id ) {
4461
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4462
4463
			if ( ! empty( $redirect ) ) {
4464
				$url = add_query_arg(
4465
					'redirect',
4466
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4467
					$url
4468
				);
4469
			}
4470
4471
			if( is_network_admin() ) {
4472
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4473
			}
4474
		} else {
4475
4476
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4477
			// because otherwise this logic can get us in to a loop.
4478
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4479
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4480
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4481
4482
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4483
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4484
					'1.1'
4485
				);
4486
4487
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4488
4489
					// Generating a register URL instead to refresh the existing token
4490
					return $this->build_connect_url( $raw, $redirect, $from, true );
4491
				}
4492
			}
4493
4494
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4495
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4496
			}
4497
4498
			$role = self::translate_current_user_to_role();
4499
			$signed_role = self::sign_role( $role );
4500
4501
			$user = wp_get_current_user();
4502
4503
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4504
			$redirect = $redirect
4505
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4506
				: $jetpack_admin_page;
4507
4508
			if( isset( $_REQUEST['is_multisite'] ) ) {
4509
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4510
			}
4511
4512
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4513
4514
			/**
4515
			 * Filter the type of authorization.
4516
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4517
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4518
			 *
4519
			 * @since 4.3.3
4520
			 *
4521
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4522
			 */
4523
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4524
4525
4526
			$tracks = new Tracking();
4527
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4528
4529
			$args = urlencode_deep(
4530
				array(
4531
					'response_type' => 'code',
4532
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4533
					'redirect_uri'  => add_query_arg(
4534
						array(
4535
							'action'   => 'authorize',
4536
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4537
							'redirect' => urlencode( $redirect ),
4538
						),
4539
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4540
					),
4541
					'state'         => $user->ID,
4542
					'scope'         => $signed_role,
4543
					'user_email'    => $user->user_email,
4544
					'user_login'    => $user->user_login,
4545
					'is_active'     => Jetpack::is_active(),
4546
					'jp_version'    => JETPACK__VERSION,
4547
					'auth_type'     => $auth_type,
4548
					'secret'        => $secrets['secret_1'],
4549
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4550
					'blogname'      => get_option( 'blogname' ),
4551
					'site_url'      => site_url(),
4552
					'home_url'      => home_url(),
4553
					'site_icon'     => get_site_icon_url(),
4554
					'site_lang'     => get_locale(),
4555
					'_ui'           => $tracks_identity['_ui'],
4556
					'_ut'           => $tracks_identity['_ut'],
4557
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4558
				)
4559
			);
4560
4561
			self::apply_activation_source_to_args( $args );
4562
4563
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4564
		}
4565
4566
		if ( $from ) {
4567
			$url = add_query_arg( 'from', $from, $url );
4568
		}
4569
4570
		// Ensure that class to get the affiliate code is loaded
4571
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4572
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4573
		}
4574
		// Get affiliate code and add it to the URL
4575
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4576
4577
		$calypso_env = $this->get_calypso_env();
4578
4579
		if ( ! empty( $calypso_env ) ) {
4580
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4581
		}
4582
4583
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4584
	}
4585
4586
	/**
4587
	 * Get our assumed site creation date.
4588
	 * Calculated based on the earlier date of either:
4589
	 * - Earliest admin user registration date.
4590
	 * - Earliest date of post of any post type.
4591
	 *
4592
	 * @since 7.2.0
4593
	 *
4594
	 * @return string Assumed site creation date and time.
4595
	 */
4596
	public static function get_assumed_site_creation_date() {
4597
		$earliest_registered_users = get_users( array(
4598
			'role'    => 'administrator',
4599
			'orderby' => 'user_registered',
4600
			'order'   => 'ASC',
4601
			'fields'  => array( 'user_registered' ),
4602
			'number'  => 1,
4603
		) );
4604
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4605
4606
		$earliest_posts = get_posts( array(
4607
			'posts_per_page' => 1,
4608
			'post_type'      => 'any',
4609
			'post_status'    => 'any',
4610
			'orderby'        => 'date',
4611
			'order'          => 'ASC',
4612
		) );
4613
4614
		// If there are no posts at all, we'll count only on user registration date.
4615
		if ( $earliest_posts ) {
4616
			$earliest_post_date = $earliest_posts[0]->post_date;
4617
		} else {
4618
			$earliest_post_date = PHP_INT_MAX;
4619
		}
4620
4621
		return min( $earliest_registration_date, $earliest_post_date );
4622
	}
4623
4624
	public static function apply_activation_source_to_args( &$args ) {
4625
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4626
4627
		if ( $activation_source_name ) {
4628
			$args['_as'] = urlencode( $activation_source_name );
4629
		}
4630
4631
		if ( $activation_source_keyword ) {
4632
			$args['_ak'] = urlencode( $activation_source_keyword );
4633
		}
4634
	}
4635
4636
	function build_reconnect_url( $raw = false ) {
4637
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4638
		return $raw ? $url : esc_url( $url );
4639
	}
4640
4641
	public static function admin_url( $args = null ) {
4642
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4643
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4644
		return $url;
4645
	}
4646
4647
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4648
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4649
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4650
	}
4651
4652
	function dismiss_jetpack_notice() {
4653
4654
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4655
			return;
4656
		}
4657
4658
		switch( $_GET['jetpack-notice'] ) {
4659
			case 'dismiss':
4660
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4661
4662
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4663
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4664
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4665
				}
4666
				break;
4667
			case 'jetpack-protect-multisite-opt-out':
4668
4669
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4670
					// Don't show the banner again
4671
4672
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4673
					// redirect back to the page that had the notice
4674
					if ( wp_get_referer() ) {
4675
						wp_safe_redirect( wp_get_referer() );
4676
					} else {
4677
						// Take me to Jetpack
4678
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4679
					}
4680
				}
4681
				break;
4682
		}
4683
	}
4684
4685
	public static function sort_modules( $a, $b ) {
4686
		if ( $a['sort'] == $b['sort'] )
4687
			return 0;
4688
4689
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4690
	}
4691
4692
	function ajax_recheck_ssl() {
4693
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4694
		$result = Jetpack::permit_ssl( true );
4695
		wp_send_json( array(
4696
			'enabled' => $result,
4697
			'message' => get_transient( 'jetpack_https_test_message' )
4698
		) );
4699
	}
4700
4701
/* Client API */
4702
4703
	/**
4704
	 * Returns the requested Jetpack API URL
4705
	 *
4706
	 * @return string
4707
	 */
4708
	public static function api_url( $relative_url ) {
4709
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4710
	}
4711
4712
	/**
4713
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4714
	 */
4715
	public static function fix_url_for_bad_hosts( $url ) {
4716
		if ( 0 !== strpos( $url, 'https://' ) ) {
4717
			return $url;
4718
		}
4719
4720
		switch ( JETPACK_CLIENT__HTTPS ) {
4721
			case 'ALWAYS' :
4722
				return $url;
4723
			case 'NEVER' :
4724
				return set_url_scheme( $url, 'http' );
4725
			// default : case 'AUTO' :
4726
		}
4727
4728
		// we now return the unmodified SSL URL by default, as a security precaution
4729
		return $url;
4730
	}
4731
4732
	/**
4733
	 * Create a random secret for validating onboarding payload
4734
	 *
4735
	 * @return string Secret token
4736
	 */
4737
	public static function create_onboarding_token() {
4738
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4739
			$token = wp_generate_password( 32, false );
4740
			Jetpack_Options::update_option( 'onboarding', $token );
4741
		}
4742
4743
		return $token;
4744
	}
4745
4746
	/**
4747
	 * Remove the onboarding token
4748
	 *
4749
	 * @return bool True on success, false on failure
4750
	 */
4751
	public static function invalidate_onboarding_token() {
4752
		return Jetpack_Options::delete_option( 'onboarding' );
4753
	}
4754
4755
	/**
4756
	 * Validate an onboarding token for a specific action
4757
	 *
4758
	 * @return boolean True if token/action pair is accepted, false if not
4759
	 */
4760
	public static function validate_onboarding_token_action( $token, $action ) {
4761
		// Compare tokens, bail if tokens do not match
4762
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4763
			return false;
4764
		}
4765
4766
		// List of valid actions we can take
4767
		$valid_actions = array(
4768
			'/jetpack/v4/settings',
4769
		);
4770
4771
		// Whitelist the action
4772
		if ( ! in_array( $action, $valid_actions ) ) {
4773
			return false;
4774
		}
4775
4776
		return true;
4777
	}
4778
4779
	/**
4780
	 * Checks to see if the URL is using SSL to connect with Jetpack
4781
	 *
4782
	 * @since 2.3.3
4783
	 * @return boolean
4784
	 */
4785
	public static function permit_ssl( $force_recheck = false ) {
4786
		// Do some fancy tests to see if ssl is being supported
4787
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4788
			$message = '';
4789
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4790
				$ssl = 0;
4791
			} else {
4792
				switch ( JETPACK_CLIENT__HTTPS ) {
4793
					case 'NEVER':
4794
						$ssl = 0;
4795
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4796
						break;
4797
					case 'ALWAYS':
4798
					case 'AUTO':
4799
					default:
4800
						$ssl = 1;
4801
						break;
4802
				}
4803
4804
				// If it's not 'NEVER', test to see
4805
				if ( $ssl ) {
4806
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4807
						$ssl = 0;
4808
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4809
					} else {
4810
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4811
						if ( is_wp_error( $response ) ) {
4812
							$ssl = 0;
4813
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4814
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4815
							$ssl = 0;
4816
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4817
						}
4818
					}
4819
				}
4820
			}
4821
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4822
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4823
		}
4824
4825
		return (bool) $ssl;
4826
	}
4827
4828
	/*
4829
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4830
	 */
4831
	public function alert_auto_ssl_fail() {
4832
		if ( ! current_user_can( 'manage_options' ) )
4833
			return;
4834
4835
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4836
		?>
4837
4838
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4839
			<div class="jp-banner__content">
4840
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4841
				<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>
4842
				<p>
4843
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4844
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4845
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4846
				</p>
4847
				<p>
4848
					<?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' ),
4849
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4850
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4851
				</p>
4852
			</div>
4853
		</div>
4854
		<style>
4855
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4856
		</style>
4857
		<script type="text/javascript">
4858
			jQuery( document ).ready( function( $ ) {
4859
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4860
					var $this = $( this );
4861
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4862
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4863
					e.preventDefault();
4864
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4865
					$.post( ajaxurl, data )
4866
					  .done( function( response ) {
4867
					  	if ( response.enabled ) {
4868
					  		$( '#jetpack-ssl-warning' ).hide();
4869
					  	} else {
4870
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4871
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4872
					  	}
4873
					  }.bind( $this ) );
4874
				} );
4875
			} );
4876
		</script>
4877
4878
		<?php
4879
	}
4880
4881
	/**
4882
	 * Returns the Jetpack XML-RPC API
4883
	 *
4884
	 * @return string
4885
	 */
4886
	public static function xmlrpc_api_url() {
4887
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4888
		return untrailingslashit( $base ) . '/xmlrpc.php';
4889
	}
4890
4891
	public static function connection() {
4892
		return self::init()->connection_manager;
4893
	}
4894
4895
	/**
4896
	 * Creates two secret tokens and the end of life timestamp for them.
4897
	 *
4898
	 * Note these tokens are unique per call, NOT static per site for connecting.
4899
	 *
4900
	 * @since 2.6
4901
	 * @return array
4902
	 */
4903
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4904
		if ( false === $user_id ) {
4905
			$user_id = get_current_user_id();
4906
		}
4907
4908
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4909
	}
4910
4911
	public static function get_secrets( $action, $user_id ) {
4912
		$secrets = self::connection()->get_secrets( $action, $user_id );
4913
4914
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4915
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4916
		}
4917
4918
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4919
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4920
		}
4921
4922
		return $secrets;
4923
	}
4924
4925
	/**
4926
	 * @deprecated 7.5 Use Connection_Manager instead.
4927
	 *
4928
	 * @param $action
4929
	 * @param $user_id
4930
	 */
4931
	public static function delete_secrets( $action, $user_id ) {
4932
		return self::connection()->delete_secrets( $action, $user_id );
4933
	}
4934
4935
	/**
4936
	 * Builds the timeout limit for queries talking with the wpcom servers.
4937
	 *
4938
	 * Based on local php max_execution_time in php.ini
4939
	 *
4940
	 * @since 2.6
4941
	 * @return int
4942
	 * @deprecated
4943
	 **/
4944
	public function get_remote_query_timeout_limit() {
4945
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4946
		return Jetpack::get_max_execution_time();
4947
	}
4948
4949
	/**
4950
	 * Builds the timeout limit for queries talking with the wpcom servers.
4951
	 *
4952
	 * Based on local php max_execution_time in php.ini
4953
	 *
4954
	 * @since 5.4
4955
	 * @return int
4956
	 **/
4957
	public static function get_max_execution_time() {
4958
		$timeout = (int) ini_get( 'max_execution_time' );
4959
4960
		// Ensure exec time set in php.ini
4961
		if ( ! $timeout ) {
4962
			$timeout = 30;
4963
		}
4964
		return $timeout;
4965
	}
4966
4967
	/**
4968
	 * Sets a minimum request timeout, and returns the current timeout
4969
	 *
4970
	 * @since 5.4
4971
	 **/
4972
	public static function set_min_time_limit( $min_timeout ) {
4973
		$timeout = self::get_max_execution_time();
4974
		if ( $timeout < $min_timeout ) {
4975
			$timeout = $min_timeout;
4976
			set_time_limit( $timeout );
4977
		}
4978
		return $timeout;
4979
	}
4980
4981
4982
	/**
4983
	 * Takes the response from the Jetpack register new site endpoint and
4984
	 * verifies it worked properly.
4985
	 *
4986
	 * @since 2.6
4987
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4988
	 **/
4989
	public function validate_remote_register_response( $response ) {
4990
	  if ( is_wp_error( $response ) ) {
4991
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4992
		}
4993
4994
		$code   = wp_remote_retrieve_response_code( $response );
4995
		$entity = wp_remote_retrieve_body( $response );
4996
		if ( $entity )
4997
			$registration_response = json_decode( $entity );
4998
		else
4999
			$registration_response = false;
5000
5001
		$code_type = intval( $code / 100 );
5002
		if ( 5 == $code_type ) {
5003
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5004
		} elseif ( 408 == $code ) {
5005
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5006
		} elseif ( ! empty( $registration_response->error ) ) {
5007
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5008
				$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' );
5009
			} else {
5010
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5011
			}
5012
5013
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5014
		} elseif ( 200 != $code ) {
5015
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5016
		}
5017
5018
		// Jetpack ID error block
5019
		if ( empty( $registration_response->jetpack_id ) ) {
5020
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5021
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5022
			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 );
5023
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5024
			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 );
5025
		}
5026
5027
	    return $registration_response;
5028
	}
5029
	/**
5030
	 * @return bool|WP_Error
5031
	 */
5032
	public static function register() {
5033
		$tracking = new Tracking();
5034
		$tracking->record_user_event( 'jpc_register_begin' );
5035
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5036
		$secrets = Jetpack::generate_secrets( 'register' );
5037
5038 View Code Duplication
		if (
5039
			empty( $secrets['secret_1'] ) ||
5040
			empty( $secrets['secret_2'] ) ||
5041
			empty( $secrets['exp'] )
5042
		) {
5043
			return new Jetpack_Error( 'missing_secrets' );
5044
		}
5045
5046
		// better to try (and fail) to set a higher timeout than this system
5047
		// supports than to have register fail for more users than it should
5048
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5049
5050
		$gmt_offset = get_option( 'gmt_offset' );
5051
		if ( ! $gmt_offset ) {
5052
			$gmt_offset = 0;
5053
		}
5054
5055
		$stats_options = get_option( 'stats_options' );
5056
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5057
5058
		$tracks = new Tracking();
5059
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
5060
5061
		$args = array(
5062
			'method'  => 'POST',
5063
			'body'    => array(
5064
				'siteurl'         => site_url(),
5065
				'home'            => home_url(),
5066
				'gmt_offset'      => $gmt_offset,
5067
				'timezone_string' => (string) get_option( 'timezone_string' ),
5068
				'site_name'       => (string) get_option( 'blogname' ),
5069
				'secret_1'        => $secrets['secret_1'],
5070
				'secret_2'        => $secrets['secret_2'],
5071
				'site_lang'       => get_locale(),
5072
				'timeout'         => $timeout,
5073
				'stats_id'        => $stats_id,
5074
				'state'           => get_current_user_id(),
5075
				'_ui'             => $tracks_identity['_ui'],
5076
				'_ut'             => $tracks_identity['_ut'],
5077
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5078
				'jetpack_version' => JETPACK__VERSION
5079
			),
5080
			'headers' => array(
5081
				'Accept' => 'application/json',
5082
			),
5083
			'timeout' => $timeout,
5084
		);
5085
5086
		self::apply_activation_source_to_args( $args['body'] );
5087
5088
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5089
5090
		// Make sure the response is valid and does not contain any Jetpack errors
5091
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5092
		if ( is_wp_error( $registration_details ) ) {
5093
			return $registration_details;
5094
		} elseif ( ! $registration_details ) {
5095
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5096
		}
5097
5098 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5099
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5100
		}
5101
5102
		if ( isset( $registration_details->jetpack_public ) ) {
5103
			$jetpack_public = (int) $registration_details->jetpack_public;
5104
		} else {
5105
			$jetpack_public = false;
5106
		}
5107
5108
		Jetpack_Options::update_options(
5109
			array(
5110
				'id'         => (int)    $registration_details->jetpack_id,
5111
				'blog_token' => (string) $registration_details->jetpack_secret,
5112
				'public'     => $jetpack_public,
5113
			)
5114
		);
5115
5116
		/**
5117
		 * Fires when a site is registered on WordPress.com.
5118
		 *
5119
		 * @since 3.7.0
5120
		 *
5121
		 * @param int $json->jetpack_id Jetpack Blog ID.
5122
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5123
		 * @param int|bool $jetpack_public Is the site public.
5124
		 */
5125
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5126
5127
		// Initialize Jump Start for the first and only time.
5128
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5129
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5130
5131
			$jetpack = Jetpack::init();
5132
5133
			$jetpack->stat( 'jumpstart', 'unique-views' );
5134
			$jetpack->do_stats( 'server_side' );
5135
		};
5136
5137
		return true;
5138
	}
5139
5140
	/**
5141
	 * If the db version is showing something other that what we've got now, bump it to current.
5142
	 *
5143
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
Documentation introduced by
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
5144
	 */
5145
	public static function maybe_set_version_option() {
5146
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5147
		if ( JETPACK__VERSION != $version ) {
5148
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5149
5150
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5151
				/** This action is documented in class.jetpack.php */
5152
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5153
			}
5154
5155
			return true;
5156
		}
5157
		return false;
5158
	}
5159
5160
/* Client Server API */
5161
5162
	/**
5163
	 * Loads the Jetpack XML-RPC client
5164
	 */
5165
	public static function load_xml_rpc_client() {
5166
		require_once ABSPATH . WPINC . '/class-IXR.php';
5167
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5168
	}
5169
5170
	/**
5171
	 * Resets the saved authentication state in between testing requests.
5172
	 */
5173
	public function reset_saved_auth_state() {
5174
		$this->xmlrpc_verification = null;
5175
		$this->rest_authentication_status = null;
5176
	}
5177
5178
	function verify_xml_rpc_signature() {
5179
		if ( $this->xmlrpc_verification ) {
5180
			return $this->xmlrpc_verification;
5181
		}
5182
5183
		// It's not for us
5184
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5185
			return false;
5186
		}
5187
5188
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
5189
		if (
5190
			empty( $token_key )
5191
		||
5192
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5193
		) {
5194
			return false;
5195
		}
5196
5197
		if ( '0' === $user_id ) {
5198
			$token_type = 'blog';
5199
			$user_id = 0;
5200
		} else {
5201
			$token_type = 'user';
5202
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5203
				return false;
5204
			}
5205
			$user_id = (int) $user_id;
5206
5207
			$user = new WP_User( $user_id );
5208
			if ( ! $user || ! $user->exists() ) {
5209
				return false;
5210
			}
5211
		}
5212
5213
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
0 ignored issues
show
Documentation introduced by
$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...
5214
		if ( ! $token ) {
5215
			return false;
5216
		}
5217
5218
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5219
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5220
			$post_data   = $_POST;
5221
			$file_hashes = array();
5222
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5223
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5224
					continue;
5225
				}
5226
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5227
				$file_hashes[$post_data_key] = $post_data_value;
5228
			}
5229
5230
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5231
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5232
				$post_data[$post_data_key] = $post_data_value;
5233
			}
5234
5235
			ksort( $post_data );
5236
5237
			$body = http_build_query( stripslashes_deep( $post_data ) );
5238
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5239
			$body = file_get_contents( 'php://input' );
5240
		} else {
5241
			$body = null;
5242
		}
5243
5244
		$signature = $jetpack_signature->sign_current_request(
5245
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5246
		);
5247
5248
		if ( ! $signature ) {
5249
			return false;
5250
		} else if ( is_wp_error( $signature ) ) {
5251
			return $signature;
5252
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5253
			return false;
5254
		}
5255
5256
		$timestamp = (int) $_GET['timestamp'];
5257
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5258
5259
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5260
			return false;
5261
		}
5262
5263
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5264
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5265
			if ( ! empty( $_GET['onboarding'] ) ) {
5266
				$jpo = $_GET;
5267
			} else {
5268
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5269
			}
5270
5271
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5272
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5273
5274
			if (
5275
				isset( $jpo_user ) && isset( $jpo_token ) &&
5276
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5277
				isset( $_GET['rest_route'] ) &&
5278
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5279
			) {
5280
				$jpUser = get_user_by( 'email', $jpo_user );
5281
				if ( is_a( $jpUser, 'WP_User' ) ) {
5282
					wp_set_current_user( $jpUser->ID );
5283
					$user_can = is_multisite()
5284
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5285
						: current_user_can( 'manage_options' );
5286
					if ( $user_can ) {
5287
						$token_type = 'user';
5288
						$token->external_user_id = $jpUser->ID;
5289
					}
5290
				}
5291
			}
5292
		}
5293
5294
		$this->xmlrpc_verification = array(
5295
			'type'      => $token_type,
5296
			'token_key' => $token_key,
5297
			'user_id'   => $token->external_user_id,
5298
		);
5299
5300
		return $this->xmlrpc_verification;
5301
	}
5302
5303
	/**
5304
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5305
	 */
5306
	function authenticate_jetpack( $user, $username, $password ) {
5307
		if ( is_a( $user, 'WP_User' ) ) {
5308
			return $user;
5309
		}
5310
5311
		$token_details = $this->verify_xml_rpc_signature();
5312
5313
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5314
			return $user;
5315
		}
5316
5317
		if ( 'user' !== $token_details['type'] ) {
5318
			return $user;
5319
		}
5320
5321
		if ( ! $token_details['user_id'] ) {
5322
			return $user;
5323
		}
5324
5325
		nocache_headers();
5326
5327
		return new WP_User( $token_details['user_id'] );
5328
	}
5329
5330
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5331
	// Uses the existing XMLRPC request signing implementation.
5332
	function wp_rest_authenticate( $user ) {
5333
		if ( ! empty( $user ) ) {
5334
			// Another authentication method is in effect.
5335
			return $user;
5336
		}
5337
5338
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5339
			// Nothing to do for this authentication method.
5340
			return null;
5341
		}
5342
5343
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5344
			// Nothing to do for this authentication method.
5345
			return null;
5346
		}
5347
5348
		// Ensure that we always have the request body available.  At this
5349
		// point, the WP REST API code to determine the request body has not
5350
		// run yet.  That code may try to read from 'php://input' later, but
5351
		// this can only be done once per request in PHP versions prior to 5.6.
5352
		// So we will go ahead and perform this read now if needed, and save
5353
		// the request body where both the Jetpack signature verification code
5354
		// and the WP REST API code can see it.
5355
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5356
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5357
		}
5358
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5359
5360
		// Only support specific request parameters that have been tested and
5361
		// are known to work with signature verification.  A different method
5362
		// can be passed to the WP REST API via the '?_method=' parameter if
5363
		// needed.
5364
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5365
			$this->rest_authentication_status = new WP_Error(
5366
				'rest_invalid_request',
5367
				__( 'This request method is not supported.', 'jetpack' ),
5368
				array( 'status' => 400 )
5369
			);
5370
			return null;
5371
		}
5372
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5373
			$this->rest_authentication_status = new WP_Error(
5374
				'rest_invalid_request',
5375
				__( 'This request method does not support body parameters.', 'jetpack' ),
5376
				array( 'status' => 400 )
5377
			);
5378
			return null;
5379
		}
5380
5381
		$verified = $this->verify_xml_rpc_signature();
5382
5383
		if ( is_wp_error( $verified ) ) {
5384
			$this->rest_authentication_status = $verified;
5385
			return null;
5386
		}
5387
5388
		if (
5389
			$verified &&
5390
			isset( $verified['type'] ) &&
5391
			'user' === $verified['type'] &&
5392
			! empty( $verified['user_id'] )
5393
		) {
5394
			// Authentication successful.
5395
			$this->rest_authentication_status = true;
5396
			return $verified['user_id'];
5397
		}
5398
5399
		// Something else went wrong.  Probably a signature error.
5400
		$this->rest_authentication_status = new WP_Error(
5401
			'rest_invalid_signature',
5402
			__( 'The request is not signed correctly.', 'jetpack' ),
5403
			array( 'status' => 400 )
5404
		);
5405
		return null;
5406
	}
5407
5408
	/**
5409
	 * Report authentication status to the WP REST API.
5410
	 *
5411
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
5412
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5413
	 */
5414
	public function wp_rest_authentication_errors( $value ) {
5415
		if ( $value !== null ) {
5416
			return $value;
5417
		}
5418
		return $this->rest_authentication_status;
5419
	}
5420
5421
	function add_nonce( $timestamp, $nonce ) {
5422
		global $wpdb;
5423
		static $nonces_used_this_request = array();
5424
5425
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5426
			return $nonces_used_this_request["$timestamp:$nonce"];
5427
		}
5428
5429
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5430
		$timestamp = (int) $timestamp;
5431
		$nonce     = esc_sql( $nonce );
5432
5433
		// Raw query so we can avoid races: add_option will also update
5434
		$show_errors = $wpdb->show_errors( false );
5435
5436
		$old_nonce = $wpdb->get_row(
5437
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5438
		);
5439
5440
		if ( is_null( $old_nonce ) ) {
5441
			$return = $wpdb->query(
5442
				$wpdb->prepare(
5443
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5444
					"jetpack_nonce_{$timestamp}_{$nonce}",
5445
					time(),
5446
					'no'
5447
				)
5448
			);
5449
		} else {
5450
			$return = false;
5451
		}
5452
5453
		$wpdb->show_errors( $show_errors );
5454
5455
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5456
5457
		return $return;
5458
	}
5459
5460
	/**
5461
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5462
	 * Capture it here so we can verify the signature later.
5463
	 */
5464
	function xmlrpc_methods( $methods ) {
5465
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5466
		return $methods;
5467
	}
5468
5469
	function public_xmlrpc_methods( $methods ) {
5470
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5471
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5472
		}
5473
		return $methods;
5474
	}
5475
5476
	function jetpack_getOptions( $args ) {
5477
		global $wp_xmlrpc_server;
5478
5479
		$wp_xmlrpc_server->escape( $args );
5480
5481
		$username	= $args[1];
5482
		$password	= $args[2];
5483
5484
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5485
			return $wp_xmlrpc_server->error;
5486
		}
5487
5488
		$options = array();
5489
		$user_data = $this->get_connected_user_data();
5490
		if ( is_array( $user_data ) ) {
5491
			$options['jetpack_user_id'] = array(
5492
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5493
				'readonly'      => true,
5494
				'value'         => $user_data['ID'],
5495
			);
5496
			$options['jetpack_user_login'] = array(
5497
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5498
				'readonly'      => true,
5499
				'value'         => $user_data['login'],
5500
			);
5501
			$options['jetpack_user_email'] = array(
5502
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5503
				'readonly'      => true,
5504
				'value'         => $user_data['email'],
5505
			);
5506
			$options['jetpack_user_site_count'] = array(
5507
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5508
				'readonly'      => true,
5509
				'value'         => $user_data['site_count'],
5510
			);
5511
		}
5512
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5513
		$args = stripslashes_deep( $args );
5514
		return $wp_xmlrpc_server->wp_getOptions( $args );
5515
	}
5516
5517
	function xmlrpc_options( $options ) {
5518
		$jetpack_client_id = false;
5519
		if ( self::is_active() ) {
5520
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5521
		}
5522
		$options['jetpack_version'] = array(
5523
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5524
				'readonly'      => true,
5525
				'value'         => JETPACK__VERSION,
5526
		);
5527
5528
		$options['jetpack_client_id'] = array(
5529
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5530
				'readonly'      => true,
5531
				'value'         => $jetpack_client_id,
5532
		);
5533
		return $options;
5534
	}
5535
5536
	public static function clean_nonces( $all = false ) {
5537
		global $wpdb;
5538
5539
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5540
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5541
5542
		if ( true !== $all ) {
5543
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5544
			$sql_args[] = time() - 3600;
5545
		}
5546
5547
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5548
5549
		$sql = $wpdb->prepare( $sql, $sql_args );
5550
5551
		for ( $i = 0; $i < 1000; $i++ ) {
5552
			if ( ! $wpdb->query( $sql ) ) {
5553
				break;
5554
			}
5555
		}
5556
	}
5557
5558
	/**
5559
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5560
	 * SET: state( $key, $value );
5561
	 * GET: $value = state( $key );
5562
	 *
5563
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
5564
	 * @param string $value
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
5565
	 * @param bool $restate private
5566
	 */
5567
	public static function state( $key = null, $value = null, $restate = false ) {
5568
		static $state = array();
5569
		static $path, $domain;
5570
		if ( ! isset( $path ) ) {
5571
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5572
			$admin_url = Jetpack::admin_url();
5573
			$bits      = wp_parse_url( $admin_url );
5574
5575
			if ( is_array( $bits ) ) {
5576
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5577
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5578
			} else {
5579
				$path = $domain = null;
5580
			}
5581
		}
5582
5583
		// Extract state from cookies and delete cookies
5584
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5585
			$yum = $_COOKIE[ 'jetpackState' ];
5586
			unset( $_COOKIE[ 'jetpackState' ] );
5587
			foreach ( $yum as $k => $v ) {
5588
				if ( strlen( $v ) )
5589
					$state[ $k ] = $v;
5590
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5591
			}
5592
		}
5593
5594
		if ( $restate ) {
5595
			foreach ( $state as $k => $v ) {
5596
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5597
			}
5598
			return;
5599
		}
5600
5601
		// Get a state variable
5602
		if ( isset( $key ) && ! isset( $value ) ) {
5603
			if ( array_key_exists( $key, $state ) )
5604
				return $state[ $key ];
5605
			return null;
5606
		}
5607
5608
		// Set a state variable
5609
		if ( isset ( $key ) && isset( $value ) ) {
5610
			if( is_array( $value ) && isset( $value[0] ) ) {
5611
				$value = $value[0];
5612
			}
5613
			$state[ $key ] = $value;
5614
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5615
		}
5616
	}
5617
5618
	public static function restate() {
5619
		Jetpack::state( null, null, true );
5620
	}
5621
5622
	public static function check_privacy( $file ) {
5623
		static $is_site_publicly_accessible = null;
5624
5625
		if ( is_null( $is_site_publicly_accessible ) ) {
5626
			$is_site_publicly_accessible = false;
5627
5628
			Jetpack::load_xml_rpc_client();
5629
			$rpc = new Jetpack_IXR_Client();
5630
5631
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5632
			if ( $success ) {
5633
				$response = $rpc->getResponse();
5634
				if ( $response ) {
5635
					$is_site_publicly_accessible = true;
5636
				}
5637
			}
5638
5639
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5640
		}
5641
5642
		if ( $is_site_publicly_accessible ) {
5643
			return;
5644
		}
5645
5646
		$module_slug = self::get_module_slug( $file );
5647
5648
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5649
		if ( ! $privacy_checks ) {
5650
			$privacy_checks = $module_slug;
5651
		} else {
5652
			$privacy_checks .= ",$module_slug";
5653
		}
5654
5655
		Jetpack::state( 'privacy_checks', $privacy_checks );
5656
	}
5657
5658
	/**
5659
	 * Helper method for multicall XMLRPC.
5660
	 */
5661
	public static function xmlrpc_async_call() {
5662
		global $blog_id;
5663
		static $clients = array();
5664
5665
		$client_blog_id = is_multisite() ? $blog_id : 0;
5666
5667
		if ( ! isset( $clients[$client_blog_id] ) ) {
5668
			Jetpack::load_xml_rpc_client();
5669
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5670
			if ( function_exists( 'ignore_user_abort' ) ) {
5671
				ignore_user_abort( true );
5672
			}
5673
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5674
		}
5675
5676
		$args = func_get_args();
5677
5678
		if ( ! empty( $args[0] ) ) {
5679
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5680
		} elseif ( is_multisite() ) {
5681
			foreach ( $clients as $client_blog_id => $client ) {
5682
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5683
					continue;
5684
				}
5685
5686
				$switch_success = switch_to_blog( $client_blog_id, true );
5687
				if ( ! $switch_success ) {
5688
					continue;
5689
				}
5690
5691
				flush();
5692
				$client->query();
5693
5694
				restore_current_blog();
5695
			}
5696
		} else {
5697
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5698
				flush();
5699
				$clients[0]->query();
5700
			}
5701
		}
5702
	}
5703
5704
	public static function staticize_subdomain( $url ) {
5705
5706
		// Extract hostname from URL
5707
		$host = parse_url( $url, PHP_URL_HOST );
5708
5709
		// Explode hostname on '.'
5710
		$exploded_host = explode( '.', $host );
5711
5712
		// Retrieve the name and TLD
5713
		if ( count( $exploded_host ) > 1 ) {
5714
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5715
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5716
			// Rebuild domain excluding subdomains
5717
			$domain = $name . '.' . $tld;
5718
		} else {
5719
			$domain = $host;
5720
		}
5721
		// Array of Automattic domains
5722
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5723
5724
		// Return $url if not an Automattic domain
5725
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5726
			return $url;
5727
		}
5728
5729
		if ( is_ssl() ) {
5730
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5731
		}
5732
5733
		srand( crc32( basename( $url ) ) );
5734
		$static_counter = rand( 0, 2 );
5735
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5736
5737
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5738
	}
5739
5740
/* JSON API Authorization */
5741
5742
	/**
5743
	 * Handles the login action for Authorizing the JSON API
5744
	 */
5745
	function login_form_json_api_authorization() {
5746
		$this->verify_json_api_authorization_request();
5747
5748
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5749
5750
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5751
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5752
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5753
	}
5754
5755
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5756
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5757
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5758
			return $url;
5759
		}
5760
5761
		$parsed_url = parse_url( $url );
5762
		$url = strtok( $url, '?' );
5763
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5764
		if ( ! empty( $parsed_url['query'] ) )
5765
			$url .= "&{$parsed_url['query']}";
5766
5767
		return $url;
5768
	}
5769
5770
	// Make sure the POSTed request is handled by the same action
5771
	function preserve_action_in_login_form_for_json_api_authorization() {
5772
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5773
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5774
	}
5775
5776
	// If someone logs in to approve API access, store the Access Code in usermeta
5777
	function store_json_api_authorization_token( $user_login, $user ) {
5778
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5779
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5780
		$token = wp_generate_password( 32, false );
5781
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5782
	}
5783
5784
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5785
	function allow_wpcom_public_api_domain( $domains ) {
5786
		$domains[] = 'public-api.wordpress.com';
5787
		return $domains;
5788
	}
5789
5790
	static function is_redirect_encoded( $redirect_url ) {
5791
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5792
	}
5793
5794
	// Add all wordpress.com environments to the safe redirect whitelist
5795
	function allow_wpcom_environments( $domains ) {
5796
		$domains[] = 'wordpress.com';
5797
		$domains[] = 'wpcalypso.wordpress.com';
5798
		$domains[] = 'horizon.wordpress.com';
5799
		$domains[] = 'calypso.localhost';
5800
		return $domains;
5801
	}
5802
5803
	// Add the Access Code details to the public-api.wordpress.com redirect
5804
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5805
		return add_query_arg(
5806
			urlencode_deep(
5807
				array(
5808
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5809
					'jetpack-user-id' => (int) $user->ID,
5810
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5811
				)
5812
			),
5813
			$redirect_to
5814
		);
5815
	}
5816
5817
5818
	/**
5819
	 * Verifies the request by checking the signature
5820
	 *
5821
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5822
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5823
	 *
5824
	 * @param null|array $environment
5825
	 */
5826
	function verify_json_api_authorization_request( $environment = null ) {
5827
		$environment = is_null( $environment )
5828
			? $_REQUEST
5829
			: $environment;
5830
5831
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5832
		$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...
5833
		if ( ! $token || empty( $token->secret ) ) {
5834
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5835
		}
5836
5837
		$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' );
5838
5839
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5840
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5841
			/**
5842
			 * Jetpack authorisation request Error.
5843
			 *
5844
			 * @since 7.5.0
5845
			 *
5846
			 */
5847
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5848
			$die_error = sprintf(
5849
				/* translators: %s is a URL */
5850
				__( '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' ),
5851
				'https://jetpack.com/support/double-encoding/'
5852
			);
5853
		}
5854
5855
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5856
5857
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5858
			$signature = $jetpack_signature->sign_request(
5859
				$environment['token'],
5860
				$environment['timestamp'],
5861
				$environment['nonce'],
5862
				'',
5863
				'GET',
5864
				$environment['jetpack_json_api_original_query'],
5865
				null,
5866
				true
5867
			);
5868
		} else {
5869
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5870
		}
5871
5872
		if ( ! $signature ) {
5873
			wp_die( $die_error );
5874
		} else if ( is_wp_error( $signature ) ) {
5875
			wp_die( $die_error );
5876
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5877
			if ( is_ssl() ) {
5878
				// 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
5879
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5880
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5881
					wp_die( $die_error );
5882
				}
5883
			} else {
5884
				wp_die( $die_error );
5885
			}
5886
		}
5887
5888
		$timestamp = (int) $environment['timestamp'];
5889
		$nonce     = stripslashes( (string) $environment['nonce'] );
5890
5891
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5892
			// De-nonce the nonce, at least for 5 minutes.
5893
			// 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)
5894
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5895
			if ( $old_nonce_time < time() - 300 ) {
5896
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5897
			}
5898
		}
5899
5900
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5901
		$data_filters = array(
5902
			'state'        => 'opaque',
5903
			'client_id'    => 'int',
5904
			'client_title' => 'string',
5905
			'client_image' => 'url',
5906
		);
5907
5908
		foreach ( $data_filters as $key => $sanitation ) {
5909
			if ( ! isset( $data->$key ) ) {
5910
				wp_die( $die_error );
5911
			}
5912
5913
			switch ( $sanitation ) {
5914
			case 'int' :
5915
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5916
				break;
5917
			case 'opaque' :
5918
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5919
				break;
5920
			case 'string' :
5921
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5922
				break;
5923
			case 'url' :
5924
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5925
				break;
5926
			}
5927
		}
5928
5929
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5930
			wp_die( $die_error );
5931
		}
5932
	}
5933
5934
	function login_message_json_api_authorization( $message ) {
5935
		return '<p class="message">' . sprintf(
5936
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5937
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5938
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5939
	}
5940
5941
	/**
5942
	 * Get $content_width, but with a <s>twist</s> filter.
5943
	 */
5944
	public static function get_content_width() {
5945
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5946
			? $GLOBALS['content_width']
5947
			: false;
5948
		/**
5949
		 * Filter the Content Width value.
5950
		 *
5951
		 * @since 2.2.3
5952
		 *
5953
		 * @param string $content_width Content Width value.
5954
		 */
5955
		return apply_filters( 'jetpack_content_width', $content_width );
5956
	}
5957
5958
	/**
5959
	 * Pings the WordPress.com Mirror Site for the specified options.
5960
	 *
5961
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5962
	 *
5963
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5964
	 */
5965
	public function get_cloud_site_options( $option_names ) {
5966
		$option_names = array_filter( (array) $option_names, 'is_string' );
5967
5968
		Jetpack::load_xml_rpc_client();
5969
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5970
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5971
		if ( $xml->isError() ) {
5972
			return array(
5973
				'error_code' => $xml->getErrorCode(),
5974
				'error_msg'  => $xml->getErrorMessage(),
5975
			);
5976
		}
5977
		$cloud_site_options = $xml->getResponse();
5978
5979
		return $cloud_site_options;
5980
	}
5981
5982
	/**
5983
	 * Checks if the site is currently in an identity crisis.
5984
	 *
5985
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5986
	 */
5987
	public static function check_identity_crisis() {
5988
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5989
			return false;
5990
		}
5991
5992
		return Jetpack_Options::get_option( 'sync_error_idc' );
5993
	}
5994
5995
	/**
5996
	 * Checks whether the home and siteurl specifically are whitelisted
5997
	 * Written so that we don't have re-check $key and $value params every time
5998
	 * we want to check if this site is whitelisted, for example in footer.php
5999
	 *
6000
	 * @since  3.8.0
6001
	 * @return bool True = already whitelisted False = not whitelisted
6002
	 */
6003
	public static function is_staging_site() {
6004
		$is_staging = false;
6005
6006
		$known_staging = array(
6007
			'urls' => array(
6008
				'#\.staging\.wpengine\.com$#i', // WP Engine
6009
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6010
				'#\.stage\.site$#i'             // DreamPress
6011
			),
6012
			'constants' => array(
6013
				'IS_WPE_SNAPSHOT',      // WP Engine
6014
				'KINSTA_DEV_ENV',       // Kinsta.com
6015
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6016
				'JETPACK_STAGING_MODE', // Generic
6017
			)
6018
		);
6019
		/**
6020
		 * Filters the flags of known staging sites.
6021
		 *
6022
		 * @since 3.9.0
6023
		 *
6024
		 * @param array $known_staging {
6025
		 *     An array of arrays that each are used to check if the current site is staging.
6026
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6027
		 *     @type array $constants PHP constants of known staging/developement environments.
6028
		 *  }
6029
		 */
6030
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6031
6032
		if ( isset( $known_staging['urls'] ) ) {
6033
			foreach ( $known_staging['urls'] as $url ){
6034
				if ( preg_match( $url, site_url() ) ) {
6035
					$is_staging = true;
6036
					break;
6037
				}
6038
			}
6039
		}
6040
6041
		if ( isset( $known_staging['constants'] ) ) {
6042
			foreach ( $known_staging['constants'] as $constant ) {
6043
				if ( defined( $constant ) && constant( $constant ) ) {
6044
					$is_staging = true;
6045
				}
6046
			}
6047
		}
6048
6049
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6050
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6051
			$is_staging = true;
6052
		}
6053
6054
		/**
6055
		 * Filters is_staging_site check.
6056
		 *
6057
		 * @since 3.9.0
6058
		 *
6059
		 * @param bool $is_staging If the current site is a staging site.
6060
		 */
6061
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6062
	}
6063
6064
	/**
6065
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6066
	 *
6067
	 * @since 4.4.0
6068
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6069
	 *
6070
	 * @return bool
6071
	 */
6072
	public static function validate_sync_error_idc_option() {
6073
		$is_valid = false;
6074
6075
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6076
		if ( false === $idc_allowed ) {
6077
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6078
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6079
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6080
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6081
				$transient_duration = HOUR_IN_SECONDS;
6082
			} else {
6083
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6084
				$idc_allowed = '1';
6085
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6086
			}
6087
6088
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6089
		}
6090
6091
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6092
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6093
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6094
			$local_options = self::get_sync_error_idc_option();
6095
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6096
				$is_valid = true;
6097
			}
6098
		}
6099
6100
		/**
6101
		 * Filters whether the sync_error_idc option is valid.
6102
		 *
6103
		 * @since 4.4.0
6104
		 *
6105
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6106
		 */
6107
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6108
6109
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6110
			// Since the option exists, and did not validate, delete it
6111
			Jetpack_Options::delete_option( 'sync_error_idc' );
6112
		}
6113
6114
		return $is_valid;
6115
	}
6116
6117
	/**
6118
	 * Normalizes a url by doing three things:
6119
	 *  - Strips protocol
6120
	 *  - Strips www
6121
	 *  - Adds a trailing slash
6122
	 *
6123
	 * @since 4.4.0
6124
	 * @param string $url
6125
	 * @return WP_Error|string
6126
	 */
6127
	public static function normalize_url_protocol_agnostic( $url ) {
6128
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6129
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6130
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6131
		}
6132
6133
		// Strip www and protocols
6134
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6135
		return $url;
6136
	}
6137
6138
	/**
6139
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6140
	 *
6141
	 * @since 4.4.0
6142
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6143
	 *
6144
	 * @param array $response
6145
	 * @return array Array of the local urls, wpcom urls, and error code
6146
	 */
6147
	public static function get_sync_error_idc_option( $response = array() ) {
6148
		// Since the local options will hit the database directly, store the values
6149
		// in a transient to allow for autoloading and caching on subsequent views.
6150
		$local_options = get_transient( 'jetpack_idc_local' );
6151
		if ( false === $local_options ) {
6152
			$local_options = array(
6153
				'home'    => Jetpack_Sync_Functions::home_url(),
6154
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6155
			);
6156
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6157
		}
6158
6159
		$options = array_merge( $local_options, $response );
6160
6161
		$returned_values = array();
6162
		foreach( $options as $key => $option ) {
6163
			if ( 'error_code' === $key ) {
6164
				$returned_values[ $key ] = $option;
6165
				continue;
6166
			}
6167
6168
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6169
				continue;
6170
			}
6171
6172
			$returned_values[ $key ] = $normalized_url;
6173
		}
6174
6175
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6176
6177
		return $returned_values;
6178
	}
6179
6180
	/**
6181
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6182
	 * If set to true, the site will be put into staging mode.
6183
	 *
6184
	 * @since 4.3.2
6185
	 * @return bool
6186
	 */
6187
	public static function sync_idc_optin() {
6188
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6189
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6190
		} else {
6191
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6192
		}
6193
6194
		/**
6195
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6196
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6197
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6198
		 *
6199
		 * @since 4.3.2
6200
		 *
6201
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6202
		 */
6203
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6204
	}
6205
6206
	/**
6207
	 * Maybe Use a .min.css stylesheet, maybe not.
6208
	 *
6209
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6210
	 */
6211
	public static function maybe_min_asset( $url, $path, $plugin ) {
6212
		// Short out on things trying to find actual paths.
6213
		if ( ! $path || empty( $plugin ) ) {
6214
			return $url;
6215
		}
6216
6217
		$path = ltrim( $path, '/' );
6218
6219
		// Strip out the abspath.
6220
		$base = dirname( plugin_basename( $plugin ) );
6221
6222
		// Short out on non-Jetpack assets.
6223
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6224
			return $url;
6225
		}
6226
6227
		// File name parsing.
6228
		$file              = "{$base}/{$path}";
6229
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6230
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6231
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6232
		$extension         = array_shift( $file_name_parts_r );
6233
6234
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6235
			// Already pointing at the minified version.
6236
			if ( 'min' === $file_name_parts_r[0] ) {
6237
				return $url;
6238
			}
6239
6240
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6241
			if ( file_exists( $min_full_path ) ) {
6242
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6243
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6244
				if ( 'css' === $extension ) {
6245
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6246
					self::$min_assets[ $key ] = $path;
6247
				}
6248
			}
6249
		}
6250
6251
		return $url;
6252
	}
6253
6254
	/**
6255
	 * If the asset is minified, let's flag .min as the suffix.
6256
	 *
6257
	 * Attached to `style_loader_src` filter.
6258
	 *
6259
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6260
	 * @param string $handle The registered handle of the script in question.
6261
	 * @param string $href The url of the asset in question.
0 ignored issues
show
Bug introduced by
There is no parameter named $href. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6262
	 */
6263
	public static function set_suffix_on_min( $src, $handle ) {
6264
		if ( false === strpos( $src, '.min.css' ) ) {
6265
			return $src;
6266
		}
6267
6268
		if ( ! empty( self::$min_assets ) ) {
6269
			foreach ( self::$min_assets as $file => $path ) {
6270
				if ( false !== strpos( $src, $file ) ) {
6271
					wp_style_add_data( $handle, 'suffix', '.min' );
6272
					return $src;
6273
				}
6274
			}
6275
		}
6276
6277
		return $src;
6278
	}
6279
6280
	/**
6281
	 * Maybe inlines a stylesheet.
6282
	 *
6283
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6284
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6285
	 *
6286
	 * Attached to `style_loader_tag` filter.
6287
	 *
6288
	 * @param string $tag The tag that would link to the external asset.
6289
	 * @param string $handle The registered handle of the script in question.
6290
	 *
6291
	 * @return string
6292
	 */
6293
	public static function maybe_inline_style( $tag, $handle ) {
6294
		global $wp_styles;
6295
		$item = $wp_styles->registered[ $handle ];
6296
6297
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6298
			return $tag;
6299
		}
6300
6301
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6302
			$href = $matches[1];
6303
			// Strip off query string
6304
			if ( $pos = strpos( $href, '?' ) ) {
6305
				$href = substr( $href, 0, $pos );
6306
			}
6307
			// Strip off fragment
6308
			if ( $pos = strpos( $href, '#' ) ) {
6309
				$href = substr( $href, 0, $pos );
6310
			}
6311
		} else {
6312
			return $tag;
6313
		}
6314
6315
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6316
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6317
			return $tag;
6318
		}
6319
6320
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6321
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6322
			// And this isn't the pass that actually deals with the RTL version...
6323
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6324
				// Short out, as the RTL version will deal with it in a moment.
6325
				return $tag;
6326
			}
6327
		}
6328
6329
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6330
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6331
		if ( $css ) {
6332
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6333
			if ( empty( $item->extra['after'] ) ) {
6334
				wp_add_inline_style( $handle, $css );
6335
			} else {
6336
				array_unshift( $item->extra['after'], $css );
6337
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6338
			}
6339
		}
6340
6341
		return $tag;
6342
	}
6343
6344
	/**
6345
	 * Loads a view file from the views
6346
	 *
6347
	 * Data passed in with the $data parameter will be available in the
6348
	 * template file as $data['value']
6349
	 *
6350
	 * @param string $template - Template file to load
6351
	 * @param array $data - Any data to pass along to the template
6352
	 * @return boolean - If template file was found
6353
	 **/
6354
	public function load_view( $template, $data = array() ) {
6355
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6356
6357
		if( file_exists( $views_dir . $template ) ) {
6358
			require_once( $views_dir . $template );
6359
			return true;
6360
		}
6361
6362
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6363
		return false;
6364
	}
6365
6366
	/**
6367
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6368
	 */
6369
	public function deprecated_hooks() {
6370
		global $wp_filter;
6371
6372
		/*
6373
		 * Format:
6374
		 * deprecated_filter_name => replacement_name
6375
		 *
6376
		 * If there is no replacement, use null for replacement_name
6377
		 */
6378
		$deprecated_list = array(
6379
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6380
			'wpl_sharing_2014_1'                                     => null,
6381
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6382
			'jetpack_identity_crisis_options_to_check'               => null,
6383
			'update_option_jetpack_single_user_site'                 => null,
6384
			'audio_player_default_colors'                            => null,
6385
			'add_option_jetpack_featured_images_enabled'             => null,
6386
			'add_option_jetpack_update_details'                      => null,
6387
			'add_option_jetpack_updates'                             => null,
6388
			'add_option_jetpack_network_name'                        => null,
6389
			'add_option_jetpack_network_allow_new_registrations'     => null,
6390
			'add_option_jetpack_network_add_new_users'               => null,
6391
			'add_option_jetpack_network_site_upload_space'           => null,
6392
			'add_option_jetpack_network_upload_file_types'           => null,
6393
			'add_option_jetpack_network_enable_administration_menus' => null,
6394
			'add_option_jetpack_is_multi_site'                       => null,
6395
			'add_option_jetpack_is_main_network'                     => null,
6396
			'add_option_jetpack_main_network_site'                   => null,
6397
			'jetpack_sync_all_registered_options'                    => null,
6398
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6399
			'jetpack_is_post_mailable'                               => null,
6400
			'jetpack_seo_site_host'                                  => null,
6401
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6402
			'jetpack_holiday_snow_option_name'                       => null,
6403
			'jetpack_holiday_chance_of_snow'                         => null,
6404
			'jetpack_holiday_snow_js_url'                            => null,
6405
			'jetpack_is_holiday_snow_season'                         => null,
6406
			'jetpack_holiday_snow_option_updated'                    => null,
6407
			'jetpack_holiday_snowing'                                => null,
6408
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6409
			'jetpack_cache_plans'                                    => null,
6410
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6411
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6412
			'jetpack_enable_site_verification'                       => null,
6413
			'can_display_jetpack_manage_notice'                      => null,
6414
			// Removed in Jetpack 7.3.0
6415
			'atd_load_scripts'                                       => null,
6416
			'atd_http_post_timeout'                                  => null,
6417
			'atd_http_post_error'                                    => null,
6418
			'atd_service_domain'                                     => null,
6419
		);
6420
6421
		// This is a silly loop depth. Better way?
6422
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6423
			if ( has_action( $hook ) ) {
6424
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6425
					foreach( $values AS $hooked ) {
6426
						if ( is_callable( $hooked['function'] ) ) {
6427
							$function_name = 'an anonymous function';
6428
						} else {
6429
							$function_name = $hooked['function'];
6430
						}
6431
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6432
					}
6433
				}
6434
			}
6435
		}
6436
	}
6437
6438
	/**
6439
	 * Converts any url in a stylesheet, to the correct absolute url.
6440
	 *
6441
	 * Considerations:
6442
	 *  - Normal, relative URLs     `feh.png`
6443
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6444
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6445
	 *  - Absolute URLs             `http://domain.com/feh.png`
6446
	 *  - Domain root relative URLs `/feh.png`
6447
	 *
6448
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6449
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6450
	 *
6451
	 * @return mixed|string
6452
	 */
6453
	public static function absolutize_css_urls( $css, $css_file_url ) {
6454
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6455
		$css_dir = dirname( $css_file_url );
6456
		$p       = parse_url( $css_dir );
6457
		$domain  = sprintf(
6458
					'%1$s//%2$s%3$s%4$s',
6459
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6460
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6461
					$p['host'],
6462
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6463
				);
6464
6465
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6466
			$find = $replace = array();
6467
			foreach ( $matches as $match ) {
6468
				$url = trim( $match['path'], "'\" \t" );
6469
6470
				// If this is a data url, we don't want to mess with it.
6471
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6472
					continue;
6473
				}
6474
6475
				// If this is an absolute or protocol-agnostic url,
6476
				// we don't want to mess with it.
6477
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6478
					continue;
6479
				}
6480
6481
				switch ( substr( $url, 0, 1 ) ) {
6482
					case '/':
6483
						$absolute = $domain . $url;
6484
						break;
6485
					default:
6486
						$absolute = $css_dir . '/' . $url;
6487
				}
6488
6489
				$find[]    = $match[0];
6490
				$replace[] = sprintf( 'url("%s")', $absolute );
6491
			}
6492
			$css = str_replace( $find, $replace, $css );
6493
		}
6494
6495
		return $css;
6496
	}
6497
6498
	/**
6499
	 * This methods removes all of the registered css files on the front end
6500
	 * from Jetpack in favor of using a single file. In effect "imploding"
6501
	 * all the files into one file.
6502
	 *
6503
	 * Pros:
6504
	 * - Uses only ONE css asset connection instead of 15
6505
	 * - Saves a minimum of 56k
6506
	 * - Reduces server load
6507
	 * - Reduces time to first painted byte
6508
	 *
6509
	 * Cons:
6510
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6511
	 *		should not cause any issues with themes.
6512
	 * - Plugins/themes dequeuing styles no longer do anything. See
6513
	 *		jetpack_implode_frontend_css filter for a workaround
6514
	 *
6515
	 * For some situations developers may wish to disable css imploding and
6516
	 * instead operate in legacy mode where each file loads seperately and
6517
	 * can be edited individually or dequeued. This can be accomplished with
6518
	 * the following line:
6519
	 *
6520
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6521
	 *
6522
	 * @since 3.2
6523
	 **/
6524
	public function implode_frontend_css( $travis_test = false ) {
6525
		$do_implode = true;
6526
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6527
			$do_implode = false;
6528
		}
6529
6530
		// Do not implode CSS when the page loads via the AMP plugin.
6531
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6532
			$do_implode = false;
6533
		}
6534
6535
		/**
6536
		 * Allow CSS to be concatenated into a single jetpack.css file.
6537
		 *
6538
		 * @since 3.2.0
6539
		 *
6540
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6541
		 */
6542
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6543
6544
		// Do not use the imploded file when default behavior was altered through the filter
6545
		if ( ! $do_implode ) {
6546
			return;
6547
		}
6548
6549
		// We do not want to use the imploded file in dev mode, or if not connected
6550
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6551
			if ( ! $travis_test ) {
6552
				return;
6553
			}
6554
		}
6555
6556
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6557
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6558
			return;
6559
		}
6560
6561
		/*
6562
		 * Now we assume Jetpack is connected and able to serve the single
6563
		 * file.
6564
		 *
6565
		 * In the future there will be a check here to serve the file locally
6566
		 * or potentially from the Jetpack CDN
6567
		 *
6568
		 * For now:
6569
		 * - Enqueue a single imploded css file
6570
		 * - Zero out the style_loader_tag for the bundled ones
6571
		 * - Be happy, drink scotch
6572
		 */
6573
6574
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6575
6576
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6577
6578
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6579
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6580
	}
6581
6582
	function concat_remove_style_loader_tag( $tag, $handle ) {
6583
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6584
			$tag = '';
6585
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6586
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6587
			}
6588
		}
6589
6590
		return $tag;
6591
	}
6592
6593
	/*
6594
	 * Check the heartbeat data
6595
	 *
6596
	 * Organizes the heartbeat data by severity.  For example, if the site
6597
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6598
	 *
6599
	 * Data will be added to "caution" array, if it either:
6600
	 *  - Out of date Jetpack version
6601
	 *  - Out of date WP version
6602
	 *  - Out of date PHP version
6603
	 *
6604
	 * $return array $filtered_data
6605
	 */
6606
	public static function jetpack_check_heartbeat_data() {
6607
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6608
6609
		$good    = array();
6610
		$caution = array();
6611
		$bad     = array();
6612
6613
		foreach ( $raw_data as $stat => $value ) {
6614
6615
			// Check jetpack version
6616
			if ( 'version' == $stat ) {
6617
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6618
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6619
					continue;
6620
				}
6621
			}
6622
6623
			// Check WP version
6624
			if ( 'wp-version' == $stat ) {
6625
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6626
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6627
					continue;
6628
				}
6629
			}
6630
6631
			// Check PHP version
6632
			if ( 'php-version' == $stat ) {
6633
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6634
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6635
					continue;
6636
				}
6637
			}
6638
6639
			// Check ID crisis
6640
			if ( 'identitycrisis' == $stat ) {
6641
				if ( 'yes' == $value ) {
6642
					$bad[ $stat ] = $value;
6643
					continue;
6644
				}
6645
			}
6646
6647
			// The rest are good :)
6648
			$good[ $stat ] = $value;
6649
		}
6650
6651
		$filtered_data = array(
6652
			'good'    => $good,
6653
			'caution' => $caution,
6654
			'bad'     => $bad
6655
		);
6656
6657
		return $filtered_data;
6658
	}
6659
6660
6661
	/*
6662
	 * This method is used to organize all options that can be reset
6663
	 * without disconnecting Jetpack.
6664
	 *
6665
	 * It is used in class.jetpack-cli.php to reset options
6666
	 *
6667
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6668
	 *
6669
	 * @return array of options to delete.
6670
	 */
6671
	public static function get_jetpack_options_for_reset() {
6672
		return Jetpack_Options::get_options_for_reset();
6673
	}
6674
6675
	/*
6676
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6677
	 * so we can bring them directly to their site in calypso.
6678
	 *
6679
	 * @param string | url
6680
	 * @return string | url without the guff
6681
	 */
6682
	public static function build_raw_urls( $url ) {
6683
		$strip_http = '/.*?:\/\//i';
6684
		$url = preg_replace( $strip_http, '', $url  );
6685
		$url = str_replace( '/', '::', $url );
6686
		return $url;
6687
	}
6688
6689
	/**
6690
	 * Stores and prints out domains to prefetch for page speed optimization.
6691
	 *
6692
	 * @param mixed $new_urls
6693
	 */
6694
	public static function dns_prefetch( $new_urls = null ) {
6695
		static $prefetch_urls = array();
6696
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6697
			echo "\r\n";
6698
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6699
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6700
			}
6701
		} elseif ( ! empty( $new_urls ) ) {
6702
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6703
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6704
			}
6705
			foreach ( (array) $new_urls as $this_new_url ) {
6706
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6707
			}
6708
			$prefetch_urls = array_unique( $prefetch_urls );
6709
		}
6710
	}
6711
6712
	public function wp_dashboard_setup() {
6713
		if ( self::is_active() ) {
6714
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6715
		}
6716
6717
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6718
			$jetpack_logo = new Jetpack_Logo();
6719
			$widget_title = sprintf(
6720
				wp_kses(
6721
					/* translators: Placeholder is a Jetpack logo. */
6722
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6723
					array( 'span' => array() )
6724
				),
6725
				$jetpack_logo->get_jp_emblem( true )
6726
			);
6727
6728
			wp_add_dashboard_widget(
6729
				'jetpack_summary_widget',
6730
				$widget_title,
6731
				array( __CLASS__, 'dashboard_widget' )
6732
			);
6733
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6734
6735
			// If we're inactive and not in development mode, sort our box to the top.
6736
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6737
				global $wp_meta_boxes;
6738
6739
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6740
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6741
6742
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6743
			}
6744
		}
6745
	}
6746
6747
	/**
6748
	 * @param mixed $result Value for the user's option
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6749
	 * @return mixed
6750
	 */
6751
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6752
		if ( ! is_array( $sorted ) ) {
6753
			return $sorted;
6754
		}
6755
6756
		foreach ( $sorted as $box_context => $ids ) {
6757
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6758
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6759
				continue;
6760
			}
6761
6762
			$ids_array = explode( ',', $ids );
6763
			$key = array_search( 'dashboard_stats', $ids_array );
6764
6765
			if ( false !== $key ) {
6766
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6767
				$ids_array[ $key ] = 'jetpack_summary_widget';
6768
				$sorted[ $box_context ] = implode( ',', $ids_array );
6769
				// We've found it, stop searching, and just return.
6770
				break;
6771
			}
6772
		}
6773
6774
		return $sorted;
6775
	}
6776
6777
	public static function dashboard_widget() {
6778
		/**
6779
		 * Fires when the dashboard is loaded.
6780
		 *
6781
		 * @since 3.4.0
6782
		 */
6783
		do_action( 'jetpack_dashboard_widget' );
6784
	}
6785
6786
	public static function dashboard_widget_footer() {
6787
		?>
6788
		<footer>
6789
6790
		<div class="protect">
6791
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6792
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6793
				<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>
6794
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6795
				<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' ); ?>">
6796
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6797
				</a>
6798
			<?php else : ?>
6799
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6800
			<?php endif; ?>
6801
		</div>
6802
6803
		<div class="akismet">
6804
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6805
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6806
				<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>
6807
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6808
				<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">
6809
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6810
				</a>
6811
			<?php else : ?>
6812
				<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>
6813
			<?php endif; ?>
6814
		</div>
6815
6816
		</footer>
6817
		<?php
6818
	}
6819
6820
	/*
6821
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6822
	 */
6823
	function jetpack_icon_user_connected( $columns ) {
6824
		$columns['user_jetpack'] = '';
6825
		return $columns;
6826
	}
6827
6828
	/*
6829
	 * Show Jetpack icon if the user is linked.
6830
	 */
6831
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6832
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6833
			$jetpack_logo = new Jetpack_Logo();
6834
			$emblem_html = sprintf(
6835
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6836
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6837
				$jetpack_logo->get_jp_emblem()
6838
			);
6839
			return $emblem_html;
6840
		}
6841
6842
		return $val;
6843
	}
6844
6845
	/*
6846
	 * Style the Jetpack user column
6847
	 */
6848
	function jetpack_user_col_style() {
6849
		global $current_screen;
6850
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6851
			<style>
6852
				.fixed .column-user_jetpack {
6853
					width: 21px;
6854
				}
6855
				.jp-emblem-user-admin svg {
6856
					width: 20px;
6857
					height: 20px;
6858
				}
6859
				.jp-emblem-user-admin path {
6860
					fill: #00BE28;
6861
				}
6862
			</style>
6863
		<?php }
6864
	}
6865
6866
	/**
6867
	 * Checks if Akismet is active and working.
6868
	 *
6869
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6870
	 * that implied usage of methods present since more recent version.
6871
	 * See https://github.com/Automattic/jetpack/pull/9585
6872
	 *
6873
	 * @since  5.1.0
6874
	 *
6875
	 * @return bool True = Akismet available. False = Aksimet not available.
6876
	 */
6877
	public static function is_akismet_active() {
6878
		static $status = null;
6879
6880
		if ( ! is_null( $status ) ) {
6881
			return $status;
6882
		}
6883
6884
		// Check if a modern version of Akismet is active.
6885
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6886
			$status = false;
6887
			return $status;
6888
		}
6889
6890
		// Make sure there is a key known to Akismet at all before verifying key.
6891
		$akismet_key = Akismet::get_api_key();
6892
		if ( ! $akismet_key ) {
6893
			$status = false;
6894
			return $status;
6895
		}
6896
6897
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6898
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6899
6900
		// 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.
6901
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6902
		// We cache the result of the Akismet key verification for ten minutes.
6903
		if ( ! $akismet_key_state || $recheck ) {
6904
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6905
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6906
		}
6907
6908
		$status = 'valid' === $akismet_key_state;
6909
6910
		return $status;
6911
	}
6912
6913
	/**
6914
	 * Checks if one or more function names is in debug_backtrace
6915
	 *
6916
	 * @param $names Mixed string name of function or array of string names of functions
6917
	 *
6918
	 * @return bool
6919
	 */
6920
	public static function is_function_in_backtrace( $names ) {
6921
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6922
		if ( ! is_array( $names ) ) {
6923
			$names = array( $names );
6924
		}
6925
		$names_as_keys = array_flip( $names );
6926
6927
		//Do check in constant O(1) time for PHP5.5+
6928
		if ( function_exists( 'array_column' ) ) {
6929
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6930
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6931
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6932
			return ! empty ( $intersection );
6933
		}
6934
6935
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6936
		foreach ( $backtrace as $call ) {
6937
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6938
				return true;
6939
			}
6940
		}
6941
		return false;
6942
	}
6943
6944
	/**
6945
	 * Given a minified path, and a non-minified path, will return
6946
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6947
	 *
6948
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6949
	 * root Jetpack directory.
6950
	 *
6951
	 * @since 5.6.0
6952
	 *
6953
	 * @param string $min_path
6954
	 * @param string $non_min_path
6955
	 * @return string The URL to the file
6956
	 */
6957
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6958
		$path = ( Constants::is_defined( 'SCRIPT_DEBUG' ) && Constants::get_constant( 'SCRIPT_DEBUG' ) )
6959
			? $non_min_path
6960
			: $min_path;
6961
6962
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6963
	}
6964
6965
	/**
6966
	 * Checks for whether Jetpack Backup & Scan is enabled.
6967
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6968
	 * @return bool|int|mixed
6969
	 */
6970
	public static function is_rewind_enabled() {
6971
		if ( ! Jetpack::is_active() ) {
6972
			return false;
6973
		}
6974
6975
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6976
		if ( false === $rewind_enabled ) {
6977
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6978
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6979
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6980
				&& ! empty( $rewind_data['state'] )
6981
				&& 'active' === $rewind_data['state'] )
6982
				? 1
6983
				: 0;
6984
6985
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6986
		}
6987
		return $rewind_enabled;
6988
	}
6989
6990
	/**
6991
	 * Return Calypso environment value; used for developing Jetpack and pairing
6992
	 * it with different Calypso enrionments, such as localhost.
6993
	 *
6994
	 * @since 7.4.0
6995
	 *
6996
	 * @return string Calypso environment
6997
	 */
6998
	public static function get_calypso_env() {
6999
		if ( isset( $_GET['calypso_env'] ) ) {
7000
			return sanitize_key( $_GET['calypso_env'] );
7001
		}
7002
7003
		if ( getenv( 'CALYPSO_ENV' ) ) {
7004
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7005
		}
7006
7007
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7008
			return sanitize_key( CALYPSO_ENV );
7009
		}
7010
7011
		return '';
7012
	}
7013
7014
	/**
7015
	 * Checks whether or not TOS has been agreed upon.
7016
	 * Will return true if a user has clicked to register, or is already connected.
7017
	 */
7018
	public static function jetpack_tos_agreed() {
7019
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7020
	}
7021
7022
	/**
7023
	 * Handles activating default modules as well general cleanup for the new connection.
7024
	 *
7025
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7026
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7027
	 * @param boolean $send_state_messages          Whether to send state messages.
7028
	 * @return void
7029
	 */
7030
	public static function handle_post_authorization_actions(
7031
		$activate_sso = false,
7032
		$redirect_on_activation_error = false,
7033
		$send_state_messages = true
7034
	) {
7035
		$other_modules = $activate_sso
7036
			? array( 'sso' )
7037
			: array();
7038
7039
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7040
			Jetpack::delete_active_modules();
7041
7042
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
Documentation introduced by
999 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...
7043
		} else {
7044
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7045
		}
7046
7047
		// Since this is a fresh connection, be sure to clear out IDC options
7048
		Jetpack_IDC::clear_all_idc_options();
7049
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7050
7051
		// Start nonce cleaner
7052
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7053
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7054
7055
		if ( $send_state_messages ) {
7056
			Jetpack::state( 'message', 'authorized' );
7057
		}
7058
	}
7059
7060
	/**
7061
	 * Returns a boolean for whether backups UI should be displayed or not.
7062
	 *
7063
	 * @return bool Should backups UI be displayed?
7064
	 */
7065
	public static function show_backups_ui() {
7066
		/**
7067
		 * Whether UI for backups should be displayed.
7068
		 *
7069
		 * @since 6.5.0
7070
		 *
7071
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7072
		 */
7073
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7074
	}
7075
7076
	/*
7077
	 * Deprecated manage functions
7078
	 */
7079
	function prepare_manage_jetpack_notice() {
7080
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7081
	}
7082
	function manage_activate_screen() {
7083
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7084
	}
7085
	function admin_jetpack_manage_notice() {
7086
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7087
	}
7088
	function opt_out_jetpack_manage_url() {
7089
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7090
	}
7091
	function opt_in_jetpack_manage_url() {
7092
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7093
	}
7094
	function opt_in_jetpack_manage_notice() {
7095
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7096
	}
7097
	function can_display_jetpack_manage_notice() {
7098
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7099
	}
7100
7101
	/**
7102
	 * Clean leftoveruser meta.
7103
	 *
7104
	 * Delete Jetpack-related user meta when it is no longer needed.
7105
	 *
7106
	 * @since 7.3.0
7107
	 *
7108
	 * @param int $user_id User ID being updated.
7109
	 */
7110
	public static function user_meta_cleanup( $user_id ) {
7111
		$meta_keys = array(
7112
			// AtD removed from Jetpack 7.3
7113
			'AtD_options',
7114
			'AtD_check_when',
7115
			'AtD_guess_lang',
7116
			'AtD_ignored_phrases',
7117
		);
7118
7119
		foreach ( $meta_keys as $meta_key ) {
7120
			if ( get_user_meta( $user_id, $meta_key ) ) {
7121
				delete_user_meta( $user_id, $meta_key );
7122
			}
7123
		}
7124
	}
7125
7126
	function is_active_and_not_development_mode( $maybe ) {
7127
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7128
			return false;
7129
		}
7130
		return true;
7131
	}
7132
7133
}
7134