Completed
Push — phpcs/jetpack ( 47f0fe )
by
unknown
72:37 queued 62:26
created

Jetpack::maybe_inline_style()   C

Complexity

Conditions 13
Paths 34

Size

Total Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
nc 34
nop 2
dl 0
loc 50
rs 6.6166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
use Automattic\Jetpack\Assets;
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Config;
5
use Automattic\Jetpack\Connection\Client;
6
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7
use Automattic\Jetpack\Connection\Plugin_Storage as Connection_Plugin_Storage;
8
use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
9
use Automattic\Jetpack\Connection\Webhooks as Connection_Webhooks;
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
12
use Automattic\Jetpack\Licensing;
13
use Automattic\Jetpack\Partner;
14
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
15
use Automattic\Jetpack\Redirect;
16
use Automattic\Jetpack\Status;
17
use Automattic\Jetpack\Sync\Functions;
18
use Automattic\Jetpack\Sync\Health;
19
use Automattic\Jetpack\Sync\Sender;
20
use Automattic\Jetpack\Terms_Of_Service;
21
use Automattic\Jetpack\Tracking;
22
23
/*
24
Options:
25
jetpack_options (array)
26
	An array of options.
27
	@see Jetpack_Options::get_option_names()
28
29
jetpack_register (string)
30
	Temporary verification secrets.
31
32
jetpack_activated (int)
33
	1: the plugin was activated normally
34
	2: the plugin was activated on this site because of a network-wide activation
35
	3: the plugin was auto-installed
36
	4: the plugin was manually disconnected (but is still installed)
37
38
jetpack_active_modules (array)
39
	Array of active module slugs.
40
41
jetpack_do_activate (bool)
42
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
43
*/
44
45
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
46
47
/**
48
 * Class Jetpack
49
 *
50
 * Everything. Too much. A bucket for Jetpack functions before namespacing was a thing.
51
 *
52
 * Extends Jetpack_Deprecated, which is another bucket for things that used to be here.
53
 */
54
class Jetpack extends Jetpack_Deprecated {
55
	public $xmlrpc_server = null;
56
57
	/**
58
	 * @var array The handles of styles that are concatenated into jetpack.css.
59
	 *
60
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
61
	 */
62
	public $concatenated_style_handles = array(
63
		'jetpack-carousel',
64
		'grunion.css',
65
		'the-neverending-homepage',
66
		'jetpack_likes',
67
		'jetpack_related-posts',
68
		'sharedaddy',
69
		'jetpack-slideshow',
70
		'presentations',
71
		'quiz',
72
		'jetpack-subscriptions',
73
		'jetpack-responsive-videos-style',
74
		'jetpack-social-menu',
75
		'tiled-gallery',
76
		'jetpack_display_posts_widget',
77
		'gravatar-profile-widget',
78
		'goodreads-widget',
79
		'jetpack_social_media_icons_widget',
80
		'jetpack-top-posts-widget',
81
		'jetpack_image_widget',
82
		'jetpack-my-community-widget',
83
		'jetpack-authors-widget',
84
		'wordads',
85
		'eu-cookie-law-style',
86
		'flickr-widget-style',
87
		'jetpack-search-widget',
88
		'jetpack-simple-payments-widget-style',
89
		'jetpack-widget-social-icons-styles',
90
		'wpcom_instagram_widget',
91
	);
92
93
	/**
94
	 * Contains all assets that have had their URL rewritten to minified versions.
95
	 *
96
	 * @var array
97
	 */
98
	static $min_assets = array();
99
100
	public $plugins_to_deactivate = array(
101
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
102
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
103
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
104
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
105
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
106
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
107
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
108
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
109
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
110
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
111
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
112
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
113
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
114
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
115
	);
116
117
	/**
118
	 * Map of modules that have conflicts with plugins and should not be auto-activated
119
	 * if the plugins are active.  Used by filter_default_modules
120
	 *
121
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
122
	 * change `module-slug` and add this to your plugin:
123
	 *
124
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
125
	 * function my_jetpack_get_default_modules( $modules ) {
126
	 *     return array_diff( $modules, array( 'module-slug' ) );
127
	 * }
128
	 *
129
	 * @var array
130
	 */
131
	private $conflicting_plugins = array(
132
		'comments'           => array(
133
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
134
			'Disqus'                         => 'disqus-comment-system/disqus.php',
135
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
136
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
137
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
138
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
139
		),
140
		'comment-likes'      => array(
141
			'Epoch' => 'epoch/plugincore.php',
142
		),
143
		'contact-form'       => array(
144
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
145
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
146
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
147
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
148
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
149
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
150
		),
151
		'latex'              => array(
152
			'LaTeX for WordPress'     => 'latex/latex.php',
153
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
154
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
155
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
156
			'Enable Latex'            => 'enable-latex/enable-latex.php',
157
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
158
		),
159
		'protect'            => array(
160
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
161
			'Captcha'                           => 'captcha/captcha.php',
162
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
163
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
164
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
165
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
166
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
167
			'Security-protection'               => 'security-protection/security-protection.php',
168
			'Login Security'                    => 'login-security/login-security.php',
169
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
170
			'Wordfence Security'                => 'wordfence/wordfence.php',
171
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
172
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
173
		),
174
		'random-redirect'    => array(
175
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
176
		),
177
		'related-posts'      => array(
178
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
179
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
180
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
181
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
182
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
183
			'outbrain'                    => 'outbrain/outbrain.php',
184
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
185
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
186
		),
187
		'sharedaddy'         => array(
188
			'AddThis'     => 'addthis/addthis_social_widget.php',
189
			'Add To Any'  => 'add-to-any/add-to-any.php',
190
			'ShareThis'   => 'share-this/sharethis.php',
191
			'Shareaholic' => 'shareaholic/shareaholic.php',
192
		),
193
		'seo-tools'          => array(
194
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
195
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
196
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
197
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
198
			'The SEO Framework'              => 'autodescription/autodescription.php',
199
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
200
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
201
		),
202
		'verification-tools' => array(
203
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
204
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
205
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
206
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
207
			'The SEO Framework'              => 'autodescription/autodescription.php',
208
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
209
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
210
		),
211
		'widget-visibility'  => array(
212
			'Widget Logic'    => 'widget-logic/widget_logic.php',
213
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
214
		),
215
		'sitemaps'           => array(
216
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
217
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
218
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
219
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
220
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
221
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
222
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
223
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
224
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
225
			'The SEO Framework'                    => 'autodescription/autodescription.php',
226
			'Sitemap'                              => 'sitemap/sitemap.php',
227
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
228
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
229
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
230
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
231
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
232
			'Slim SEO'                             => 'slim-seo/slim-seo.php',
233
		),
234
		'lazy-images'        => array(
235
			'Lazy Load'              => 'lazy-load/lazy-load.php',
236
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
237
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
238
		),
239
	);
240
241
	/**
242
	 * Plugins for which we turn off our Facebook OG Tags implementation.
243
	 *
244
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
245
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
246
	 *
247
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
248
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
249
	 */
250
	private $open_graph_conflicting_plugins = array(
251
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
252
		// 2 Click Social Media Buttons
253
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
254
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
255
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
256
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
257
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
258
		// Open Graph Meta Tags by Heateor
259
		'facebook/facebook.php',                                 // Facebook (official plugin)
260
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
261
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
262
		// Facebook Featured Image & OG Meta Tags
263
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
264
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
265
		// Facebook Open Graph Meta Tags for WordPress
266
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
267
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
268
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
269
		// Fedmich's Facebook Open Graph Meta
270
		'network-publisher/networkpub.php',                      // Network Publisher
271
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
272
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
273
		// NextScripts SNAP
274
		'og-tags/og-tags.php',                                   // OG Tags
275
		'opengraph/opengraph.php',                               // Open Graph
276
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
277
		// Open Graph Protocol Framework
278
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
279
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
280
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
281
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
282
		'sharepress/sharepress.php',                             // SharePress
283
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
284
		'social-discussions/social-discussions.php',             // Social Discussions
285
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
286
		'socialize/socialize.php',                               // Socialize
287
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
288
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
289
		// Tweet, Like, Google +1 and Share
290
		'wordbooker/wordbooker.php',                             // Wordbooker
291
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
292
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
293
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
294
		// WP Facebook Like Send & Open Graph Meta
295
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
296
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
297
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
298
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
299
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
300
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
301
		'slim-seo/slim-seo.php',                                 // Slim SEO
302
	);
303
304
	/**
305
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
306
	 */
307
	private $twitter_cards_conflicting_plugins = array(
308
		// 'twitter/twitter.php',                       // The official one handles this on its own.
309
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
310
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
311
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
312
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
313
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
314
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
315
		'twitter-cards/twitter-cards.php',           // Twitter Cards
316
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
317
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
318
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
319
		'seo-by-rank-math/rank-math.php',            // Rank Math.
320
		'slim-seo/slim-seo.php',                     // Slim SEO
321
	);
322
323
	/**
324
	 * Message to display in admin_notice
325
	 *
326
	 * @var string
327
	 */
328
	public $message = '';
329
330
	/**
331
	 * Error to display in admin_notice
332
	 *
333
	 * @var string
334
	 */
335
	public $error = '';
336
337
	/**
338
	 * Modules that need more privacy description.
339
	 *
340
	 * @var string
341
	 */
342
	public $privacy_checks = '';
343
344
	/**
345
	 * Stats to record once the page loads
346
	 *
347
	 * @var array
348
	 */
349
	public $stats = array();
350
351
	/**
352
	 * Jetpack_Sync object
353
	 */
354
	public $sync;
355
356
	/**
357
	 * Verified data for JSON authorization request
358
	 */
359
	public $json_api_authorization_request = array();
360
361
	/**
362
	 * @var Automattic\Jetpack\Connection\Manager
363
	 */
364
	protected $connection_manager;
365
366
	/**
367
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
368
	 */
369
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
370
371
	/**
372
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
373
	 *
374
	 * @var Automattic\Jetpack\A8c_Mc_Stats
375
	 */
376
	public $a8c_mc_stats_instance;
377
378
	/**
379
	 * Constant for login redirect key.
380
	 *
381
	 * @var string
382
	 * @since 8.4.0
383
	 */
384
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
385
386
	/**
387
	 * Holds the singleton instance of this class
388
	 *
389
	 * @since 2.3.3
390
	 * @var Jetpack
391
	 */
392
	static $instance = false;
393
394
	/**
395
	 * Singleton
396
	 *
397
	 * @static
398
	 */
399
	public static function init() {
400
		if ( ! self::$instance ) {
401
			self::$instance = new Jetpack();
402
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
403
		}
404
405
		return self::$instance;
406
	}
407
408
	/**
409
	 * Must never be called statically
410
	 */
411
	function plugin_upgrade() {
412
		if ( self::is_active() ) {
413
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
414
			if ( JETPACK__VERSION != $version ) {
415
				// Prevent multiple upgrades at once - only a single process should trigger
416
				// an upgrade to avoid stampedes
417
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
418
					return;
419
				}
420
421
				// Set a short lock to prevent multiple instances of the upgrade
422
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
423
424
				// check which active modules actually exist and remove others from active_modules list
425
				$unfiltered_modules = self::get_active_modules();
426
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
427
				if ( array_diff( $unfiltered_modules, $modules ) ) {
428
					self::update_active_modules( $modules );
429
				}
430
431
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
432
433
				// Upgrade to 4.3.0
434
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
435
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
436
				}
437
438
				// Make sure Markdown for posts gets turned back on
439
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
440
					update_option( 'wpcom_publish_posts_with_markdown', true );
441
				}
442
443
				/*
444
				 * Minileven deprecation. 8.3.0.
445
				 * Only delete options if not using
446
				 * the replacement standalone Minileven plugin.
447
				 */
448
				if (
449
					! self::is_plugin_active( 'minileven-master/minileven.php' )
450
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
451
				) {
452
					if ( get_option( 'wp_mobile_custom_css' ) ) {
453
						delete_option( 'wp_mobile_custom_css' );
454
					}
455
					if ( get_option( 'wp_mobile_excerpt' ) ) {
456
						delete_option( 'wp_mobile_excerpt' );
457
					}
458
					if ( get_option( 'wp_mobile_featured_images' ) ) {
459
						delete_option( 'wp_mobile_featured_images' );
460
					}
461
					if ( get_option( 'wp_mobile_app_promos' ) ) {
462
						delete_option( 'wp_mobile_app_promos' );
463
					}
464
				}
465
466
				// Upgrade to 8.4.0.
467
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
468
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
469
				}
470
471
				// Update to 8.8.x (WordPress 5.5 Compatibility).
472
				if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
473
					$updated = update_site_option(
474
						'auto_update_plugins',
475
						array_unique(
476
							array_merge(
477
								(array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
478
								(array) get_site_option( 'auto_update_plugins', array() )
479
							)
480
						)
481
					);
482
483
					if ( $updated ) {
484
						Jetpack_Options::delete_option( 'autoupdate_plugins' );
485
					} // Should we have some type of fallback if something fails here?
486
				}
487
488
				if ( did_action( 'wp_loaded' ) ) {
489
					self::upgrade_on_load();
490
				} else {
491
					add_action(
492
						'wp_loaded',
493
						array( __CLASS__, 'upgrade_on_load' )
494
					);
495
				}
496
			}
497
		}
498
	}
499
500
	/**
501
	 * Runs upgrade routines that need to have modules loaded.
502
	 */
503
	static function upgrade_on_load() {
504
505
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
506
		// This can happen in case Jetpack has been just upgraded and is
507
		// being initialized late during the page load. In this case we wait
508
		// until the next proper admin page load with Jetpack active.
509
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
510
			delete_transient( self::$plugin_upgrade_lock_key );
511
512
			return;
513
		}
514
515
		self::maybe_set_version_option();
516
517
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
518
			Jetpack_Widget_Conditions::migrate_post_type_rules();
519
		}
520
521
		if (
522
			class_exists( 'Jetpack_Sitemap_Manager' )
523
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
524
		) {
525
			do_action( 'jetpack_sitemaps_purge_data' );
526
		}
527
528
		// Delete old stats cache
529
		delete_option( 'jetpack_restapi_stats_cache' );
530
531
		delete_transient( self::$plugin_upgrade_lock_key );
532
	}
533
534
	/**
535
	 * Saves all the currently active modules to options.
536
	 * Also fires Action hooks for each newly activated and deactivated module.
537
	 *
538
	 * @param $modules Array Array of active modules to be saved in options.
539
	 *
540
	 * @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...
541
	 */
542
	static function update_active_modules( $modules ) {
543
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
544
		$active_modules       = self::get_active_modules();
545
		$new_active_modules   = array_diff( $modules, $current_modules );
546
		$new_inactive_modules = array_diff( $active_modules, $modules );
547
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
548
		$reindexed_modules    = array_values( $new_current_modules );
549
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
550
551
		foreach ( $new_active_modules as $module ) {
552
			/**
553
			 * Fires when a specific module is activated.
554
			 *
555
			 * @since 1.9.0
556
			 *
557
			 * @param string $module Module slug.
558
			 * @param boolean $success whether the module was activated. @since 4.2
559
			 */
560
			do_action( 'jetpack_activate_module', $module, $success );
561
			/**
562
			 * Fires when a module is activated.
563
			 * The dynamic part of the filter, $module, is the module slug.
564
			 *
565
			 * @since 1.9.0
566
			 *
567
			 * @param string $module Module slug.
568
			 */
569
			do_action( "jetpack_activate_module_$module", $module );
570
		}
571
572
		foreach ( $new_inactive_modules as $module ) {
573
			/**
574
			 * Fired after a module has been deactivated.
575
			 *
576
			 * @since 4.2.0
577
			 *
578
			 * @param string $module Module slug.
579
			 * @param boolean $success whether the module was deactivated.
580
			 */
581
			do_action( 'jetpack_deactivate_module', $module, $success );
582
			/**
583
			 * Fires when a module is deactivated.
584
			 * The dynamic part of the filter, $module, is the module slug.
585
			 *
586
			 * @since 1.9.0
587
			 *
588
			 * @param string $module Module slug.
589
			 */
590
			do_action( "jetpack_deactivate_module_$module", $module );
591
		}
592
593
		return $success;
594
	}
595
596
	static function delete_active_modules() {
597
		self::update_active_modules( array() );
598
	}
599
600
	/**
601
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
602
	 * available.
603
	 */
604
	public function add_configure_hook() {
605
		global $wp_filter;
606
607
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
608
		if ( false !== $current_priority ) {
609
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
610
		}
611
612
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
613
		sort( $taken_priorities );
614
615
		$first_priority = array_shift( $taken_priorities );
616
617
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
618
			$new_priority = - PHP_INT_MAX;
619
		} else {
620
			$new_priority = $first_priority - 1;
621
		}
622
623
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
624
	}
625
626
	/**
627
	 * Constructor.  Initializes WordPress hooks
628
	 */
629
	private function __construct() {
630
		/*
631
		 * Check for and alert any deprecated hooks
632
		 */
633
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
634
635
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
636
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
637
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
638
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
639
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
640
641
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
642
643
		add_filter(
644
			'jetpack_signature_check_token',
645
			array( __CLASS__, 'verify_onboarding_token' ),
646
			10,
647
			3
648
		);
649
650
		/**
651
		 * Prepare Gutenberg Editor functionality
652
		 */
653
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
654
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
655
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
656
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
657
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
658
659
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
660
661
		// Unlink user before deleting the user from WP.com.
662
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
663
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
664
665
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
666
667
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
668
		add_action( 'login_init', array( $this, 'login_init' ) );
669
670
		// Set up the REST authentication hooks.
671
		Connection_Rest_Authentication::init();
672
673
		add_action( 'admin_init', array( $this, 'admin_init' ) );
674
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
675
676
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
677
678
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
679
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
680
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
681
682
		// returns HTTPS support status
683
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
684
685
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
686
687
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
688
689
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
690
691
		/**
692
		 * These actions run checks to load additional files.
693
		 * They check for external files or plugins, so they need to run as late as possible.
694
		 */
695
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
696
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
697
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
698
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
699
700
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
701
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
702
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
703
704
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
705
706
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
707
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
708
709
		// A filter to control all just in time messages
710
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
711
712
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
713
714
		/*
715
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
716
		 * We should make sure to only do this for front end links.
717
		 */
718
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
719
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
720
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
721
722
			/*
723
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
724
			 * so they point moderation links on emails to Calypso.
725
			 */
726
			jetpack_require_lib( 'functions.wp-notify' );
727
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
728
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
729
		}
730
731
		add_action(
732
			'plugins_loaded',
733
			function () {
734
				if ( User_Agent_Info::is_mobile_app() ) {
735
					add_filter( 'get_edit_post_link', '__return_empty_string' );
736
				}
737
			}
738
		);
739
740
		// Update the site's Jetpack plan and products from API on heartbeats.
741
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
742
743
		/**
744
		 * This is the hack to concatenate all css files into one.
745
		 * For description and reasoning see the implode_frontend_css method.
746
		 *
747
		 * Super late priority so we catch all the registered styles.
748
		 */
749
		if ( ! is_admin() ) {
750
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
751
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
752
		}
753
754
		/**
755
		 * These are sync actions that we need to keep track of for jitms
756
		 */
757
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
758
759
		// Actually push the stats on shutdown.
760
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
761
			add_action( 'shutdown', array( $this, 'push_stats' ) );
762
		}
763
764
		// Actions for Manager::authorize().
765
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
766
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
767
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
768
769
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
770
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
771
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
772
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
773
774
		// Filters for the Manager::get_token() urls and request body.
775
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
776
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
777
778
		// Actions for successful reconnect.
779
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
780
781
		// Actions for licensing.
782
		Licensing::instance()->initialize();
783
784
		// Make resources use static domain when possible.
785
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
786
	}
787
788
	/**
789
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
790
	 * Config object.
791
	 */
792
	public function configure() {
793
		$config = new Config();
794
795
		foreach (
796
			array(
797
				'sync',
798
			)
799
			as $feature
800
		) {
801
			$config->ensure( $feature );
802
		}
803
804
		$config->ensure(
805
			'connection',
806
			array(
807
				'slug' => 'jetpack',
808
				'name' => 'Jetpack',
809
			)
810
		);
811
812
		if ( is_admin() ) {
813
			$config->ensure( 'jitm' );
814
		}
815
816
		if ( ! $this->connection_manager ) {
817
			$this->connection_manager = new Connection_Manager( 'jetpack' );
818
		}
819
820
		/*
821
		 * Load things that should only be in Network Admin.
822
		 *
823
		 * For now blow away everything else until a more full
824
		 * understanding of what is needed at the network level is
825
		 * available
826
		 */
827
		if ( is_multisite() ) {
828
			$network = Jetpack_Network::init();
829
			$network->set_connection( $this->connection_manager );
830
		}
831
832
		if ( $this->connection_manager->is_active() ) {
833
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
834
835
			Jetpack_Heartbeat::init();
836
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
837
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
838
				Jetpack_Search_Performance_Logger::init();
839
			}
840
		}
841
842
		// Initialize remote file upload request handlers.
843
		$this->add_remote_request_handlers();
844
845
		/*
846
		 * Enable enhanced handling of previewing sites in Calypso
847
		 */
848
		if ( self::is_active() ) {
849
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
850
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
851
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
852
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
853
		}
854
855
		if ( ( new Tracking( $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) ) {
0 ignored issues
show
Documentation introduced by
$this->connection_manager is of type object<Automattic\Jetpack\Connection\Manager>, but the function expects a string.

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...
Documentation introduced by
new \Automattic\Jetpack\Terms_Of_Service() is of type object<Automattic\Jetpack\Terms_Of_Service>, but the function expects a object<Automattic\Jetpac...tpack\Terms_Of_Service>.

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...
Documentation introduced by
new \Automattic\Jetpack\Status() is of type object<Automattic\Jetpack\Status>, but the function expects a object<Automattic\Jetpac...omattic\Jetpack\Status>.

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...
856
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
857
		} else {
858
			/**
859
			 * Initialize tracking right after the user agrees to the terms of service.
860
			 */
861
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
862
		}
863
	}
864
865
	/**
866
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
867
	 * initialization code.
868
	 *
869
	 * @action plugins_loaded
870
	 */
871
	public function late_initialization() {
872
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
873
874
		Partner::init();
875
876
		/**
877
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
878
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
879
		 *
880
		 * @since 8.1.0
881
		 *
882
		 * @param Jetpack $jetpack the main plugin class object.
883
		 */
884
		do_action( 'jetpack_loaded', $this );
885
886
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
887
	}
888
889
	/**
890
	 * This is ported over from the manage module, which has been deprecated and baked in here.
891
	 *
892
	 * @param $domains
893
	 */
894
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
895
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
896
	}
897
898
	/**
899
	 * Return $domains, with 'wordpress.com' appended.
900
	 * This is ported over from the manage module, which has been deprecated and baked in here.
901
	 *
902
	 * @param $domains
903
	 * @return array
904
	 */
905
	function allow_wpcom_domain( $domains ) {
906
		if ( empty( $domains ) ) {
907
			$domains = array();
908
		}
909
		$domains[] = 'wordpress.com';
910
		return array_unique( $domains );
911
	}
912
913
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
914
		$post = get_post( $post_id );
915
916
		if ( empty( $post ) ) {
917
			return $default_url;
918
		}
919
920
		$post_type = $post->post_type;
921
922
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
923
		// https://en.support.wordpress.com/custom-post-types/
924
		$allowed_post_types = array(
925
			'post',
926
			'page',
927
			'jetpack-portfolio',
928
			'jetpack-testimonial',
929
		);
930
931
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
932
			return $default_url;
933
		}
934
935
		return Redirect::get_url(
936
			'calypso-edit-' . $post_type,
937
			array(
938
				'path' => $post_id,
939
			)
940
		);
941
	}
942
943
	function point_edit_comment_links_to_calypso( $url ) {
944
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
945
		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...
946
947
		return Redirect::get_url(
948
			'calypso-edit-comment',
949
			array(
950
				'path' => $query_args['amp;c'],
951
			)
952
		);
953
954
	}
955
956
	function jetpack_track_last_sync_callback( $params ) {
957
		/**
958
		 * Filter to turn off jitm caching
959
		 *
960
		 * @since 5.4.0
961
		 *
962
		 * @param bool false Whether to cache just in time messages
963
		 */
964
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
965
			return $params;
966
		}
967
968
		if ( is_array( $params ) && isset( $params[0] ) ) {
969
			$option = $params[0];
970
			if ( 'active_plugins' === $option ) {
971
				// use the cache if we can, but not terribly important if it gets evicted
972
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
973
			}
974
		}
975
976
		return $params;
977
	}
978
979
	function jetpack_connection_banner_callback() {
980
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
981
982
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
983
		if (
984
			isset( $_REQUEST['dismissBanner'] ) &&
985
			! Jetpack_Connection_Banner::force_display()
986
		) {
987
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
988
			wp_send_json_success();
989
		}
990
991
		wp_die();
992
	}
993
994
	/**
995
	 * If there are any stats that need to be pushed, but haven't been, push them now.
996
	 */
997
	function push_stats() {
998
		if ( ! empty( $this->stats ) ) {
999
			$this->do_stats( 'server_side' );
1000
		}
1001
	}
1002
1003
	/**
1004
	 * Sets the Jetpack custom capabilities.
1005
	 *
1006
	 * @param string[] $caps    Array of the user's capabilities.
1007
	 * @param string   $cap     Capability name.
1008
	 * @param int      $user_id The user ID.
1009
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1010
	 */
1011
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1012
		$is_offline_mode = ( new Status() )->is_offline_mode();
1013
		switch ( $cap ) {
1014
			case 'jetpack_manage_modules':
1015
			case 'jetpack_activate_modules':
1016
			case 'jetpack_deactivate_modules':
1017
				$caps = array( 'manage_options' );
1018
				break;
1019
			case 'jetpack_configure_modules':
1020
				$caps = array( 'manage_options' );
1021
				break;
1022
			case 'jetpack_manage_autoupdates':
1023
				$caps = array(
1024
					'manage_options',
1025
					'update_plugins',
1026
				);
1027
				break;
1028
			case 'jetpack_network_admin_page':
1029
			case 'jetpack_network_settings_page':
1030
				$caps = array( 'manage_network_plugins' );
1031
				break;
1032
			case 'jetpack_network_sites_page':
1033
				$caps = array( 'manage_sites' );
1034
				break;
1035
			case 'jetpack_admin_page':
1036
				if ( $is_offline_mode ) {
1037
					$caps = array( 'manage_options' );
1038
					break;
1039
				} else {
1040
					$caps = array( 'read' );
1041
				}
1042
				break;
1043
		}
1044
		return $caps;
1045
	}
1046
1047
	/**
1048
	 * Register assets for use in various modules and the Jetpack admin page.
1049
	 *
1050
	 * @uses wp_script_is, wp_register_script, plugins_url
1051
	 * @action wp_loaded
1052
	 * @return null
1053
	 */
1054
	public function register_assets() {
1055 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1056
			wp_register_script(
1057
				'jetpack-gallery-settings',
1058
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1059
				array( 'media-views' ),
1060
				'20121225'
1061
			);
1062
		}
1063
1064
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1065
			wp_register_script(
1066
				'jetpack-twitter-timeline',
1067
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1068
				array( 'jquery' ),
1069
				'4.0.0',
1070
				true
1071
			);
1072
		}
1073
1074
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1075
			wp_register_script(
1076
				'jetpack-facebook-embed',
1077
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1078
				array(),
1079
				null,
1080
				true
1081
			);
1082
1083
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1084
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1085
			if ( ! is_numeric( $fb_app_id ) ) {
1086
				$fb_app_id = '';
1087
			}
1088
			wp_localize_script(
1089
				'jetpack-facebook-embed',
1090
				'jpfbembed',
1091
				array(
1092
					'appid'  => $fb_app_id,
1093
					'locale' => $this->get_locale(),
1094
				)
1095
			);
1096
		}
1097
1098
		/**
1099
		 * As jetpack_register_genericons is by default fired off a hook,
1100
		 * the hook may have already fired by this point.
1101
		 * So, let's just trigger it manually.
1102
		 */
1103
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1104
		jetpack_register_genericons();
1105
1106
		/**
1107
		 * Register the social logos
1108
		 */
1109
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1110
		jetpack_register_social_logos();
1111
1112 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1113
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1114
		}
1115
	}
1116
1117
	/**
1118
	 * Guess locale from language code.
1119
	 *
1120
	 * @param string $lang Language code.
1121
	 * @return string|bool
1122
	 */
1123 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1124
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1125
			return 'en_US';
1126
		}
1127
1128
		if ( ! class_exists( 'GP_Locales' ) ) {
1129
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1130
				return false;
1131
			}
1132
1133
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1134
		}
1135
1136
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1137
			// WP.com: get_locale() returns 'it'
1138
			$locale = GP_Locales::by_slug( $lang );
1139
		} else {
1140
			// Jetpack: get_locale() returns 'it_IT';
1141
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1142
		}
1143
1144
		if ( ! $locale ) {
1145
			return false;
1146
		}
1147
1148
		if ( empty( $locale->facebook_locale ) ) {
1149
			if ( empty( $locale->wp_locale ) ) {
1150
				return false;
1151
			} else {
1152
				// Facebook SDK is smart enough to fall back to en_US if a
1153
				// locale isn't supported. Since supported Facebook locales
1154
				// can fall out of sync, we'll attempt to use the known
1155
				// wp_locale value and rely on said fallback.
1156
				return $locale->wp_locale;
1157
			}
1158
		}
1159
1160
		return $locale->facebook_locale;
1161
	}
1162
1163
	/**
1164
	 * Get the locale.
1165
	 *
1166
	 * @return string|bool
1167
	 */
1168
	function get_locale() {
1169
		$locale = $this->guess_locale_from_lang( get_locale() );
1170
1171
		if ( ! $locale ) {
1172
			$locale = 'en_US';
1173
		}
1174
1175
		return $locale;
1176
	}
1177
1178
	/**
1179
	 * Return the network_site_url so that .com knows what network this site is a part of.
1180
	 *
1181
	 * @param  bool $option
1182
	 * @return string
1183
	 */
1184
	public function jetpack_main_network_site_option( $option ) {
1185
		return network_site_url();
1186
	}
1187
	/**
1188
	 * Network Name.
1189
	 */
1190
	static function network_name( $option = null ) {
1191
		global $current_site;
1192
		return $current_site->site_name;
1193
	}
1194
	/**
1195
	 * Does the network allow new user and site registrations.
1196
	 *
1197
	 * @return string
1198
	 */
1199
	static function network_allow_new_registrations( $option = null ) {
1200
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1201
	}
1202
	/**
1203
	 * Does the network allow admins to add new users.
1204
	 *
1205
	 * @return boolian
1206
	 */
1207
	static function network_add_new_users( $option = null ) {
1208
		return (bool) get_site_option( 'add_new_users' );
1209
	}
1210
	/**
1211
	 * File upload psace left per site in MB.
1212
	 *  -1 means NO LIMIT.
1213
	 *
1214
	 * @return number
1215
	 */
1216
	static function network_site_upload_space( $option = null ) {
1217
		// value in MB
1218
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1219
	}
1220
1221
	/**
1222
	 * Network allowed file types.
1223
	 *
1224
	 * @return string
1225
	 */
1226
	static function network_upload_file_types( $option = null ) {
1227
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1228
	}
1229
1230
	/**
1231
	 * Maximum file upload size set by the network.
1232
	 *
1233
	 * @return number
1234
	 */
1235
	static function network_max_upload_file_size( $option = null ) {
1236
		// value in KB
1237
		return get_site_option( 'fileupload_maxk', 300 );
1238
	}
1239
1240
	/**
1241
	 * Lets us know if a site allows admins to manage the network.
1242
	 *
1243
	 * @return array
1244
	 */
1245
	static function network_enable_administration_menus( $option = null ) {
1246
		return get_site_option( 'menu_items' );
1247
	}
1248
1249
	/**
1250
	 * If a user has been promoted to or demoted from admin, we need to clear the
1251
	 * jetpack_other_linked_admins transient.
1252
	 *
1253
	 * @since 4.3.2
1254
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1255
	 *
1256
	 * @param int    $user_id   The user ID whose role changed.
1257
	 * @param string $role      The new role.
1258
	 * @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...
1259
	 */
1260
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1261
		if ( 'administrator' == $role
1262
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1263
			|| is_null( $old_roles )
1264
		) {
1265
			delete_transient( 'jetpack_other_linked_admins' );
1266
		}
1267
	}
1268
1269
	/**
1270
	 * Checks to see if there are any other users available to become primary
1271
	 * Users must both:
1272
	 * - Be linked to wpcom
1273
	 * - Be an admin
1274
	 *
1275
	 * @return mixed False if no other users are linked, Int if there are.
1276
	 */
1277
	static function get_other_linked_admins() {
1278
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1279
1280
		if ( false === $other_linked_users ) {
1281
			$admins = get_users( array( 'role' => 'administrator' ) );
1282
			if ( count( $admins ) > 1 ) {
1283
				$available = array();
1284
				foreach ( $admins as $admin ) {
1285
					if ( self::is_user_connected( $admin->ID ) ) {
1286
						$available[] = $admin->ID;
1287
					}
1288
				}
1289
1290
				$count_connected_admins = count( $available );
1291
				if ( count( $available ) > 1 ) {
1292
					$other_linked_users = $count_connected_admins;
1293
				} else {
1294
					$other_linked_users = 0;
1295
				}
1296
			} else {
1297
				$other_linked_users = 0;
1298
			}
1299
1300
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1301
		}
1302
1303
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1304
	}
1305
1306
	/**
1307
	 * Return whether we are dealing with a multi network setup or not.
1308
	 * The reason we are type casting this is because we want to avoid the situation where
1309
	 * the result is false since when is_main_network_option return false it cases
1310
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1311
	 * database which could be set to anything as opposed to what this function returns.
1312
	 *
1313
	 * @param  bool $option
1314
	 *
1315
	 * @return boolean
1316
	 */
1317
	public function is_main_network_option( $option ) {
1318
		// return '1' or ''
1319
		return (string) (bool) self::is_multi_network();
1320
	}
1321
1322
	/**
1323
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1324
	 *
1325
	 * @param  string $option
1326
	 * @return boolean
1327
	 */
1328
	public function is_multisite( $option ) {
1329
		return (string) (bool) is_multisite();
1330
	}
1331
1332
	/**
1333
	 * Implemented since there is no core is multi network function
1334
	 * Right now there is no way to tell if we which network is the dominant network on the system
1335
	 *
1336
	 * @since  3.3
1337
	 * @return boolean
1338
	 */
1339 View Code Duplication
	public static function is_multi_network() {
1340
		global  $wpdb;
1341
1342
		// if we don't have a multi site setup no need to do any more
1343
		if ( ! is_multisite() ) {
1344
			return false;
1345
		}
1346
1347
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1348
		if ( $num_sites > 1 ) {
1349
			return true;
1350
		} else {
1351
			return false;
1352
		}
1353
	}
1354
1355
	/**
1356
	 * Get back if the current site is single user site.
1357
	 *
1358
	 * @return bool
1359
	 */
1360 View Code Duplication
	public static function is_single_user_site() {
1361
		global $wpdb;
1362
1363
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1364
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1365
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1366
		}
1367
		return 1 === (int) $some_users;
1368
	}
1369
1370
	/**
1371
	 * Returns true if the site has file write access false otherwise.
1372
	 *
1373
	 * @return string ( '1' | '0' )
1374
	 **/
1375
	public static function file_system_write_access() {
1376
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1377
			require_once ABSPATH . 'wp-admin/includes/file.php';
1378
		}
1379
1380
		require_once ABSPATH . 'wp-admin/includes/template.php';
1381
1382
		$filesystem_method = get_filesystem_method();
1383
		if ( $filesystem_method === 'direct' ) {
1384
			return 1;
1385
		}
1386
1387
		ob_start();
1388
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1389
		ob_end_clean();
1390
		if ( $filesystem_credentials_are_stored ) {
1391
			return 1;
1392
		}
1393
		return 0;
1394
	}
1395
1396
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1397
	/**
1398
	 * jetpack_updates is saved in the following schema:
1399
	 *
1400
	 * array (
1401
	 *      'plugins'                       => (int) Number of plugin updates available.
1402
	 *      'themes'                        => (int) Number of theme updates available.
1403
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1404
	 *      'translations'                  => (int) Number of translation updates available.
1405
	 *      'total'                         => (int) Total of all available updates.
1406
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1407
	 * )
1408
	 *
1409
	 * @return array
1410
	 */
1411
	public static function get_updates() {
1412
		$update_data = wp_get_update_data();
1413
1414
		// Stores the individual update counts as well as the total count.
1415
		if ( isset( $update_data['counts'] ) ) {
1416
			$updates = $update_data['counts'];
1417
		}
1418
1419
		// If we need to update WordPress core, let's find the latest version number.
1420 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1421
			$cur = get_preferred_from_update_core();
1422
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1423
				$updates['wp_update_version'] = $cur->current;
1424
			}
1425
		}
1426
		return isset( $updates ) ? $updates : array();
1427
	}
1428
	// phpcs:enable
1429
1430
	public static function get_update_details() {
1431
		$update_details = array(
1432
			'update_core'    => get_site_transient( 'update_core' ),
1433
			'update_plugins' => get_site_transient( 'update_plugins' ),
1434
			'update_themes'  => get_site_transient( 'update_themes' ),
1435
		);
1436
		return $update_details;
1437
	}
1438
1439
	/**
1440
	 * Is Jetpack active?
1441
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1442
	 *
1443
	 * @return bool
1444
	 */
1445
	public static function is_active() {
1446
		return self::connection()->is_active();
1447
	}
1448
1449
	/**
1450
	 * Deprecated: Is Jetpack in development (offline) mode?
1451
	 *
1452
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1453
	 * and themes still use it, and we do not want to flood them with notices.
1454
	 *
1455
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1456
	 *
1457
	 * @deprecated since 8.0.
1458
	 */
1459
	public static function is_development_mode() {
1460
		return ( new Status() )->is_offline_mode();
1461
	}
1462
1463
	/**
1464
	 * Whether the site is currently onboarding or not.
1465
	 * A site is considered as being onboarded if it currently has an onboarding token.
1466
	 *
1467
	 * @since 5.8
1468
	 *
1469
	 * @access public
1470
	 * @static
1471
	 *
1472
	 * @return bool True if the site is currently onboarding, false otherwise
1473
	 */
1474
	public static function is_onboarding() {
1475
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1476
	}
1477
1478
	/**
1479
	 * Determines reason for Jetpack offline mode.
1480
	 */
1481
	public static function development_mode_trigger_text() {
1482
		$status = new Status();
1483
1484
		if ( ! $status->is_offline_mode() ) {
1485
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1486
		}
1487
1488
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1489
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1490
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1491
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1492
		} elseif ( $status->is_local_site() ) {
1493
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1494
			/** This filter is documented in packages/status/src/class-status.php */
1495
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1496
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1497
		} else {
1498
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1499
		}
1500
1501
		return $notice;
1502
1503
	}
1504
	/**
1505
	 * Get Jetpack offline mode notice text and notice class.
1506
	 *
1507
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1508
	 */
1509
	public static function show_development_mode_notice() {
1510 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1511
			$notice = sprintf(
1512
				/* translators: %s is a URL */
1513
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1514
				Redirect::get_url( 'jetpack-support-development-mode' )
1515
			);
1516
1517
			$notice .= ' ' . self::development_mode_trigger_text();
1518
1519
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1520
		}
1521
1522
		// Throw up a notice if using a development version and as for feedback.
1523
		if ( self::is_development_version() ) {
1524
			/* translators: %s is a URL */
1525
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), Redirect::get_url( 'jetpack-contact-support-beta-group' ) );
1526
1527
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1528
		}
1529
		// Throw up a notice if using staging mode
1530 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1531
			/* translators: %s is a URL */
1532
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1533
1534
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1535
		}
1536
	}
1537
1538
	/**
1539
	 * Whether Jetpack's version maps to a public release, or a development version.
1540
	 */
1541
	public static function is_development_version() {
1542
		/**
1543
		 * Allows filtering whether this is a development version of Jetpack.
1544
		 *
1545
		 * This filter is especially useful for tests.
1546
		 *
1547
		 * @since 4.3.0
1548
		 *
1549
		 * @param bool $development_version Is this a develoment version of Jetpack?
1550
		 */
1551
		return (bool) apply_filters(
1552
			'jetpack_development_version',
1553
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1554
		);
1555
	}
1556
1557
	/**
1558
	 * Get the wpcom email of the current|specified connected user.
1559
	 */
1560
	public static function get_connected_user_email( $user_id = null ) {
1561
		if ( ! $user_id ) {
1562
			$user_id = get_current_user_id();
1563
		}
1564
1565
		$xml = new Jetpack_IXR_Client(
1566
			array(
1567
				'user_id' => $user_id,
1568
			)
1569
		);
1570
		$xml->query( 'wpcom.getUserEmail' );
1571
		if ( ! $xml->isError() ) {
1572
			return $xml->getResponse();
1573
		}
1574
		return false;
1575
	}
1576
1577
	/**
1578
	 * Get the wpcom email of the master user.
1579
	 */
1580
	public static function get_master_user_email() {
1581
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1582
		if ( $master_user_id ) {
1583
			return self::get_connected_user_email( $master_user_id );
1584
		}
1585
		return '';
1586
	}
1587
1588
	/**
1589
	 * Gets current user IP address.
1590
	 *
1591
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1592
	 *
1593
	 * @return string                  Current user IP address.
1594
	 */
1595
	public static function current_user_ip( $check_all_headers = false ) {
1596
		if ( $check_all_headers ) {
1597
			foreach ( array(
1598
				'HTTP_CF_CONNECTING_IP',
1599
				'HTTP_CLIENT_IP',
1600
				'HTTP_X_FORWARDED_FOR',
1601
				'HTTP_X_FORWARDED',
1602
				'HTTP_X_CLUSTER_CLIENT_IP',
1603
				'HTTP_FORWARDED_FOR',
1604
				'HTTP_FORWARDED',
1605
				'HTTP_VIA',
1606
			) as $key ) {
1607
				if ( ! empty( $_SERVER[ $key ] ) ) {
1608
					return $_SERVER[ $key ];
1609
				}
1610
			}
1611
		}
1612
1613
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1614
	}
1615
1616
	/**
1617
	 * Loads the currently active modules.
1618
	 */
1619
	public static function load_modules() {
1620
		$is_offline_mode = ( new Status() )->is_offline_mode();
1621
		if (
1622
			! self::is_active()
1623
			&& ! $is_offline_mode
1624
			&& ! self::is_onboarding()
1625
			&& (
1626
				! is_multisite()
1627
				|| ! get_site_option( 'jetpack_protect_active' )
1628
			)
1629
		) {
1630
			return;
1631
		}
1632
1633
		$version = Jetpack_Options::get_option( 'version' );
1634 View Code Duplication
		if ( ! $version ) {
1635
			$version = $old_version = JETPACK__VERSION . ':' . time();
1636
			/** This action is documented in class.jetpack.php */
1637
			do_action( 'updating_jetpack_version', $version, false );
1638
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1639
		}
1640
		list( $version ) = explode( ':', $version );
1641
1642
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1643
1644
		$modules_data = array();
1645
1646
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1647
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1648
			$updated_modules = array();
1649
			foreach ( $modules as $module ) {
1650
				$modules_data[ $module ] = self::get_module( $module );
1651
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1652
					continue;
1653
				}
1654
1655
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1656
					continue;
1657
				}
1658
1659
				$updated_modules[] = $module;
1660
			}
1661
1662
			$modules = array_diff( $modules, $updated_modules );
1663
		}
1664
1665
		foreach ( $modules as $index => $module ) {
1666
			// If we're in offline mode, disable modules requiring a connection.
1667
			if ( $is_offline_mode ) {
1668
				// Prime the pump if we need to
1669
				if ( empty( $modules_data[ $module ] ) ) {
1670
					$modules_data[ $module ] = self::get_module( $module );
1671
				}
1672
				// If the module requires a connection, but we're in local mode, don't include it.
1673
				if ( $modules_data[ $module ]['requires_connection'] ) {
1674
					continue;
1675
				}
1676
			}
1677
1678
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1679
				continue;
1680
			}
1681
1682
			if ( ! include_once self::get_module_path( $module ) ) {
1683
				unset( $modules[ $index ] );
1684
				self::update_active_modules( array_values( $modules ) );
1685
				continue;
1686
			}
1687
1688
			/**
1689
			 * Fires when a specific module is loaded.
1690
			 * The dynamic part of the hook, $module, is the module slug.
1691
			 *
1692
			 * @since 1.1.0
1693
			 */
1694
			do_action( 'jetpack_module_loaded_' . $module );
1695
		}
1696
1697
		/**
1698
		 * Fires when all the modules are loaded.
1699
		 *
1700
		 * @since 1.1.0
1701
		 */
1702
		do_action( 'jetpack_modules_loaded' );
1703
1704
		// 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.
1705
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1706
	}
1707
1708
	/**
1709
	 * Check if Jetpack's REST API compat file should be included
1710
	 *
1711
	 * @action plugins_loaded
1712
	 * @return null
1713
	 */
1714
	public function check_rest_api_compat() {
1715
		/**
1716
		 * Filters the list of REST API compat files to be included.
1717
		 *
1718
		 * @since 2.2.5
1719
		 *
1720
		 * @param array $args Array of REST API compat files to include.
1721
		 */
1722
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1723
1724
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1725
			require_once $_jetpack_rest_api_compat_include;
1726
		}
1727
	}
1728
1729
	/**
1730
	 * Gets all plugins currently active in values, regardless of whether they're
1731
	 * traditionally activated or network activated.
1732
	 *
1733
	 * @todo Store the result in core's object cache maybe?
1734
	 */
1735
	public static function get_active_plugins() {
1736
		$active_plugins = (array) get_option( 'active_plugins', array() );
1737
1738
		if ( is_multisite() ) {
1739
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1740
			// whereas active_plugins stores them in the values.
1741
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1742
			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...
1743
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1744
			}
1745
		}
1746
1747
		sort( $active_plugins );
1748
1749
		return array_unique( $active_plugins );
1750
	}
1751
1752
	/**
1753
	 * Gets and parses additional plugin data to send with the heartbeat data
1754
	 *
1755
	 * @since 3.8.1
1756
	 *
1757
	 * @return array Array of plugin data
1758
	 */
1759
	public static function get_parsed_plugin_data() {
1760
		if ( ! function_exists( 'get_plugins' ) ) {
1761
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
1762
		}
1763
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1764
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1765
		$active_plugins = self::get_active_plugins();
1766
1767
		$plugins = array();
1768
		foreach ( $all_plugins as $path => $plugin_data ) {
1769
			$plugins[ $path ] = array(
1770
				'is_active' => in_array( $path, $active_plugins ),
1771
				'file'      => $path,
1772
				'name'      => $plugin_data['Name'],
1773
				'version'   => $plugin_data['Version'],
1774
				'author'    => $plugin_data['Author'],
1775
			);
1776
		}
1777
1778
		return $plugins;
1779
	}
1780
1781
	/**
1782
	 * Gets and parses theme data to send with the heartbeat data
1783
	 *
1784
	 * @since 3.8.1
1785
	 *
1786
	 * @return array Array of theme data
1787
	 */
1788
	public static function get_parsed_theme_data() {
1789
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
1790
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1791
1792
		$themes = array();
1793
		foreach ( $all_themes as $slug => $theme_data ) {
1794
			$theme_headers = array();
1795
			foreach ( $header_keys as $header_key ) {
1796
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1797
			}
1798
1799
			$themes[ $slug ] = array(
1800
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
1801
				'slug'            => $slug,
1802
				'theme_root'      => $theme_data->get_theme_root_uri(),
1803
				'parent'          => $theme_data->parent(),
1804
				'headers'         => $theme_headers,
1805
			);
1806
		}
1807
1808
		return $themes;
1809
	}
1810
1811
	/**
1812
	 * Checks whether a specific plugin is active.
1813
	 *
1814
	 * We don't want to store these in a static variable, in case
1815
	 * there are switch_to_blog() calls involved.
1816
	 */
1817
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1818
		return in_array( $plugin, self::get_active_plugins() );
1819
	}
1820
1821
	/**
1822
	 * Check if Jetpack's Open Graph tags should be used.
1823
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1824
	 *
1825
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1826
	 * @action plugins_loaded
1827
	 * @return null
1828
	 */
1829
	public function check_open_graph() {
1830
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
1831
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1832
		}
1833
1834
		$active_plugins = self::get_active_plugins();
1835
1836
		if ( ! empty( $active_plugins ) ) {
1837
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1838
				if ( in_array( $plugin, $active_plugins ) ) {
1839
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1840
					break;
1841
				}
1842
			}
1843
		}
1844
1845
		/**
1846
		 * Allow the addition of Open Graph Meta Tags to all pages.
1847
		 *
1848
		 * @since 2.0.3
1849
		 *
1850
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1851
		 */
1852
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1853
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1854
		}
1855
	}
1856
1857
	/**
1858
	 * Check if Jetpack's Twitter tags should be used.
1859
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1860
	 *
1861
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1862
	 * @action plugins_loaded
1863
	 * @return null
1864
	 */
1865
	public function check_twitter_tags() {
1866
1867
		$active_plugins = self::get_active_plugins();
1868
1869
		if ( ! empty( $active_plugins ) ) {
1870
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1871
				if ( in_array( $plugin, $active_plugins ) ) {
1872
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1873
					break;
1874
				}
1875
			}
1876
		}
1877
1878
		/**
1879
		 * Allow Twitter Card Meta tags to be disabled.
1880
		 *
1881
		 * @since 2.6.0
1882
		 *
1883
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1884
		 */
1885
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1886
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1887
		}
1888
	}
1889
1890
	/* Jetpack Options API */
1891
1892
	public static function get_option_names( $type = 'compact' ) {
1893
		return Jetpack_Options::get_option_names( $type );
1894
	}
1895
1896
	/**
1897
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1898
	 *
1899
	 * @param string $name    Option name
1900
	 * @param mixed  $default (optional)
1901
	 */
1902
	public static function get_option( $name, $default = false ) {
1903
		return Jetpack_Options::get_option( $name, $default );
1904
	}
1905
1906
	/**
1907
	 * Returns an array of all PHP files in the specified absolute path.
1908
	 * Equivalent to glob( "$absolute_path/*.php" ).
1909
	 *
1910
	 * @param string $absolute_path The absolute path of the directory to search.
1911
	 * @return array Array of absolute paths to the PHP files.
1912
	 */
1913
	public static function glob_php( $absolute_path ) {
1914
		if ( function_exists( 'glob' ) ) {
1915
			return glob( "$absolute_path/*.php" );
1916
		}
1917
1918
		$absolute_path = untrailingslashit( $absolute_path );
1919
		$files         = array();
1920
		if ( ! $dir = @opendir( $absolute_path ) ) {
1921
			return $files;
1922
		}
1923
1924
		while ( false !== $file = readdir( $dir ) ) {
1925
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1926
				continue;
1927
			}
1928
1929
			$file = "$absolute_path/$file";
1930
1931
			if ( ! is_file( $file ) ) {
1932
				continue;
1933
			}
1934
1935
			$files[] = $file;
1936
		}
1937
1938
		closedir( $dir );
1939
1940
		return $files;
1941
	}
1942
1943
	public static function activate_new_modules( $redirect = false ) {
1944
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
1945
			return;
1946
		}
1947
1948
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1949 View Code Duplication
		if ( ! $jetpack_old_version ) {
1950
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1951
			/** This action is documented in class.jetpack.php */
1952
			do_action( 'updating_jetpack_version', $version, false );
1953
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1954
		}
1955
1956
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1957
1958
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1959
			return;
1960
		}
1961
1962
		$active_modules     = self::get_active_modules();
1963
		$reactivate_modules = array();
1964
		foreach ( $active_modules as $active_module ) {
1965
			$module = self::get_module( $active_module );
1966
			if ( ! isset( $module['changed'] ) ) {
1967
				continue;
1968
			}
1969
1970
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1971
				continue;
1972
			}
1973
1974
			$reactivate_modules[] = $active_module;
1975
			self::deactivate_module( $active_module );
1976
		}
1977
1978
		$new_version = JETPACK__VERSION . ':' . time();
1979
		/** This action is documented in class.jetpack.php */
1980
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1981
		Jetpack_Options::update_options(
1982
			array(
1983
				'version'     => $new_version,
1984
				'old_version' => $jetpack_old_version,
1985
			)
1986
		);
1987
1988
		self::state( 'message', 'modules_activated' );
1989
1990
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
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...
1991
1992
		if ( $redirect ) {
1993
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
1994
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
1995
				$page = $_GET['page'];
1996
			}
1997
1998
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
1999
			exit;
2000
		}
2001
	}
2002
2003
	/**
2004
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2005
	 * Make sure to tuck away module "library" files in a sub-directory.
2006
	 */
2007
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2008
		static $modules = null;
2009
2010
		if ( ! isset( $modules ) ) {
2011
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2012
			// Use the cache if we're on the front-end and it's available...
2013
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2014
				$modules = $available_modules_option[ JETPACK__VERSION ];
2015
			} else {
2016
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2017
2018
				$modules = array();
2019
2020
				foreach ( $files as $file ) {
2021
					if ( ! $headers = self::get_module( $file ) ) {
2022
						continue;
2023
					}
2024
2025
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2026
				}
2027
2028
				Jetpack_Options::update_option(
2029
					'available_modules',
2030
					array(
2031
						JETPACK__VERSION => $modules,
2032
					)
2033
				);
2034
			}
2035
		}
2036
2037
		/**
2038
		 * Filters the array of modules available to be activated.
2039
		 *
2040
		 * @since 2.4.0
2041
		 *
2042
		 * @param array $modules Array of available modules.
2043
		 * @param string $min_version Minimum version number required to use modules.
2044
		 * @param string $max_version Maximum version number required to use modules.
2045
		 */
2046
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2047
2048
		if ( ! $min_version && ! $max_version ) {
2049
			return array_keys( $mods );
2050
		}
2051
2052
		$r = array();
2053
		foreach ( $mods as $slug => $introduced ) {
2054
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2055
				continue;
2056
			}
2057
2058
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2059
				continue;
2060
			}
2061
2062
			$r[] = $slug;
2063
		}
2064
2065
		return $r;
2066
	}
2067
2068
	/**
2069
	 * Default modules loaded on activation.
2070
	 */
2071
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2072
		$return = array();
2073
2074
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2075
			$module_data = self::get_module( $module );
2076
2077
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2078
				case 'yes':
2079
					$return[] = $module;
2080
					break;
2081
				case 'public':
2082
					if ( Jetpack_Options::get_option( 'public' ) ) {
2083
						$return[] = $module;
2084
					}
2085
					break;
2086
				case 'no':
2087
				default:
2088
					break;
2089
			}
2090
		}
2091
		/**
2092
		 * Filters the array of default modules.
2093
		 *
2094
		 * @since 2.5.0
2095
		 *
2096
		 * @param array $return Array of default modules.
2097
		 * @param string $min_version Minimum version number required to use modules.
2098
		 * @param string $max_version Maximum version number required to use modules.
2099
		 */
2100
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2101
	}
2102
2103
	/**
2104
	 * Checks activated modules during auto-activation to determine
2105
	 * if any of those modules are being deprecated.  If so, close
2106
	 * them out, and add any replacement modules.
2107
	 *
2108
	 * Runs at priority 99 by default.
2109
	 *
2110
	 * This is run late, so that it can still activate a module if
2111
	 * the new module is a replacement for another that the user
2112
	 * currently has active, even if something at the normal priority
2113
	 * would kibosh everything.
2114
	 *
2115
	 * @since 2.6
2116
	 * @uses jetpack_get_default_modules filter
2117
	 * @param array $modules
2118
	 * @return array
2119
	 */
2120
	function handle_deprecated_modules( $modules ) {
2121
		$deprecated_modules = array(
2122
			'debug'            => null,  // Closed out and moved to the debugger library.
2123
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2124
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2125
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2126
		);
2127
2128
		// Don't activate SSO if they never completed activating WPCC.
2129
		if ( self::is_module_active( 'wpcc' ) ) {
2130
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2131
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2132
				$deprecated_modules['wpcc'] = null;
2133
			}
2134
		}
2135
2136
		foreach ( $deprecated_modules as $module => $replacement ) {
2137
			if ( self::is_module_active( $module ) ) {
2138
				self::deactivate_module( $module );
2139
				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...
2140
					$modules[] = $replacement;
2141
				}
2142
			}
2143
		}
2144
2145
		return array_unique( $modules );
2146
	}
2147
2148
	/**
2149
	 * Checks activated plugins during auto-activation to determine
2150
	 * if any of those plugins are in the list with a corresponding module
2151
	 * that is not compatible with the plugin. The module will not be allowed
2152
	 * to auto-activate.
2153
	 *
2154
	 * @since 2.6
2155
	 * @uses jetpack_get_default_modules filter
2156
	 * @param array $modules
2157
	 * @return array
2158
	 */
2159
	function filter_default_modules( $modules ) {
2160
2161
		$active_plugins = self::get_active_plugins();
2162
2163
		if ( ! empty( $active_plugins ) ) {
2164
2165
			// For each module we'd like to auto-activate...
2166
			foreach ( $modules as $key => $module ) {
2167
				// If there are potential conflicts for it...
2168
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2169
					// For each potential conflict...
2170
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2171
						// If that conflicting plugin is active...
2172
						if ( in_array( $plugin, $active_plugins ) ) {
2173
							// Remove that item from being auto-activated.
2174
							unset( $modules[ $key ] );
2175
						}
2176
					}
2177
				}
2178
			}
2179
		}
2180
2181
		return $modules;
2182
	}
2183
2184
	/**
2185
	 * Extract a module's slug from its full path.
2186
	 */
2187
	public static function get_module_slug( $file ) {
2188
		return str_replace( '.php', '', basename( $file ) );
2189
	}
2190
2191
	/**
2192
	 * Generate a module's path from its slug.
2193
	 */
2194
	public static function get_module_path( $slug ) {
2195
		/**
2196
		 * Filters the path of a modules.
2197
		 *
2198
		 * @since 7.4.0
2199
		 *
2200
		 * @param array $return The absolute path to a module's root php file
2201
		 * @param string $slug The module slug
2202
		 */
2203
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $slug.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2204
	}
2205
2206
	/**
2207
	 * Load module data from module file. Headers differ from WordPress
2208
	 * plugin headers to avoid them being identified as standalone
2209
	 * plugins on the WordPress plugins page.
2210
	 */
2211
	public static function get_module( $module ) {
2212
		$headers = array(
2213
			'name'                      => 'Module Name',
2214
			'description'               => 'Module Description',
2215
			'sort'                      => 'Sort Order',
2216
			'recommendation_order'      => 'Recommendation Order',
2217
			'introduced'                => 'First Introduced',
2218
			'changed'                   => 'Major Changes In',
2219
			'deactivate'                => 'Deactivate',
2220
			'free'                      => 'Free',
2221
			'requires_connection'       => 'Requires Connection',
2222
			'auto_activate'             => 'Auto Activate',
2223
			'module_tags'               => 'Module Tags',
2224
			'feature'                   => 'Feature',
2225
			'additional_search_queries' => 'Additional Search Queries',
2226
			'plan_classes'              => 'Plans',
2227
		);
2228
2229
		$file = self::get_module_path( self::get_module_slug( $module ) );
2230
2231
		$mod = self::get_file_data( $file, $headers );
2232
		if ( empty( $mod['name'] ) ) {
2233
			return false;
2234
		}
2235
2236
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2237
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2238
		$mod['deactivate']           = empty( $mod['deactivate'] );
2239
		$mod['free']                 = empty( $mod['free'] );
2240
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2241
2242
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2243
			$mod['auto_activate'] = 'No';
2244
		} else {
2245
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2246
		}
2247
2248
		if ( $mod['module_tags'] ) {
2249
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2250
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2251
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2252
		} else {
2253
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2254
		}
2255
2256 View Code Duplication
		if ( $mod['plan_classes'] ) {
2257
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2258
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2259
		} else {
2260
			$mod['plan_classes'] = array( 'free' );
2261
		}
2262
2263 View Code Duplication
		if ( $mod['feature'] ) {
2264
			$mod['feature'] = explode( ',', $mod['feature'] );
2265
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2266
		} else {
2267
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2268
		}
2269
2270
		/**
2271
		 * Filters the feature array on a module.
2272
		 *
2273
		 * This filter allows you to control where each module is filtered: Recommended,
2274
		 * and the default "Other" listing.
2275
		 *
2276
		 * @since 3.5.0
2277
		 *
2278
		 * @param array   $mod['feature'] The areas to feature this module:
2279
		 *     'Recommended' shows on the main Jetpack admin screen.
2280
		 *     'Other' should be the default if no other value is in the array.
2281
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2282
		 * @param array   $mod All the currently assembled module data.
2283
		 */
2284
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2285
2286
		/**
2287
		 * Filter the returned data about a module.
2288
		 *
2289
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2290
		 * so please be careful.
2291
		 *
2292
		 * @since 3.6.0
2293
		 *
2294
		 * @param array   $mod    The details of the requested module.
2295
		 * @param string  $module The slug of the module, e.g. sharedaddy
2296
		 * @param string  $file   The path to the module source file.
2297
		 */
2298
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2299
	}
2300
2301
	/**
2302
	 * Like core's get_file_data implementation, but caches the result.
2303
	 */
2304
	public static function get_file_data( $file, $headers ) {
2305
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2306
		$file_name = basename( $file );
2307
2308
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2309
2310
		$file_data_option = get_transient( $cache_key );
2311
2312
		if ( ! is_array( $file_data_option ) ) {
2313
			delete_transient( $cache_key );
2314
			$file_data_option = false;
2315
		}
2316
2317
		if ( false === $file_data_option ) {
2318
			$file_data_option = array();
2319
		}
2320
2321
		$key           = md5( $file_name . serialize( $headers ) );
2322
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2323
2324
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2325
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2326
			return $file_data_option[ $key ];
2327
		}
2328
2329
		$data = get_file_data( $file, $headers );
2330
2331
		$file_data_option[ $key ] = $data;
2332
2333
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2334
2335
		return $data;
2336
	}
2337
2338
	/**
2339
	 * Return translated module tag.
2340
	 *
2341
	 * @param string $tag Tag as it appears in each module heading.
2342
	 *
2343
	 * @return mixed
2344
	 */
2345
	public static function translate_module_tag( $tag ) {
2346
		return jetpack_get_module_i18n_tag( $tag );
2347
	}
2348
2349
	/**
2350
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2351
	 *
2352
	 * @since 3.9.2
2353
	 *
2354
	 * @param array $modules
2355
	 *
2356
	 * @return string|void
2357
	 */
2358
	public static function get_translated_modules( $modules ) {
2359
		foreach ( $modules as $index => $module ) {
2360
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2361
			if ( isset( $module['name'] ) ) {
2362
				$modules[ $index ]['name'] = $i18n_module['name'];
2363
			}
2364
			if ( isset( $module['description'] ) ) {
2365
				$modules[ $index ]['description']       = $i18n_module['description'];
2366
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2367
			}
2368
		}
2369
		return $modules;
2370
	}
2371
2372
	/**
2373
	 * Get a list of activated modules as an array of module slugs.
2374
	 */
2375
	public static function get_active_modules() {
2376
		$active = Jetpack_Options::get_option( 'active_modules' );
2377
2378
		if ( ! is_array( $active ) ) {
2379
			$active = array();
2380
		}
2381
2382
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2383
			$active[] = 'vaultpress';
2384
		} else {
2385
			$active = array_diff( $active, array( 'vaultpress' ) );
2386
		}
2387
2388
		// If protect is active on the main site of a multisite, it should be active on all sites.
2389
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2390
			$active[] = 'protect';
2391
		}
2392
2393
		/**
2394
		 * Allow filtering of the active modules.
2395
		 *
2396
		 * Gives theme and plugin developers the power to alter the modules that
2397
		 * are activated on the fly.
2398
		 *
2399
		 * @since 5.8.0
2400
		 *
2401
		 * @param array $active Array of active module slugs.
2402
		 */
2403
		$active = apply_filters( 'jetpack_active_modules', $active );
2404
2405
		return array_unique( $active );
2406
	}
2407
2408
	/**
2409
	 * Check whether or not a Jetpack module is active.
2410
	 *
2411
	 * @param string $module The slug of a Jetpack module.
2412
	 * @return bool
2413
	 *
2414
	 * @static
2415
	 */
2416
	public static function is_module_active( $module ) {
2417
		return in_array( $module, self::get_active_modules() );
2418
	}
2419
2420
	public static function is_module( $module ) {
2421
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2422
	}
2423
2424
	/**
2425
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2426
	 *
2427
	 * @param bool $catch True to start catching, False to stop.
2428
	 *
2429
	 * @static
2430
	 */
2431
	public static function catch_errors( $catch ) {
2432
		static $display_errors, $error_reporting;
2433
2434
		if ( $catch ) {
2435
			$display_errors  = @ini_set( 'display_errors', 1 );
2436
			$error_reporting = @error_reporting( E_ALL );
2437
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2438
		} else {
2439
			@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...
2440
			@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...
2441
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2442
		}
2443
	}
2444
2445
	/**
2446
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2447
	 */
2448
	public static function catch_errors_on_shutdown() {
2449
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2450
	}
2451
2452
	/**
2453
	 * Rewrite any string to make paths easier to read.
2454
	 *
2455
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2456
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2457
	 *
2458
	 * @param $string
2459
	 * @return mixed
2460
	 */
2461
	public static function alias_directories( $string ) {
2462
		// ABSPATH has a trailing slash.
2463
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2464
		// WP_CONTENT_DIR does not have a trailing slash.
2465
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2466
2467
		return $string;
2468
	}
2469
2470
	public static function activate_default_modules(
2471
		$min_version = false,
2472
		$max_version = false,
2473
		$other_modules = array(),
2474
		$redirect = null,
2475
		$send_state_messages = null
2476
	) {
2477
		$jetpack = self::init();
2478
2479
		if ( is_null( $redirect ) ) {
2480
			if (
2481
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2482
			||
2483
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2484
			||
2485
				( defined( 'WP_CLI' ) && WP_CLI )
2486
			||
2487
				( defined( 'DOING_CRON' ) && DOING_CRON )
2488
			||
2489
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2490
			) {
2491
				$redirect = false;
2492
			} elseif ( is_admin() ) {
2493
				$redirect = true;
2494
			} else {
2495
				$redirect = false;
2496
			}
2497
		}
2498
2499
		if ( is_null( $send_state_messages ) ) {
2500
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2501
		}
2502
2503
		$modules = self::get_default_modules( $min_version, $max_version );
2504
		$modules = array_merge( $other_modules, $modules );
2505
2506
		// Look for standalone plugins and disable if active.
2507
2508
		$to_deactivate = array();
2509
		foreach ( $modules as $module ) {
2510
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2511
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2512
			}
2513
		}
2514
2515
		$deactivated = array();
2516
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2517
			list( $probable_file, $probable_title ) = $deactivate_me;
2518
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2519
				$deactivated[] = $module;
2520
			}
2521
		}
2522
2523
		if ( $deactivated ) {
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...
2524
			if ( $send_state_messages ) {
2525
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2526
			}
2527
2528
			if ( $redirect ) {
2529
				$url = add_query_arg(
2530
					array(
2531
						'action'   => 'activate_default_modules',
2532
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2533
					),
2534
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2535
				);
2536
				wp_safe_redirect( $url );
2537
				exit;
2538
			}
2539
		}
2540
2541
		/**
2542
		 * Fires before default modules are activated.
2543
		 *
2544
		 * @since 1.9.0
2545
		 *
2546
		 * @param string $min_version Minimum version number required to use modules.
2547
		 * @param string $max_version Maximum version number required to use modules.
2548
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2549
		 */
2550
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2551
2552
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2553
		if ( $send_state_messages ) {
2554
			self::restate();
2555
			self::catch_errors( true );
2556
		}
2557
2558
		$active = self::get_active_modules();
2559
2560
		foreach ( $modules as $module ) {
2561
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2562
				$active[] = $module;
2563
				self::update_active_modules( $active );
2564
				continue;
2565
			}
2566
2567
			if ( $send_state_messages && in_array( $module, $active ) ) {
2568
				$module_info = self::get_module( $module );
2569 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2570
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2571
					if ( $active_state = self::state( $state ) ) {
2572
						$active_state = explode( ',', $active_state );
2573
					} else {
2574
						$active_state = array();
2575
					}
2576
					$active_state[] = $module;
2577
					self::state( $state, implode( ',', $active_state ) );
2578
				}
2579
				continue;
2580
			}
2581
2582
			$file = self::get_module_path( $module );
2583
			if ( ! file_exists( $file ) ) {
2584
				continue;
2585
			}
2586
2587
			// we'll override this later if the plugin can be included without fatal error
2588
			if ( $redirect ) {
2589
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2590
			}
2591
2592
			if ( $send_state_messages ) {
2593
				self::state( 'error', 'module_activation_failed' );
2594
				self::state( 'module', $module );
2595
			}
2596
2597
			ob_start();
2598
			require_once $file;
2599
2600
			$active[] = $module;
2601
2602 View Code Duplication
			if ( $send_state_messages ) {
2603
2604
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2605
				if ( $active_state = self::state( $state ) ) {
2606
					$active_state = explode( ',', $active_state );
2607
				} else {
2608
					$active_state = array();
2609
				}
2610
				$active_state[] = $module;
2611
				self::state( $state, implode( ',', $active_state ) );
2612
			}
2613
2614
			self::update_active_modules( $active );
2615
2616
			ob_end_clean();
2617
		}
2618
2619
		if ( $send_state_messages ) {
2620
			self::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...
2621
			self::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...
2622
		}
2623
2624
		self::catch_errors( false );
2625
		/**
2626
		 * Fires when default modules are activated.
2627
		 *
2628
		 * @since 1.9.0
2629
		 *
2630
		 * @param string $min_version Minimum version number required to use modules.
2631
		 * @param string $max_version Maximum version number required to use modules.
2632
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2633
		 */
2634
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2635
	}
2636
2637
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2638
		/**
2639
		 * Fires before a module is activated.
2640
		 *
2641
		 * @since 2.6.0
2642
		 *
2643
		 * @param string $module Module slug.
2644
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2645
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2646
		 */
2647
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2648
2649
		$jetpack = self::init();
2650
2651
		if ( ! strlen( $module ) ) {
2652
			return false;
2653
		}
2654
2655
		if ( ! self::is_module( $module ) ) {
2656
			return false;
2657
		}
2658
2659
		// If it's already active, then don't do it again
2660
		$active = self::get_active_modules();
2661
		foreach ( $active as $act ) {
2662
			if ( $act == $module ) {
2663
				return true;
2664
			}
2665
		}
2666
2667
		$module_data = self::get_module( $module );
2668
2669
		$is_offline_mode = ( new Status() )->is_offline_mode();
2670
		if ( ! self::is_active() ) {
2671
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
2672
				return false;
2673
			}
2674
2675
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
2676
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
2677
				return false;
2678
			}
2679
		}
2680
2681
		// Check and see if the old plugin is active
2682
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2683
			// Deactivate the old plugin
2684
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2685
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2686
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2687
				self::state( 'deactivated_plugins', $module );
2688
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2689
				exit;
2690
			}
2691
		}
2692
2693
		// Protect won't work with mis-configured IPs
2694
		if ( 'protect' === $module ) {
2695
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2696
			if ( ! jetpack_protect_get_ip() ) {
2697
				self::state( 'message', 'protect_misconfigured_ip' );
2698
				return false;
2699
			}
2700
		}
2701
2702
		if ( ! Jetpack_Plan::supports( $module ) ) {
2703
			return false;
2704
		}
2705
2706
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2707
		self::state( 'module', $module );
2708
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2709
2710
		self::catch_errors( true );
2711
		ob_start();
2712
		require self::get_module_path( $module );
2713
		/** This action is documented in class.jetpack.php */
2714
		do_action( 'jetpack_activate_module', $module );
2715
		$active[] = $module;
2716
		self::update_active_modules( $active );
2717
2718
		self::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...
2719
		ob_end_clean();
2720
		self::catch_errors( false );
2721
2722
		if ( $redirect ) {
2723
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2724
		}
2725
		if ( $exit ) {
2726
			exit;
2727
		}
2728
		return true;
2729
	}
2730
2731
	public static function deactivate_module( $module ) {
2732
		/**
2733
		 * Fires when a module is deactivated.
2734
		 *
2735
		 * @since 1.9.0
2736
		 *
2737
		 * @param string $module Module slug.
2738
		 */
2739
		do_action( 'jetpack_pre_deactivate_module', $module );
2740
2741
		$jetpack = self::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...
2742
2743
		$active = self::get_active_modules();
2744
		$new    = array_filter( array_diff( $active, (array) $module ) );
2745
2746
		return self::update_active_modules( $new );
2747
	}
2748
2749
	public static function enable_module_configurable( $module ) {
2750
		$module = self::get_module_slug( $module );
2751
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2752
	}
2753
2754
	/**
2755
	 * Composes a module configure URL. It uses Jetpack settings search as default value
2756
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
2757
	 *
2758
	 * @param string $module Module slug
2759
	 * @return string $url module configuration URL
2760
	 */
2761
	public static function module_configuration_url( $module ) {
2762
		$module      = self::get_module_slug( $module );
2763
		$default_url = self::admin_url() . "#/settings?term=$module";
2764
		/**
2765
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
2766
		 *
2767
		 * @since 6.9.0
2768
		 *
2769
		 * @param string $default_url Default url, which redirects to jetpack settings page.
2770
		 */
2771
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
2772
2773
		return $url;
2774
	}
2775
2776
	/* Installation */
2777
	public static function bail_on_activation( $message, $deactivate = true ) {
2778
		?>
2779
<!doctype html>
2780
<html>
2781
<head>
2782
<meta charset="<?php bloginfo( 'charset' ); ?>">
2783
<style>
2784
* {
2785
	text-align: center;
2786
	margin: 0;
2787
	padding: 0;
2788
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2789
}
2790
p {
2791
	margin-top: 1em;
2792
	font-size: 18px;
2793
}
2794
</style>
2795
<body>
2796
<p><?php echo esc_html( $message ); ?></p>
2797
</body>
2798
</html>
2799
		<?php
2800
		if ( $deactivate ) {
2801
			$plugins = get_option( 'active_plugins' );
2802
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2803
			$update  = false;
2804
			foreach ( $plugins as $i => $plugin ) {
2805
				if ( $plugin === $jetpack ) {
2806
					$plugins[ $i ] = false;
2807
					$update        = true;
2808
				}
2809
			}
2810
2811
			if ( $update ) {
2812
				update_option( 'active_plugins', array_filter( $plugins ) );
2813
			}
2814
		}
2815
		exit;
2816
	}
2817
2818
	/**
2819
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2820
	 *
2821
	 * @static
2822
	 */
2823
	public static function plugin_activation( $network_wide ) {
2824
		Jetpack_Options::update_option( 'activated', 1 );
2825
2826
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2827
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2828
		}
2829
2830
		if ( $network_wide ) {
2831
			self::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...
2832
		}
2833
2834
		// For firing one-off events (notices) immediately after activation
2835
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
2836
2837
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
2838
2839
		Health::on_jetpack_activated();
2840
2841
		self::plugin_initialize();
2842
	}
2843
2844
	public static function get_activation_source( $referer_url ) {
2845
2846
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
2847
			return array( 'wp-cli', null );
2848
		}
2849
2850
		$referer = wp_parse_url( $referer_url );
2851
2852
		$source_type  = 'unknown';
2853
		$source_query = null;
2854
2855
		if ( ! is_array( $referer ) ) {
2856
			return array( $source_type, $source_query );
2857
		}
2858
2859
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
2860
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
2861
2862
		if ( isset( $referer['query'] ) ) {
2863
			parse_str( $referer['query'], $query_parts );
2864
		} else {
2865
			$query_parts = array();
2866
		}
2867
2868
		if ( $plugins_path === $referer['path'] ) {
2869
			$source_type = 'list';
2870
		} elseif ( $plugins_install_path === $referer['path'] ) {
2871
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
2872
			switch ( $tab ) {
2873
				case 'popular':
2874
					$source_type = 'popular';
2875
					break;
2876
				case 'recommended':
2877
					$source_type = 'recommended';
2878
					break;
2879
				case 'favorites':
2880
					$source_type = 'favorites';
2881
					break;
2882
				case 'search':
2883
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
2884
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
2885
					break;
2886
				default:
2887
					$source_type = 'featured';
2888
			}
2889
		}
2890
2891
		return array( $source_type, $source_query );
2892
	}
2893
2894
	/**
2895
	 * Runs before bumping version numbers up to a new version
2896
	 *
2897
	 * @param string $version    Version:timestamp.
2898
	 * @param string $old_version Old Version:timestamp or false if not set yet.
2899
	 */
2900
	public static function do_version_bump( $version, $old_version ) {
2901
		if ( $old_version ) { // For existing Jetpack installations.
2902
2903
			// If a front end page is visited after the update, the 'wp' action will fire.
2904
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
2905
2906
			// If an admin page is visited after the update, the 'current_screen' action will fire.
2907
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
2908
		}
2909
	}
2910
2911
	/**
2912
	 * Sets the display_update_modal state.
2913
	 */
2914
	public static function set_update_modal_display() {
2915
		self::state( 'display_update_modal', 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...
2916
	}
2917
2918
	/**
2919
	 * Sets the internal version number and activation state.
2920
	 *
2921
	 * @static
2922
	 */
2923
	public static function plugin_initialize() {
2924
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2925
			Jetpack_Options::update_option( 'activated', 2 );
2926
		}
2927
2928 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2929
			$version = $old_version = JETPACK__VERSION . ':' . time();
2930
			/** This action is documented in class.jetpack.php */
2931
			do_action( 'updating_jetpack_version', $version, false );
2932
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2933
		}
2934
2935
		self::load_modules();
2936
2937
		Jetpack_Options::delete_option( 'do_activate' );
2938
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
2939
	}
2940
2941
	/**
2942
	 * Removes all connection options
2943
	 *
2944
	 * @static
2945
	 */
2946
	public static function plugin_deactivation() {
2947
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
2948
		$tracking = new Tracking();
2949
		$tracking->record_user_event( 'deactivate_plugin', array() );
2950
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2951
			Jetpack_Network::init()->deactivate();
2952
		} else {
2953
			self::disconnect( false );
2954
			// Jetpack_Heartbeat::init()->deactivate();
2955
		}
2956
	}
2957
2958
	/**
2959
	 * Disconnects from the Jetpack servers.
2960
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2961
	 *
2962
	 * @static
2963
	 */
2964
	public static function disconnect( $update_activated_state = true ) {
2965
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2966
2967
		$connection = self::connection();
2968
		$connection->clean_nonces( true );
2969
2970
		// If the site is in an IDC because sync is not allowed,
2971
		// let's make sure to not disconnect the production site.
2972
		if ( ! self::validate_sync_error_idc_option() ) {
2973
			$tracking = new Tracking();
2974
			$tracking->record_user_event( 'disconnect_site', array() );
2975
2976
			$connection->disconnect_site_wpcom( true );
2977
		}
2978
2979
		$connection->delete_all_connection_tokens( true );
2980
		Jetpack_IDC::clear_all_idc_options();
2981
2982
		if ( $update_activated_state ) {
2983
			Jetpack_Options::update_option( 'activated', 4 );
2984
		}
2985
2986
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2987
			// Check then record unique disconnection if site has never been disconnected previously
2988
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2989
				$jetpack_unique_connection['disconnected'] = 1;
2990
			} else {
2991
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2992
					// track unique disconnect
2993
					$jetpack = self::init();
2994
2995
					$jetpack->stat( 'connections', 'unique-disconnect' );
2996
					$jetpack->do_stats( 'server_side' );
2997
				}
2998
				// increment number of times disconnected
2999
				$jetpack_unique_connection['disconnected'] += 1;
3000
			}
3001
3002
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3003
		}
3004
3005
		// Delete all the sync related data. Since it could be taking up space.
3006
		Sender::get_instance()->uninstall();
3007
3008
	}
3009
3010
	/**
3011
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3012
	 */
3013
	public static function try_registration() {
3014
		$terms_of_service = new Terms_Of_Service();
3015
		// The user has agreed to the TOS at some point by now.
3016
		$terms_of_service->agree();
3017
3018
		// Let's get some testing in beta versions and such.
3019
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3020
			// Before attempting to connect, let's make sure that the domains are viable.
3021
			$domains_to_check = array_unique(
3022
				array(
3023
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3024
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3025
				)
3026
			);
3027
			foreach ( $domains_to_check as $domain ) {
3028
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3027 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...
3029
				if ( is_wp_error( $result ) ) {
3030
					return $result;
3031
				}
3032
			}
3033
		}
3034
3035
		$result = self::register();
3036
3037
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3038
		if ( ! $result || is_wp_error( $result ) ) {
3039
			return $result;
3040
		} else {
3041
			return true;
3042
		}
3043
	}
3044
3045
	/**
3046
	 * Tracking an internal event log. Try not to put too much chaff in here.
3047
	 *
3048
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3049
	 */
3050
	public static function log( $code, $data = null ) {
3051
		// only grab the latest 200 entries
3052
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3053
3054
		// Append our event to the log
3055
		$log_entry = array(
3056
			'time'    => time(),
3057
			'user_id' => get_current_user_id(),
3058
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3059
			'code'    => $code,
3060
		);
3061
		// Don't bother storing it unless we've got some.
3062
		if ( ! is_null( $data ) ) {
3063
			$log_entry['data'] = $data;
3064
		}
3065
		$log[] = $log_entry;
3066
3067
		// Try add_option first, to make sure it's not autoloaded.
3068
		// @todo: Add an add_option method to Jetpack_Options
3069
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3070
			Jetpack_Options::update_option( 'log', $log );
3071
		}
3072
3073
		/**
3074
		 * Fires when Jetpack logs an internal event.
3075
		 *
3076
		 * @since 3.0.0
3077
		 *
3078
		 * @param array $log_entry {
3079
		 *  Array of details about the log entry.
3080
		 *
3081
		 *  @param string time Time of the event.
3082
		 *  @param int user_id ID of the user who trigerred the event.
3083
		 *  @param int blog_id Jetpack Blog ID.
3084
		 *  @param string code Unique name for the event.
3085
		 *  @param string data Data about the event.
3086
		 * }
3087
		 */
3088
		do_action( 'jetpack_log_entry', $log_entry );
3089
	}
3090
3091
	/**
3092
	 * Get the internal event log.
3093
	 *
3094
	 * @param $event (string) - only return the specific log events
3095
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3096
	 *
3097
	 * @return array of log events || WP_Error for invalid params
3098
	 */
3099
	public static function get_log( $event = false, $num = false ) {
3100
		if ( $event && ! is_string( $event ) ) {
3101
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3102
		}
3103
3104
		if ( $num && ! is_numeric( $num ) ) {
3105
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Second param must be...c or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3106
		}
3107
3108
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3109
3110
		// If nothing set - act as it did before, otherwise let's start customizing the output
3111
		if ( ! $num && ! $event ) {
3112
			return $entire_log;
3113
		} else {
3114
			$entire_log = array_reverse( $entire_log );
3115
		}
3116
3117
		$custom_log_output = array();
3118
3119
		if ( $event ) {
3120
			foreach ( $entire_log as $log_event ) {
3121
				if ( $event == $log_event['code'] ) {
3122
					$custom_log_output[] = $log_event;
3123
				}
3124
			}
3125
		} else {
3126
			$custom_log_output = $entire_log;
3127
		}
3128
3129
		if ( $num ) {
3130
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3131
		}
3132
3133
		return $custom_log_output;
3134
	}
3135
3136
	/**
3137
	 * Log modification of important settings.
3138
	 */
3139
	public static function log_settings_change( $option, $old_value, $value ) {
3140
		switch ( $option ) {
3141
			case 'jetpack_sync_non_public_post_stati':
3142
				self::log( $option, $value );
3143
				break;
3144
		}
3145
	}
3146
3147
	/**
3148
	 * Return stat data for WPCOM sync
3149
	 */
3150
	public static function get_stat_data( $encode = true, $extended = true ) {
3151
		$data = Jetpack_Heartbeat::generate_stats_array();
3152
3153
		if ( $extended ) {
3154
			$additional_data = self::get_additional_stat_data();
3155
			$data            = array_merge( $data, $additional_data );
3156
		}
3157
3158
		if ( $encode ) {
3159
			return json_encode( $data );
3160
		}
3161
3162
		return $data;
3163
	}
3164
3165
	/**
3166
	 * Get additional stat data to sync to WPCOM
3167
	 */
3168
	public static function get_additional_stat_data( $prefix = '' ) {
3169
		$return[ "{$prefix}themes" ]        = self::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...
3170
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3171
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3172
		$return[ "{$prefix}site-count" ]    = 0;
3173
3174
		if ( function_exists( 'get_blog_count' ) ) {
3175
			$return[ "{$prefix}site-count" ] = get_blog_count();
3176
		}
3177
		return $return;
3178
	}
3179
3180
	private static function get_site_user_count() {
3181
		global $wpdb;
3182
3183
		if ( function_exists( 'wp_is_large_network' ) ) {
3184
			if ( wp_is_large_network( 'users' ) ) {
3185
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3186
			}
3187
		}
3188
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3189
			// It wasn't there, so regenerate the data and save the transient
3190
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3191
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3192
		}
3193
		return $user_count;
3194
	}
3195
3196
	/* Admin Pages */
3197
3198
	function admin_init() {
3199
		// If the plugin is not connected, display a connect message.
3200
		if (
3201
			// the plugin was auto-activated and needs its candy
3202
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3203
		||
3204
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3205
			! Jetpack_Options::get_option( 'activated' )
3206
		) {
3207
			self::plugin_initialize();
3208
		}
3209
3210
		$is_offline_mode = ( new Status() )->is_offline_mode();
3211
		if ( ! self::is_active() && ! $is_offline_mode ) {
3212
			Jetpack_Connection_Banner::init();
3213
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3214
			// Upgrade: 1.1 -> 1.1.1
3215
			// Check and see if host can verify the Jetpack servers' SSL certificate
3216
			$args = array();
3217
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3218
		}
3219
3220
		Jetpack_Wizard_Banner::init();
3221
3222
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3223
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3224
		}
3225
3226
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3227
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3228
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3229
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3230
3231
		if ( self::is_active() || $is_offline_mode ) {
3232
			// Artificially throw errors in certain specific cases during plugin activation.
3233
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3234
		}
3235
3236
		// Add custom column in wp-admin/users.php to show whether user is linked.
3237
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3238
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3239
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3240
	}
3241
3242
	function admin_body_class( $admin_body_class = '' ) {
3243
		$classes = explode( ' ', trim( $admin_body_class ) );
3244
3245
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3246
3247
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3248
		return " $admin_body_class ";
3249
	}
3250
3251
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3252
		return $admin_body_class . ' jetpack-pagestyles ';
3253
	}
3254
3255
	/**
3256
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3257
	 * This function artificially throws errors for such cases (per a specific list).
3258
	 *
3259
	 * @param string $plugin The activated plugin.
3260
	 */
3261
	function throw_error_on_activate_plugin( $plugin ) {
3262
		$active_modules = self::get_active_modules();
3263
3264
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3265
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3266
			$throw = false;
3267
3268
			// Try and make sure it really was the stats plugin
3269
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3270
				if ( 'stats.php' == basename( $plugin ) ) {
3271
					$throw = true;
3272
				}
3273
			} else {
3274
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3275
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3276
					$throw = true;
3277
				}
3278
			}
3279
3280
			if ( $throw ) {
3281
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3282
			}
3283
		}
3284
	}
3285
3286
	function intercept_plugin_error_scrape_init() {
3287
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3288
	}
3289
3290
	function intercept_plugin_error_scrape( $action, $result ) {
3291
		if ( ! $result ) {
3292
			return;
3293
		}
3294
3295
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3296
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3297
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3298
			}
3299
		}
3300
	}
3301
3302
	/**
3303
	 * Register the remote file upload request handlers, if needed.
3304
	 *
3305
	 * @access public
3306
	 */
3307
	public function add_remote_request_handlers() {
3308
		// Remote file uploads are allowed only via AJAX requests.
3309
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3310
			return;
3311
		}
3312
3313
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3314
		$remote_request_actions = array(
3315
			'jetpack_upload_file',
3316
			'jetpack_update_file',
3317
		);
3318
3319
		// phpcs:ignore WordPress.Security.NonceVerification
3320
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3321
			return;
3322
		}
3323
3324
		// Require Jetpack authentication for the remote file upload AJAX requests.
3325
		if ( ! $this->connection_manager ) {
3326
			$this->connection_manager = new Connection_Manager();
3327
		}
3328
3329
		$this->connection_manager->require_jetpack_authentication();
3330
3331
		// Register the remote file upload AJAX handlers.
3332
		foreach ( $remote_request_actions as $action ) {
3333
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3334
		}
3335
	}
3336
3337
	/**
3338
	 * Handler for Jetpack remote file uploads.
3339
	 *
3340
	 * @access public
3341
	 */
3342
	public function remote_request_handlers() {
3343
		$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...
3344
3345
		switch ( current_filter() ) {
3346
			case 'wp_ajax_nopriv_jetpack_upload_file':
3347
				$response = $this->upload_handler();
3348
				break;
3349
3350
			case 'wp_ajax_nopriv_jetpack_update_file':
3351
				$response = $this->upload_handler( true );
3352
				break;
3353
			default:
3354
				$response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_handler'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3355
				break;
3356
		}
3357
3358
		if ( ! $response ) {
3359
			$response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3360
		}
3361
3362
		if ( is_wp_error( $response ) ) {
3363
			$status_code       = $response->get_error_data();
0 ignored issues
show
Bug introduced by
The method get_error_data() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3364
			$error             = $response->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3365
			$error_description = $response->get_error_message();
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3366
3367
			if ( ! is_int( $status_code ) ) {
3368
				$status_code = 400;
3369
			}
3370
3371
			status_header( $status_code );
3372
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3373
		}
3374
3375
		status_header( 200 );
3376
		if ( true === $response ) {
3377
			exit;
3378
		}
3379
3380
		die( json_encode( (object) $response ) );
3381
	}
3382
3383
	/**
3384
	 * Uploads a file gotten from the global $_FILES.
3385
	 * If `$update_media_item` is true and `post_id` is defined
3386
	 * the attachment file of the media item (gotten through of the post_id)
3387
	 * will be updated instead of add a new one.
3388
	 *
3389
	 * @param  boolean $update_media_item - update media attachment
3390
	 * @return array - An array describing the uploadind files process
3391
	 */
3392
	function upload_handler( $update_media_item = false ) {
3393
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3394
			return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 405.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3395
		}
3396
3397
		$user = wp_authenticate( '', '' );
3398
		if ( ! $user || is_wp_error( $user ) ) {
3399
			return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 403.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3400
		}
3401
3402
		wp_set_current_user( $user->ID );
3403
3404
		if ( ! current_user_can( 'upload_files' ) ) {
3405
			return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_upload_files'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3406
		}
3407
3408
		if ( empty( $_FILES ) ) {
3409
			return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_files_uploaded'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3410
		}
3411
3412
		foreach ( array_keys( $_FILES ) as $files_key ) {
3413
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3414
				return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_hmac'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3415
			}
3416
		}
3417
3418
		$media_keys = array_keys( $_FILES['media'] );
3419
3420
		$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...
3421
		if ( ! $token || is_wp_error( $token ) ) {
3422
			return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3423
		}
3424
3425
		$uploaded_files = array();
3426
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3427
		unset( $GLOBALS['post'] );
3428
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3429
			$file = array();
3430
			foreach ( $media_keys as $media_key ) {
3431
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3432
			}
3433
3434
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3435
3436
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3437
			if ( $hmac_provided !== $hmac_file ) {
3438
				$uploaded_files[ $index ] = (object) array(
3439
					'error'             => 'invalid_hmac',
3440
					'error_description' => 'The corresponding HMAC for this file does not match',
3441
				);
3442
				continue;
3443
			}
3444
3445
			$_FILES['.jetpack.upload.'] = $file;
3446
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3447
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3448
				$post_id = 0;
3449
			}
3450
3451
			if ( $update_media_item ) {
3452
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3453
					return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_input'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3454
				}
3455
3456
				$media_array = $_FILES['media'];
3457
3458
				$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...
3459
				$file_array['type']     = $media_array['type'][0];
3460
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3461
				$file_array['error']    = $media_array['error'][0];
3462
				$file_array['size']     = $media_array['size'][0];
3463
3464
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3465
3466
				if ( is_wp_error( $edited_media_item ) ) {
3467
					return $edited_media_item;
3468
				}
3469
3470
				$response = (object) array(
3471
					'id'   => (string) $post_id,
3472
					'file' => (string) $edited_media_item->post_title,
3473
					'url'  => (string) wp_get_attachment_url( $post_id ),
3474
					'type' => (string) $edited_media_item->post_mime_type,
3475
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3476
				);
3477
3478
				return (array) array( $response );
3479
			}
3480
3481
			$attachment_id = media_handle_upload(
3482
				'.jetpack.upload.',
3483
				$post_id,
3484
				array(),
3485
				array(
3486
					'action' => 'jetpack_upload_file',
3487
				)
3488
			);
3489
3490
			if ( ! $attachment_id ) {
3491
				$uploaded_files[ $index ] = (object) array(
3492
					'error'             => 'unknown',
3493
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3494
				);
3495
			} elseif ( is_wp_error( $attachment_id ) ) {
3496
				$uploaded_files[ $index ] = (object) array(
3497
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3498
					'error_description' => $attachment_id->get_error_message(),
3499
				);
3500
			} else {
3501
				$attachment               = get_post( $attachment_id );
3502
				$uploaded_files[ $index ] = (object) array(
3503
					'id'   => (string) $attachment_id,
3504
					'file' => $attachment->post_title,
3505
					'url'  => wp_get_attachment_url( $attachment_id ),
3506
					'type' => $attachment->post_mime_type,
3507
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3508
				);
3509
				// Zip files uploads are not supported unless they are done for installation purposed
3510
				// lets delete them in case something goes wrong in this whole process
3511
				if ( 'application/zip' === $attachment->post_mime_type ) {
3512
					// Schedule a cleanup for 2 hours from now in case of failed install.
3513
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3514
				}
3515
			}
3516
		}
3517
		if ( ! is_null( $global_post ) ) {
3518
			$GLOBALS['post'] = $global_post;
3519
		}
3520
3521
		return $uploaded_files;
3522
	}
3523
3524
	/**
3525
	 * Add help to the Jetpack page
3526
	 *
3527
	 * @since Jetpack (1.2.3)
3528
	 * @return false if not the Jetpack page
3529
	 */
3530
	function admin_help() {
3531
		$current_screen = get_current_screen();
3532
3533
		// Overview
3534
		$current_screen->add_help_tab(
3535
			array(
3536
				'id'      => 'home',
3537
				'title'   => __( 'Home', 'jetpack' ),
3538
				'content' =>
3539
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3540
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3541
					'<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>',
3542
			)
3543
		);
3544
3545
		// Screen Content
3546
		if ( current_user_can( 'manage_options' ) ) {
3547
			$current_screen->add_help_tab(
3548
				array(
3549
					'id'      => 'settings',
3550
					'title'   => __( 'Settings', 'jetpack' ),
3551
					'content' =>
3552
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3553
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3554
						'<ol>' .
3555
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3556
							'<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>' .
3557
						'</ol>' .
3558
						'<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>',
3559
				)
3560
			);
3561
		}
3562
3563
		// Help Sidebar
3564
		$support_url = Redirect::get_url( 'jetpack-support' );
3565
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3566
		$current_screen->set_help_sidebar(
3567
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3568
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3569
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3570
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3571
		);
3572
	}
3573
3574
	function admin_menu_css() {
3575
		wp_enqueue_style( 'jetpack-icons' );
3576
	}
3577
3578
	function admin_menu_order() {
3579
		return true;
3580
	}
3581
3582
	function jetpack_menu_order( $menu_order ) {
3583
		$jp_menu_order = array();
3584
3585
		foreach ( $menu_order as $index => $item ) {
3586
			if ( $item != 'jetpack' ) {
3587
				$jp_menu_order[] = $item;
3588
			}
3589
3590
			if ( $index == 0 ) {
3591
				$jp_menu_order[] = 'jetpack';
3592
			}
3593
		}
3594
3595
		return $jp_menu_order;
3596
	}
3597
3598
	function admin_banner_styles() {
3599
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3600
3601 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3602
			wp_register_style(
3603
				'jetpack-dops-style',
3604
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3605
				array(),
3606
				JETPACK__VERSION
3607
			);
3608
		}
3609
3610
		wp_enqueue_style(
3611
			'jetpack',
3612
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3613
			array( 'jetpack-dops-style' ),
3614
			JETPACK__VERSION . '-20121016'
3615
		);
3616
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3617
		wp_style_add_data( 'jetpack', 'suffix', $min );
3618
	}
3619
3620
	function plugin_action_links( $actions ) {
3621
3622
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3623
3624
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
3625
			return array_merge(
3626
				$jetpack_home,
3627
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3628
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3629
				$actions
3630
			);
3631
		}
3632
3633
		return array_merge( $jetpack_home, $actions );
3634
	}
3635
3636
	/**
3637
	 * Adds the deactivation warning modal if there are other active plugins using the connection
3638
	 *
3639
	 * @param string $hook The current admin page.
3640
	 *
3641
	 * @return void
3642
	 */
3643
	public function deactivate_dialog( $hook ) {
3644
		if (
3645
			'plugins.php' === $hook
3646
			&& self::is_active()
3647
		) {
3648
3649
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
3650
3651
			if ( count( $active_plugins_using_connection ) > 1 ) {
3652
3653
				add_thickbox();
3654
3655
				wp_register_script(
3656
					'jp-tracks',
3657
					'//stats.wp.com/w.js',
3658
					array(),
3659
					gmdate( 'YW' ),
3660
					true
3661
				);
3662
3663
				wp_register_script(
3664
					'jp-tracks-functions',
3665
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
3666
					array( 'jp-tracks' ),
3667
					JETPACK__VERSION,
3668
					false
3669
				);
3670
3671
				wp_enqueue_script(
3672
					'jetpack-deactivate-dialog-js',
3673
					Assets::get_file_url_for_environment(
3674
						'_inc/build/jetpack-deactivate-dialog.min.js',
3675
						'_inc/jetpack-deactivate-dialog.js'
3676
					),
3677
					array( 'jquery', 'jp-tracks-functions' ),
3678
					JETPACK__VERSION,
3679
					true
3680
				);
3681
3682
				wp_localize_script(
3683
					'jetpack-deactivate-dialog-js',
3684
					'deactivate_dialog',
3685
					array(
3686
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
3687
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
3688
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
3689
					)
3690
				);
3691
3692
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
3693
3694
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
3695
			}
3696
		}
3697
	}
3698
3699
	/**
3700
	 * Outputs the content of the deactivation modal
3701
	 *
3702
	 * @return void
3703
	 */
3704
	public function deactivate_dialog_content() {
3705
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
3706
		unset( $active_plugins_using_connection['jetpack'] );
3707
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack::load_view() has too many arguments starting with $active_plugins_using_connection.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3708
	}
3709
3710
	/**
3711
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
3712
	 *
3713
	 * @param string $login_url The wp-login URL.
3714
	 * @param string $redirect  URL to redirect users after logging in.
3715
	 * @since Jetpack 8.4
3716
	 * @return string
3717
	 */
3718
	public function login_url( $login_url, $redirect ) {
3719
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
3720
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
3721
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
3722
		}
3723
		return $login_url;
3724
	}
3725
3726
	/**
3727
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
3728
	 *
3729
	 * @since Jetpack 8.4
3730
	 */
3731
	public function login_init() {
3732
		// phpcs:ignore WordPress.Security.NonceVerification
3733
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
3734
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3735
			wp_safe_redirect(
3736
				add_query_arg(
3737
					array(
3738
						'forceInstall' => 1,
3739
						'url'          => rawurlencode( get_site_url() ),
3740
					),
3741
					// @todo provide way to go to specific calypso env.
3742
					self::get_calypso_host() . 'jetpack/connect'
3743
				)
3744
			);
3745
			exit;
3746
		}
3747
	}
3748
3749
	/*
3750
	 * Registration flow:
3751
	 * 1 - ::admin_page_load() action=register
3752
	 * 2 - ::try_registration()
3753
	 * 3 - ::register()
3754
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3755
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3756
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3757
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3758
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3759
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3760
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3761
	 *       jetpack_id, jetpack_secret, jetpack_public
3762
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3763
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3764
	 * 5 - user logs in with WP.com account
3765
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3766
	 *		- Manager::authorize()
3767
	 *		- Manager::get_token()
3768
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3769
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3770
	 *			- which responds with access_token, token_type, scope
3771
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
3772
	 *		- Jetpack::activate_default_modules()
3773
	 *     		- Deactivates deprecated plugins
3774
	 *     		- Activates all default modules
3775
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3776
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3777
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3778
	 *     Done!
3779
	 */
3780
3781
	/**
3782
	 * Handles the page load events for the Jetpack admin page
3783
	 */
3784
	function admin_page_load() {
3785
		$error = false;
3786
3787
		// Make sure we have the right body class to hook stylings for subpages off of.
3788
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
3789
3790
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3791
			// Should only be used in intermediate redirects to preserve state across redirects
3792
			self::restate();
3793
		}
3794
3795
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3796
			// @todo: Add validation against a known allowed list.
3797
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3798
			// User clicked in the iframe to link their accounts
3799
			if ( ! self::is_user_connected() ) {
3800
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3801
3802
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3803
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3804
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3805
3806
				if ( isset( $_GET['notes_iframe'] ) ) {
3807
					$connect_url .= '&notes_iframe';
3808
				}
3809
				wp_redirect( $connect_url );
3810
				exit;
3811
			} else {
3812
				if ( ! isset( $_GET['calypso_env'] ) ) {
3813
					self::state( 'message', 'already_authorized' );
3814
					wp_safe_redirect( self::admin_url() );
3815
					exit;
3816
				} else {
3817
					$connect_url  = $this->build_connect_url( true, false, $from );
3818
					$connect_url .= '&already_authorized=true';
3819
					wp_redirect( $connect_url );
3820
					exit;
3821
				}
3822
			}
3823
		}
3824
3825
		if ( isset( $_GET['action'] ) ) {
3826
			switch ( $_GET['action'] ) {
3827
				case 'authorize':
3828
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
3829
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
3830
					exit;
3831
				case 'register':
3832
					if ( ! current_user_can( 'jetpack_connect' ) ) {
3833
						$error = 'cheatin';
3834
						break;
3835
					}
3836
					check_admin_referer( 'jetpack-register' );
3837
					self::log( 'register' );
3838
					self::maybe_set_version_option();
3839
					$registered = self::try_registration();
3840
					if ( is_wp_error( $registered ) ) {
3841
						$error = $registered->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3842
						self::state( 'error', $error );
3843
						self::state( 'error', $registered->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3844
3845
						/**
3846
						 * Jetpack registration Error.
3847
						 *
3848
						 * @since 7.5.0
3849
						 *
3850
						 * @param string|int $error The error code.
3851
						 * @param \WP_Error $registered The error object.
3852
						 */
3853
						do_action( 'jetpack_connection_register_fail', $error, $registered );
3854
						break;
3855
					}
3856
3857
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
3858
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3859
3860
					/**
3861
					 * Jetpack registration Success.
3862
					 *
3863
					 * @since 7.5.0
3864
					 *
3865
					 * @param string $from 'from' GET parameter;
3866
					 */
3867
					do_action( 'jetpack_connection_register_success', $from );
3868
3869
					$url = $this->build_connect_url( true, $redirect, $from );
3870
3871
					if ( ! empty( $_GET['onboarding'] ) ) {
3872
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
3873
					}
3874
3875
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
3876
						$url = add_query_arg( 'auth_approved', 'true', $url );
3877
					}
3878
3879
					wp_redirect( $url );
3880
					exit;
3881
				case 'activate':
3882
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3883
						$error = 'cheatin';
3884
						break;
3885
					}
3886
3887
					$module = stripslashes( $_GET['module'] );
3888
					check_admin_referer( "jetpack_activate-$module" );
3889
					self::log( 'activate', $module );
3890
					if ( ! self::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::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...
3891
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
3892
					}
3893
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3894
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3895
					exit;
3896
				case 'activate_default_modules':
3897
					check_admin_referer( 'activate_default_modules' );
3898
					self::log( 'activate_default_modules' );
3899
					self::restate();
3900
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3901
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3902
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3903
					self::activate_default_modules( $min_version, $max_version, $other_modules );
3904
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3905
					exit;
3906
				case 'disconnect':
3907
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3908
						$error = 'cheatin';
3909
						break;
3910
					}
3911
3912
					check_admin_referer( 'jetpack-disconnect' );
3913
					self::log( 'disconnect' );
3914
					self::disconnect();
3915
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
3916
					exit;
3917
				case 'reconnect':
3918
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3919
						$error = 'cheatin';
3920
						break;
3921
					}
3922
3923
					check_admin_referer( 'jetpack-reconnect' );
3924
					self::log( 'reconnect' );
3925
					$this->disconnect();
3926
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3927
					exit;
3928 View Code Duplication
				case 'deactivate':
3929
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3930
						$error = 'cheatin';
3931
						break;
3932
					}
3933
3934
					$modules = stripslashes( $_GET['module'] );
3935
					check_admin_referer( "jetpack_deactivate-$modules" );
3936
					foreach ( explode( ',', $modules ) as $module ) {
3937
						self::log( 'deactivate', $module );
3938
						self::deactivate_module( $module );
3939
						self::state( 'message', 'module_deactivated' );
3940
					}
3941
					self::state( 'module', $modules );
3942
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3943
					exit;
3944
				case 'unlink':
3945
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3946
					check_admin_referer( 'jetpack-unlink' );
3947
					self::log( 'unlink' );
3948
					Connection_Manager::disconnect_user();
3949
					self::state( 'message', 'unlinked' );
3950
					if ( 'sub-unlink' == $redirect ) {
3951
						wp_safe_redirect( admin_url() );
3952
					} else {
3953
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
3954
					}
3955
					exit;
3956
				case 'onboard':
3957
					if ( ! current_user_can( 'manage_options' ) ) {
3958
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3959
					} else {
3960
						self::create_onboarding_token();
3961
						$url = $this->build_connect_url( true );
3962
3963
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
3964
							$url = add_query_arg( 'onboarding', $token, $url );
3965
						}
3966
3967
						$calypso_env = $this->get_calypso_env();
3968
						if ( ! empty( $calypso_env ) ) {
3969
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
3970
						}
3971
3972
						wp_redirect( $url );
3973
						exit;
3974
					}
3975
					exit;
3976
				default:
3977
					/**
3978
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3979
					 *
3980
					 * @since 2.6.0
3981
					 *
3982
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3983
					 */
3984
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3985
			}
3986
		}
3987
3988
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
3989
			self::activate_new_modules( true );
3990
		}
3991
3992
		$message_code = self::state( 'message' );
3993
		if ( self::state( 'optin-manage' ) ) {
3994
			$activated_manage = $message_code;
3995
			$message_code     = 'jetpack-manage';
3996
		}
3997
3998
		switch ( $message_code ) {
3999
			case 'jetpack-manage':
4000
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4001
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4002
				$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' ), $sites_url ) . '</strong>';
4003
				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...
4004
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4005
				}
4006
				break;
4007
4008
		}
4009
4010
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4011
4012
		if ( ! empty( $deactivated_plugins ) ) {
4013
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4014
			$deactivated_titles  = array();
4015
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4016
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4017
					continue;
4018
				}
4019
4020
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4021
			}
4022
4023
			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...
4024
				if ( $this->message ) {
4025
					$this->message .= "<br /><br />\n";
4026
				}
4027
4028
				$this->message .= wp_sprintf(
4029
					_n(
4030
						'Jetpack contains the most recent version of the old %l plugin.',
4031
						'Jetpack contains the most recent versions of the old %l plugins.',
4032
						count( $deactivated_titles ),
4033
						'jetpack'
4034
					),
4035
					$deactivated_titles
4036
				);
4037
4038
				$this->message .= "<br />\n";
4039
4040
				$this->message .= _n(
4041
					'The old version has been deactivated and can be removed from your site.',
4042
					'The old versions have been deactivated and can be removed from your site.',
4043
					count( $deactivated_titles ),
4044
					'jetpack'
4045
				);
4046
			}
4047
		}
4048
4049
		$this->privacy_checks = self::state( 'privacy_checks' );
4050
4051
		if ( $this->message || $this->error || $this->privacy_checks ) {
4052
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4053
		}
4054
4055
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4056
	}
4057
4058
	function admin_notices() {
4059
4060
		if ( $this->error ) {
4061
			?>
4062
<div id="message" class="jetpack-message jetpack-err">
4063
	<div class="squeezer">
4064
		<h2>
4065
			<?php
4066
			echo wp_kses(
4067
				$this->error,
4068
				array(
4069
					'a'      => array( 'href' => array() ),
4070
					'small'  => true,
4071
					'code'   => true,
4072
					'strong' => true,
4073
					'br'     => true,
4074
					'b'      => true,
4075
				)
4076
			);
4077
			?>
4078
			</h2>
4079
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4080
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4081
<?php	endif; ?>
4082
	</div>
4083
</div>
4084
			<?php
4085
		}
4086
4087
		if ( $this->message ) {
4088
			?>
4089
<div id="message" class="jetpack-message">
4090
	<div class="squeezer">
4091
		<h2>
4092
			<?php
4093
			echo wp_kses(
4094
				$this->message,
4095
				array(
4096
					'strong' => array(),
4097
					'a'      => array( 'href' => true ),
4098
					'br'     => true,
4099
				)
4100
			);
4101
			?>
4102
			</h2>
4103
	</div>
4104
</div>
4105
			<?php
4106
		}
4107
4108
		if ( $this->privacy_checks ) :
4109
			$module_names = $module_slugs = array();
4110
4111
			$privacy_checks = explode( ',', $this->privacy_checks );
4112
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4113
			foreach ( $privacy_checks as $module_slug ) {
4114
				$module = self::get_module( $module_slug );
4115
				if ( ! $module ) {
4116
					continue;
4117
				}
4118
4119
				$module_slugs[] = $module_slug;
4120
				$module_names[] = "<strong>{$module['name']}</strong>";
4121
			}
4122
4123
			$module_slugs = join( ',', $module_slugs );
4124
			?>
4125
<div id="message" class="jetpack-message jetpack-err">
4126
	<div class="squeezer">
4127
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4128
		<p>
4129
			<?php
4130
			echo wp_kses(
4131
				wptexturize(
4132
					wp_sprintf(
4133
						_nx(
4134
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4135
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4136
							count( $privacy_checks ),
4137
							'%l = list of Jetpack module/feature names',
4138
							'jetpack'
4139
						),
4140
						$module_names
4141
					)
4142
				),
4143
				array( 'strong' => true )
4144
			);
4145
4146
			echo "\n<br />\n";
4147
4148
			echo wp_kses(
4149
				sprintf(
4150
					_nx(
4151
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4152
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4153
						count( $privacy_checks ),
4154
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4155
						'jetpack'
4156
					),
4157
					wp_nonce_url(
4158
						self::admin_url(
4159
							array(
4160
								'page'   => 'jetpack',
4161
								'action' => 'deactivate',
4162
								'module' => urlencode( $module_slugs ),
4163
							)
4164
						),
4165
						"jetpack_deactivate-$module_slugs"
4166
					),
4167
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4168
				),
4169
				array(
4170
					'a' => array(
4171
						'href'  => true,
4172
						'title' => true,
4173
					),
4174
				)
4175
			);
4176
			?>
4177
		</p>
4178
	</div>
4179
</div>
4180
			<?php
4181
endif;
4182
	}
4183
4184
	/**
4185
	 * We can't always respond to a signed XML-RPC request with a
4186
	 * helpful error message. In some circumstances, doing so could
4187
	 * leak information.
4188
	 *
4189
	 * Instead, track that the error occurred via a Jetpack_Option,
4190
	 * and send that data back in the heartbeat.
4191
	 * All this does is increment a number, but it's enough to find
4192
	 * trends.
4193
	 *
4194
	 * @param WP_Error $xmlrpc_error The error produced during
4195
	 *                               signature validation.
4196
	 */
4197
	function track_xmlrpc_error( $xmlrpc_error ) {
4198
		$code = is_wp_error( $xmlrpc_error )
4199
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4200
			: 'should-not-happen';
4201
4202
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4203
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4204
			// No need to update the option if we already have
4205
			// this code stored.
4206
			return;
4207
		}
4208
		$xmlrpc_errors[ $code ] = true;
4209
4210
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, 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...
4211
	}
4212
4213
	/**
4214
	 * Initialize the jetpack stats instance only when needed
4215
	 *
4216
	 * @return void
4217
	 */
4218
	private function initialize_stats() {
4219
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4220
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4221
		}
4222
	}
4223
4224
	/**
4225
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4226
	 */
4227
	function stat( $group, $detail ) {
4228
		$this->initialize_stats();
4229
		$this->a8c_mc_stats_instance->add( $group, $detail );
4230
4231
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4232
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4233
	}
4234
4235
	/**
4236
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4237
	 */
4238
	function do_stats( $method = '' ) {
4239
		$this->initialize_stats();
4240
		if ( 'server_side' === $method ) {
4241
			$this->a8c_mc_stats_instance->do_server_side_stats();
4242
		} else {
4243
			$this->a8c_mc_stats_instance->do_stats();
4244
		}
4245
4246
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4247
		$this->stats = array();
4248
	}
4249
4250
	/**
4251
	 * Runs stats code for a one-off, server-side.
4252
	 *
4253
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4254
	 *
4255
	 * @return bool If it worked.
4256
	 */
4257
	static function do_server_side_stat( $args ) {
4258
		$url                   = self::build_stats_url( $args );
4259
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4260
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4261
	}
4262
4263
	/**
4264
	 * Builds the stats url.
4265
	 *
4266
	 * @param $args array|string The arguments to append to the URL.
4267
	 *
4268
	 * @return string The URL to be pinged.
4269
	 */
4270
	static function build_stats_url( $args ) {
4271
4272
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4273
		return $a8c_mc_stats_instance->build_stats_url( $args );
4274
4275
	}
4276
4277
	/**
4278
	 * Builds a URL to the Jetpack connection auth page
4279
	 *
4280
	 * @since 3.9.5
4281
	 *
4282
	 * @param bool        $raw If true, URL will not be escaped.
4283
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4284
	 *                              If string, will be a custom redirect.
4285
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4286
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4287
	 *
4288
	 * @return string Connect URL
4289
	 */
4290
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4291
		$site_id    = Jetpack_Options::get_option( 'id' );
4292
		$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...
4293
4294
		if ( $register || ! $blog_token || ! $site_id ) {
4295
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4296
4297
			if ( ! empty( $redirect ) ) {
4298
				$url = add_query_arg(
4299
					'redirect',
4300
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4301
					$url
4302
				);
4303
			}
4304
4305
			if ( is_network_admin() ) {
4306
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4307
			}
4308
4309
			$calypso_env = self::get_calypso_env();
4310
4311
			if ( ! empty( $calypso_env ) ) {
4312
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4313
			}
4314
		} else {
4315
4316
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4317
			// because otherwise this logic can get us in to a loop.
4318
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4319
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4320
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4321
4322
				$response = Client::wpcom_json_api_request_as_blog(
4323
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4324
					'1.1'
4325
				);
4326
4327
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4328
4329
					// Generating a register URL instead to refresh the existing token
4330
					return $this->build_connect_url( $raw, $redirect, $from, true );
4331
				}
4332
			}
4333
4334
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4290 can also be of type string; however, Jetpack::build_authorize_url() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
4335
		}
4336
4337
		if ( $from ) {
4338
			$url = add_query_arg( 'from', $from, $url );
4339
		}
4340
4341
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4342
		/**
4343
		 * Filter the URL used when connecting a user to a WordPress.com account.
4344
		 *
4345
		 * @since 8.1.0
4346
		 *
4347
		 * @param string $url Connection URL.
4348
		 * @param bool   $raw If true, URL will not be escaped.
4349
		 */
4350
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $raw.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4351
	}
4352
4353
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4354
4355
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4356
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4357
4358
		if ( $iframe ) {
4359
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4360
		}
4361
4362
		$c8n = self::connection();
4363
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
Documentation introduced by
$redirect 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...
4364
4365
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4366
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4367
4368
		if ( $iframe ) {
4369
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4370
		}
4371
4372
		/**
4373
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4374
		 *
4375
		 * @since 8.9.0
4376
		 *
4377
		 * @param string $url Connection URL.
4378
		 */
4379
		return apply_filters( 'jetpack_build_authorize_url', $url );
4380
	}
4381
4382
	/**
4383
	 * Filters the connection URL parameter array.
4384
	 *
4385
	 * @param array $args default URL parameters used by the package.
4386
	 * @return array the modified URL arguments array.
4387
	 */
4388
	public static function filter_connect_request_body( $args ) {
4389
		if (
4390
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4391
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4392
		) {
4393
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4394
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4395
				? $gp_locale->slug
4396
				: '';
4397
		}
4398
4399
		$tracking        = new Tracking();
4400
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4401
4402
		$args = array_merge(
4403
			$args,
4404
			array(
4405
				'_ui' => $tracks_identity['_ui'],
4406
				'_ut' => $tracks_identity['_ut'],
4407
			)
4408
		);
4409
4410
		$calypso_env = self::get_calypso_env();
4411
4412
		if ( ! empty( $calypso_env ) ) {
4413
			$args['calypso_env'] = $calypso_env;
4414
		}
4415
4416
		return $args;
4417
	}
4418
4419
	/**
4420
	 * Filters the redirection URL that is used for connect requests. The redirect
4421
	 * URL should return the user back to the Jetpack console.
4422
	 *
4423
	 * @param String $redirect the default redirect URL used by the package.
4424
	 * @return String the modified URL.
4425
	 */
4426
	public static function filter_connect_redirect_url( $redirect ) {
4427
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4428
		$redirect           = $redirect
4429
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4430
			: $jetpack_admin_page;
4431
4432
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4433
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4434
		}
4435
4436
		return $redirect;
4437
	}
4438
4439
	/**
4440
	 * This action fires at the beginning of the Manager::authorize method.
4441
	 */
4442
	public static function authorize_starting() {
4443
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4444
		// Checking if site has been active/connected previously before recording unique connection.
4445
		if ( ! $jetpack_unique_connection ) {
4446
			// jetpack_unique_connection option has never been set.
4447
			$jetpack_unique_connection = array(
4448
				'connected'    => 0,
4449
				'disconnected' => 0,
4450
				'version'      => '3.6.1',
4451
			);
4452
4453
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4454
4455
			// Track unique connection.
4456
			$jetpack = self::init();
4457
4458
			$jetpack->stat( 'connections', 'unique-connection' );
4459
			$jetpack->do_stats( 'server_side' );
4460
		}
4461
4462
		// Increment number of times connected.
4463
		$jetpack_unique_connection['connected'] += 1;
4464
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4465
	}
4466
4467
	/**
4468
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4469
	 * linked.
4470
	 */
4471
	public static function authorize_ending_linked() {
4472
		// Don't activate anything since we are just connecting a user.
4473
		self::state( 'message', 'linked' );
4474
	}
4475
4476
	/**
4477
	 * This action fires at the end of the Manager::authorize method when the master user is
4478
	 * authorized.
4479
	 *
4480
	 * @param array $data The request data.
4481
	 */
4482
	public static function authorize_ending_authorized( $data ) {
4483
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4484
		self::invalidate_onboarding_token();
4485
4486
		// If redirect_uri is SSO, ensure SSO module is enabled.
4487
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4488
4489
		/** This filter is documented in class.jetpack-cli.php */
4490
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4491
4492
		$activate_sso = (
4493
			isset( $redirect_options['action'] ) &&
4494
			'jetpack-sso' === $redirect_options['action'] &&
4495
			$jetpack_start_enable_sso
4496
		);
4497
4498
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4499
4500
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4501
	}
4502
4503
	/**
4504
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
4505
	 * reconnect process is completed.
4506
	 * Note that this currently only happens when we don't need the user to re-authorize
4507
	 * their WP.com account, eg in cases where we are restoring a connection with
4508
	 * unhealthy blog token.
4509
	 */
4510
	public static function reconnection_completed() {
4511
		self::state( 'message', 'reconnection_completed' );
4512
	}
4513
4514 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4515
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4516
4517
		if ( $activation_source_name ) {
4518
			$args['_as'] = urlencode( $activation_source_name );
4519
		}
4520
4521
		if ( $activation_source_keyword ) {
4522
			$args['_ak'] = urlencode( $activation_source_keyword );
4523
		}
4524
	}
4525
4526
	function build_reconnect_url( $raw = false ) {
4527
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4528
		return $raw ? $url : esc_url( $url );
4529
	}
4530
4531
	public static function admin_url( $args = null ) {
4532
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
Documentation introduced by
array('page' => 'jetpack') is of type array<string,string,{"page":"string"}>, but the function expects a string.

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...
4533
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4534
		return $url;
4535
	}
4536
4537
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4538
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4539
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4540
	}
4541
4542
	function dismiss_jetpack_notice() {
4543
4544
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4545
			return;
4546
		}
4547
4548
		switch ( $_GET['jetpack-notice'] ) {
4549
			case 'dismiss':
4550
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4551
4552
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4553
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4554
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4555
				}
4556
				break;
4557
		}
4558
	}
4559
4560
	public static function sort_modules( $a, $b ) {
4561
		if ( $a['sort'] == $b['sort'] ) {
4562
			return 0;
4563
		}
4564
4565
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4566
	}
4567
4568
	function ajax_recheck_ssl() {
4569
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4570
		$result = self::permit_ssl( true );
4571
		wp_send_json(
4572
			array(
4573
				'enabled' => $result,
4574
				'message' => get_transient( 'jetpack_https_test_message' ),
4575
			)
4576
		);
4577
	}
4578
4579
	/* Client API */
4580
4581
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4582
		// Default to a blog token.
4583
		$token_type = 'blog';
4584
4585
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4586
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4587
			if ( ! empty( $_GET['onboarding'] ) ) {
4588
				$jpo = $_GET;
4589
			} else {
4590
				$jpo = json_decode( $request_data, true );
4591
			}
4592
4593
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4594
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4595
4596
			if (
4597
				isset( $jpo_user )
4598
				&& isset( $jpo_token )
4599
				&& is_email( $jpo_user )
4600
				&& ctype_alnum( $jpo_token )
4601
				&& isset( $_GET['rest_route'] )
4602
				&& self::validate_onboarding_token_action(
4603
					$jpo_token,
4604
					$_GET['rest_route']
4605
				)
4606
			) {
4607
				$jp_user = get_user_by( 'email', $jpo_user );
4608
				if ( is_a( $jp_user, 'WP_User' ) ) {
4609
					wp_set_current_user( $jp_user->ID );
4610
					$user_can = is_multisite()
4611
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4612
						: current_user_can( 'manage_options' );
4613
					if ( $user_can ) {
4614
						$token_type              = 'user';
4615
						$token->external_user_id = $jp_user->ID;
4616
					}
4617
				}
4618
			}
4619
4620
			$token_data['type']    = $token_type;
4621
			$token_data['user_id'] = $token->external_user_id;
4622
		}
4623
4624
		return $token_data;
4625
	}
4626
4627
	/**
4628
	 * Create a random secret for validating onboarding payload
4629
	 *
4630
	 * @return string Secret token
4631
	 */
4632
	public static function create_onboarding_token() {
4633
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4634
			$token = wp_generate_password( 32, false );
4635
			Jetpack_Options::update_option( 'onboarding', $token );
4636
		}
4637
4638
		return $token;
4639
	}
4640
4641
	/**
4642
	 * Remove the onboarding token
4643
	 *
4644
	 * @return bool True on success, false on failure
4645
	 */
4646
	public static function invalidate_onboarding_token() {
4647
		return Jetpack_Options::delete_option( 'onboarding' );
4648
	}
4649
4650
	/**
4651
	 * Validate an onboarding token for a specific action
4652
	 *
4653
	 * @return boolean True if token/action pair is accepted, false if not
4654
	 */
4655
	public static function validate_onboarding_token_action( $token, $action ) {
4656
		// Compare tokens, bail if tokens do not match
4657
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4658
			return false;
4659
		}
4660
4661
		// List of valid actions we can take
4662
		$valid_actions = array(
4663
			'/jetpack/v4/settings',
4664
		);
4665
4666
		// Only allow valid actions.
4667
		if ( ! in_array( $action, $valid_actions ) ) {
4668
			return false;
4669
		}
4670
4671
		return true;
4672
	}
4673
4674
	/**
4675
	 * Checks to see if the URL is using SSL to connect with Jetpack
4676
	 *
4677
	 * @since 2.3.3
4678
	 * @return boolean
4679
	 */
4680
	public static function permit_ssl( $force_recheck = false ) {
4681
		// Do some fancy tests to see if ssl is being supported
4682
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4683
			$message = '';
4684
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4685
				$ssl = 0;
4686
			} else {
4687
				$ssl = 1;
4688
4689
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4690
					$ssl     = 0;
4691
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
4692
				} else {
4693
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4694
					if ( is_wp_error( $response ) ) {
4695
						$ssl     = 0;
4696
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4697
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4698
						$ssl     = 0;
4699
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4700
					}
4701
				}
4702
			}
4703
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4704
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4705
		}
4706
4707
		return (bool) $ssl;
4708
	}
4709
4710
	/*
4711
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
4712
	 */
4713
	public function alert_auto_ssl_fail() {
4714
		if ( ! current_user_can( 'manage_options' ) ) {
4715
			return;
4716
		}
4717
4718
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4719
		?>
4720
4721
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4722
			<div class="jp-banner__content">
4723
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4724
				<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>
4725
				<p>
4726
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4727
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4728
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4729
				</p>
4730
				<p>
4731
					<?php
4732
					printf(
4733
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
4734
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
4735
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
4736
					);
4737
					?>
4738
				</p>
4739
			</div>
4740
		</div>
4741
		<style>
4742
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4743
		</style>
4744
		<script type="text/javascript">
4745
			jQuery( document ).ready( function( $ ) {
4746
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4747
					var $this = $( this );
4748
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4749
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4750
					e.preventDefault();
4751
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4752
					$.post( ajaxurl, data )
4753
					  .done( function( response ) {
4754
						  if ( response.enabled ) {
4755
							  $( '#jetpack-ssl-warning' ).hide();
4756
						  } else {
4757
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4758
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4759
						  }
4760
					  }.bind( $this ) );
4761
				} );
4762
			} );
4763
		</script>
4764
4765
		<?php
4766
	}
4767
4768
	/**
4769
	 * Returns the connection manager object.
4770
	 *
4771
	 * @return Automattic\Jetpack\Connection\Manager
4772
	 */
4773
	public static function connection() {
4774
		$jetpack = static::init();
4775
4776
		// If the connection manager hasn't been instantiated, do that now.
4777
		if ( ! $jetpack->connection_manager ) {
4778
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
4779
		}
4780
4781
		return $jetpack->connection_manager;
4782
	}
4783
4784
	/**
4785
	 * Creates two secret tokens and the end of life timestamp for them.
4786
	 *
4787
	 * Note these tokens are unique per call, NOT static per site for connecting.
4788
	 *
4789
	 * @since 2.6
4790
	 * @param String  $action  The action name.
4791
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be false|integer?

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...
4792
	 * @param Integer $exp     Expiration time in seconds.
4793
	 * @return array
4794
	 */
4795
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4796
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4797
	}
4798
4799
	public static function get_secrets( $action, $user_id ) {
4800
		$secrets = self::connection()->get_secrets( $action, $user_id );
4801
4802
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4803
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4804
		}
4805
4806
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4807
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4808
		}
4809
4810
		return $secrets;
4811
	}
4812
4813
	/**
4814
	 * Builds the timeout limit for queries talking with the wpcom servers.
4815
	 *
4816
	 * Based on local php max_execution_time in php.ini
4817
	 *
4818
	 * @since 5.4
4819
	 * @return int
4820
	 **/
4821
	public static function get_max_execution_time() {
4822
		$timeout = (int) ini_get( 'max_execution_time' );
4823
4824
		// Ensure exec time set in php.ini.
4825
		if ( ! $timeout ) {
4826
			$timeout = 30;
4827
		}
4828
		return $timeout;
4829
	}
4830
4831
	/**
4832
	 * Sets a minimum request timeout, and returns the current timeout
4833
	 *
4834
	 * @since 5.4
4835
	 **/
4836 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
4837
		$timeout = self::get_max_execution_time();
4838
		if ( $timeout < $min_timeout ) {
4839
			$timeout = $min_timeout;
4840
			set_time_limit( $timeout );
4841
		}
4842
		return $timeout;
4843
	}
4844
4845
	/**
4846
	 * @return bool|WP_Error
4847
	 */
4848
	public static function register() {
4849
		$tracking = new Tracking();
4850
		$tracking->record_user_event( 'jpc_register_begin' );
4851
4852
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
4853
4854
		$connection   = self::connection();
4855
		$registration = $connection->register();
4856
4857
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
4858
4859
		if ( ! $registration || is_wp_error( $registration ) ) {
4860
			return $registration;
4861
		}
4862
4863
		return true;
4864
	}
4865
4866
	/**
4867
	 * Filters the registration request body to include tracking properties.
4868
	 *
4869
	 * @param array $properties
4870
	 * @return array amended properties.
4871
	 */
4872 View Code Duplication
	public static function filter_register_request_body( $properties ) {
4873
		$tracking        = new Tracking();
4874
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
4875
4876
		return array_merge(
4877
			$properties,
4878
			array(
4879
				'_ui' => $tracks_identity['_ui'],
4880
				'_ut' => $tracks_identity['_ut'],
4881
			)
4882
		);
4883
	}
4884
4885
	/**
4886
	 * Filters the token request body to include tracking properties.
4887
	 *
4888
	 * @param array $properties
4889
	 * @return array amended properties.
4890
	 */
4891 View Code Duplication
	public static function filter_token_request_body( $properties ) {
4892
		$tracking        = new Tracking();
4893
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
4894
4895
		return array_merge(
4896
			$properties,
4897
			array(
4898
				'_ui' => $tracks_identity['_ui'],
4899
				'_ut' => $tracks_identity['_ut'],
4900
			)
4901
		);
4902
	}
4903
4904
	/**
4905
	 * If the db version is showing something other that what we've got now, bump it to current.
4906
	 *
4907
	 * @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...
4908
	 */
4909
	public static function maybe_set_version_option() {
4910
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4911
		if ( JETPACK__VERSION != $version ) {
4912
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4913
4914
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4915
				/** This action is documented in class.jetpack.php */
4916
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4917
			}
4918
4919
			return true;
4920
		}
4921
		return false;
4922
	}
4923
4924
	/* Client Server API */
4925
4926
	/**
4927
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
4928
	 * SET: state( $key, $value );
4929
	 * GET: $value = state( $key );
4930
	 *
4931
	 * @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...
4932
	 * @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...
4933
	 * @param bool   $restate private
4934
	 */
4935
	public static function state( $key = null, $value = null, $restate = false ) {
4936
		static $state = array();
4937
		static $path, $domain;
4938
		if ( ! isset( $path ) ) {
4939
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
4940
			$admin_url = self::admin_url();
4941
			$bits      = wp_parse_url( $admin_url );
4942
4943
			if ( is_array( $bits ) ) {
4944
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
4945
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
4946
			} else {
4947
				$path = $domain = null;
4948
			}
4949
		}
4950
4951
		// Extract state from cookies and delete cookies
4952
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
4953
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
4954
			unset( $_COOKIE['jetpackState'] );
4955
			foreach ( $yum as $k => $v ) {
0 ignored issues
show
Bug introduced by
The expression $yum of type string|array<integer,string> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
4956
				if ( strlen( $v ) ) {
4957
					$state[ $k ] = $v;
4958
				}
4959
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
4960
			}
4961
		}
4962
4963
		if ( $restate ) {
4964
			foreach ( $state as $k => $v ) {
4965
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
4966
			}
4967
			return;
4968
		}
4969
4970
		// Get a state variable.
4971
		if ( isset( $key ) && ! isset( $value ) ) {
4972
			if ( array_key_exists( $key, $state ) ) {
4973
				return $state[ $key ];
4974
			}
4975
			return null;
4976
		}
4977
4978
		// Set a state variable.
4979
		if ( isset( $key ) && isset( $value ) ) {
4980
			if ( is_array( $value ) && isset( $value[0] ) ) {
4981
				$value = $value[0];
4982
			}
4983
			$state[ $key ] = $value;
4984
			if ( ! headers_sent() ) {
4985
				if ( self::should_set_cookie( $key ) ) {
4986
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
4987
				}
4988
			}
4989
		}
4990
	}
4991
4992
	public static function restate() {
4993
		self::state( null, null, true );
4994
	}
4995
4996
	/**
4997
	 * Determines whether the jetpackState[$key] value should be added to the
4998
	 * cookie.
4999
	 *
5000
	 * @param string $key The state key.
5001
	 *
5002
	 * @return boolean Whether the value should be added to the cookie.
5003
	 */
5004
	public static function should_set_cookie( $key ) {
5005
		global $current_screen;
5006
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5007
5008
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5009
			return false;
5010
		}
5011
5012
		return true;
5013
	}
5014
5015
	public static function check_privacy( $file ) {
5016
		static $is_site_publicly_accessible = null;
5017
5018
		if ( is_null( $is_site_publicly_accessible ) ) {
5019
			$is_site_publicly_accessible = false;
5020
5021
			$rpc = new Jetpack_IXR_Client();
5022
5023
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5024
			if ( $success ) {
5025
				$response = $rpc->getResponse();
5026
				if ( $response ) {
5027
					$is_site_publicly_accessible = true;
5028
				}
5029
			}
5030
5031
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5032
		}
5033
5034
		if ( $is_site_publicly_accessible ) {
5035
			return;
5036
		}
5037
5038
		$module_slug = self::get_module_slug( $file );
5039
5040
		$privacy_checks = self::state( 'privacy_checks' );
5041
		if ( ! $privacy_checks ) {
5042
			$privacy_checks = $module_slug;
5043
		} else {
5044
			$privacy_checks .= ",$module_slug";
5045
		}
5046
5047
		self::state( 'privacy_checks', $privacy_checks );
5048
	}
5049
5050
	/**
5051
	 * Helper method for multicall XMLRPC.
5052
	 *
5053
	 * @deprecated since 8.9.0
5054
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5055
	 *
5056
	 * @param ...$args Args for the async_call.
5057
	 */
5058
	public static function xmlrpc_async_call( ...$args ) {
5059
5060
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5061
5062
		global $blog_id;
5063
		static $clients = array();
5064
5065
		$client_blog_id = is_multisite() ? $blog_id : 0;
5066
5067
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5068
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => Connection_Manager::CONNECTION_OWNER ) );
5069
			if ( function_exists( 'ignore_user_abort' ) ) {
5070
				ignore_user_abort( true );
5071
			}
5072
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5073
		}
5074
5075
		if ( ! empty( $args[0] ) ) {
5076
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5077
		} elseif ( is_multisite() ) {
5078
			foreach ( $clients as $client_blog_id => $client ) {
5079
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5080
					continue;
5081
				}
5082
5083
				$switch_success = switch_to_blog( $client_blog_id, true );
5084
				if ( ! $switch_success ) {
5085
					continue;
5086
				}
5087
5088
				flush();
5089
				$client->query();
5090
5091
				restore_current_blog();
5092
			}
5093
		} else {
5094
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5095
				flush();
5096
				$clients[0]->query();
5097
			}
5098
		}
5099
	}
5100
5101
	/* JSON API Authorization */
5102
5103
	/**
5104
	 * Handles the login action for Authorizing the JSON API
5105
	 */
5106
	function login_form_json_api_authorization() {
5107
		$this->verify_json_api_authorization_request();
5108
5109
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5110
5111
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5112
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5113
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5114
	}
5115
5116
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5117
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5118
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5119
			return $url;
5120
		}
5121
5122
		$parsed_url = wp_parse_url( $url );
5123
		$url        = strtok( $url, '?' );
5124
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5125
		if ( ! empty( $parsed_url['query'] ) ) {
5126
			$url .= "&{$parsed_url['query']}";
5127
		}
5128
5129
		return $url;
5130
	}
5131
5132
	// Make sure the POSTed request is handled by the same action
5133
	function preserve_action_in_login_form_for_json_api_authorization() {
5134
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5135
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5136
	}
5137
5138
	// If someone logs in to approve API access, store the Access Code in usermeta
5139
	function store_json_api_authorization_token( $user_login, $user ) {
5140
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5141
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5142
		$token = wp_generate_password( 32, false );
5143
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5144
	}
5145
5146
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5147
	function allow_wpcom_public_api_domain( $domains ) {
5148
		$domains[] = 'public-api.wordpress.com';
5149
		return $domains;
5150
	}
5151
5152
	static function is_redirect_encoded( $redirect_url ) {
5153
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5154
	}
5155
5156
	// Add all wordpress.com environments to the safe redirect allowed list.
5157
	function allow_wpcom_environments( $domains ) {
5158
		$domains[] = 'wordpress.com';
5159
		$domains[] = 'wpcalypso.wordpress.com';
5160
		$domains[] = 'horizon.wordpress.com';
5161
		$domains[] = 'calypso.localhost';
5162
		return $domains;
5163
	}
5164
5165
	// Add the Access Code details to the public-api.wordpress.com redirect
5166
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5167
		return add_query_arg(
5168
			urlencode_deep(
5169
				array(
5170
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5171
					'jetpack-user-id' => (int) $user->ID,
5172
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5173
				)
5174
			),
5175
			$redirect_to
5176
		);
5177
	}
5178
5179
	/**
5180
	 * Verifies the request by checking the signature
5181
	 *
5182
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5183
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5184
	 *
5185
	 * @param null|array $environment
5186
	 */
5187
	function verify_json_api_authorization_request( $environment = null ) {
5188
		$environment = is_null( $environment )
5189
			? $_REQUEST
5190
			: $environment;
5191
5192
		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...
5193
		$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...
5194
		if ( ! $token || empty( $token->secret ) ) {
5195
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5196
		}
5197
5198
		$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' );
5199
5200
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5201
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5202
			/**
5203
			 * Jetpack authorisation request Error.
5204
			 *
5205
			 * @since 7.5.0
5206
			 */
5207
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5208
			$die_error = sprintf(
5209
				/* translators: %s is a URL */
5210
				__( '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' ),
5211
				Redirect::get_url( 'jetpack-support-double-encoding' )
5212
			);
5213
		}
5214
5215
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5216
5217
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5218
			$signature = $jetpack_signature->sign_request(
5219
				$environment['token'],
5220
				$environment['timestamp'],
5221
				$environment['nonce'],
5222
				'',
5223
				'GET',
5224
				$environment['jetpack_json_api_original_query'],
5225
				null,
5226
				true
5227
			);
5228
		} else {
5229
			$signature = $jetpack_signature->sign_current_request(
5230
				array(
5231
					'body'   => null,
5232
					'method' => 'GET',
5233
				)
5234
			);
5235
		}
5236
5237
		if ( ! $signature ) {
5238
			wp_die( $die_error );
5239
		} elseif ( is_wp_error( $signature ) ) {
5240
			wp_die( $die_error );
5241
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5242
			if ( is_ssl() ) {
5243
				// 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
5244
				$signature = $jetpack_signature->sign_current_request(
5245
					array(
5246
						'scheme' => 'http',
5247
						'body'   => null,
5248
						'method' => 'GET',
5249
					)
5250
				);
5251
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5252
					wp_die( $die_error );
5253
				}
5254
			} else {
5255
				wp_die( $die_error );
5256
			}
5257
		}
5258
5259
		$timestamp = (int) $environment['timestamp'];
5260
		$nonce     = stripslashes( (string) $environment['nonce'] );
5261
5262
		if ( ! $this->connection_manager ) {
5263
			$this->connection_manager = new Connection_Manager();
5264
		}
5265
5266
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
5267
			// De-nonce the nonce, at least for 5 minutes.
5268
			// 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)
5269
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5270
			if ( $old_nonce_time < time() - 300 ) {
5271
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5272
			}
5273
		}
5274
5275
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5276
		$data_filters = array(
5277
			'state'        => 'opaque',
5278
			'client_id'    => 'int',
5279
			'client_title' => 'string',
5280
			'client_image' => 'url',
5281
		);
5282
5283
		foreach ( $data_filters as $key => $sanitation ) {
5284
			if ( ! isset( $data->$key ) ) {
5285
				wp_die( $die_error );
5286
			}
5287
5288
			switch ( $sanitation ) {
5289
				case 'int':
5290
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
5291
					break;
5292
				case 'opaque':
5293
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
5294
					break;
5295
				case 'string':
5296
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
5297
					break;
5298
				case 'url':
5299
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
5300
					break;
5301
			}
5302
		}
5303
5304
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5305
			wp_die( $die_error );
5306
		}
5307
	}
5308
5309
	function login_message_json_api_authorization( $message ) {
5310
		return '<p class="message">' . sprintf(
5311
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
5312
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5313
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5314
	}
5315
5316
	/**
5317
	 * Get $content_width, but with a <s>twist</s> filter.
5318
	 */
5319
	public static function get_content_width() {
5320
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5321
			? $GLOBALS['content_width']
5322
			: false;
5323
		/**
5324
		 * Filter the Content Width value.
5325
		 *
5326
		 * @since 2.2.3
5327
		 *
5328
		 * @param string $content_width Content Width value.
5329
		 */
5330
		return apply_filters( 'jetpack_content_width', $content_width );
5331
	}
5332
5333
	/**
5334
	 * Pings the WordPress.com Mirror Site for the specified options.
5335
	 *
5336
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site.
5337
	 *
5338
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5339
	 */
5340
	public function get_cloud_site_options( $option_names ) {
5341
		$option_names = array_filter( (array) $option_names, 'is_string' );
5342
5343
		$xml = new Jetpack_IXR_Client();
5344
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5345
		if ( $xml->isError() ) {
5346
			return array(
5347
				'error_code' => $xml->getErrorCode(),
5348
				'error_msg'  => $xml->getErrorMessage(),
5349
			);
5350
		}
5351
		$cloud_site_options = $xml->getResponse();
5352
5353
		return $cloud_site_options;
5354
	}
5355
5356
	/**
5357
	 * Checks if the site is currently in an identity crisis.
5358
	 *
5359
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5360
	 */
5361
	public static function check_identity_crisis() {
5362
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
5363
			return false;
5364
		}
5365
5366
		return Jetpack_Options::get_option( 'sync_error_idc' );
5367
	}
5368
5369
	/**
5370
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5371
	 *
5372
	 * @since 4.4.0
5373
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5374
	 *
5375
	 * @return bool
5376
	 */
5377
	public static function validate_sync_error_idc_option() {
5378
		$is_valid = false;
5379
5380
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5381
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5382
		if ( $sync_error && self::sync_idc_optin() ) {
5383
			$local_options = self::get_sync_error_idc_option();
5384
			// Ensure all values are set.
5385
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
5386
5387
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
5388
				if (
5389
						isset( $sync_error['wpcom_home'] ) &&
5390
						isset( $sync_error['wpcom_siteurl'] ) &&
5391
						$sync_error['wpcom_home'] === $local_options['home'] &&
5392
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
5393
				) {
5394
					$is_valid = false;
5395
					// Enable migrate_for_idc so that sync actions are accepted.
5396
					Jetpack_Options::update_option( 'migrate_for_idc', true );
5397
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5398
					$is_valid = true;
5399
				}
5400
			}
5401
		}
5402
5403
		/**
5404
		 * Filters whether the sync_error_idc option is valid.
5405
		 *
5406
		 * @since 4.4.0
5407
		 *
5408
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5409
		 */
5410
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5411
5412
		if ( ! $is_valid && $sync_error ) {
5413
			// Since the option exists, and did not validate, delete it.
5414
			Jetpack_Options::delete_option( 'sync_error_idc' );
5415
		}
5416
5417
		return $is_valid;
5418
	}
5419
5420
	/**
5421
	 * Normalizes a url by doing three things:
5422
	 *  - Strips protocol
5423
	 *  - Strips www
5424
	 *  - Adds a trailing slash
5425
	 *
5426
	 * @since 4.4.0
5427
	 * @param string $url URL to normalize.
5428
	 * @return WP_Error|string
5429
	 */
5430
	public static function normalize_url_protocol_agnostic( $url ) {
5431
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5432 View Code Duplication
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsed_url of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false 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...
5433
			/* translators: %s is an URL. */
5434
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5435
		}
5436
5437
		// Strip www and protocols.
5438
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5439
		return $url;
5440
	}
5441
5442
	/**
5443
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5444
	 *
5445
	 * @since 4.4.0
5446
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5447
	 *
5448
	 * @param array $response Response array.
5449
	 * @return array Array of the local urls, wpcom urls, and error code
5450
	 */
5451
	public static function get_sync_error_idc_option( $response = array() ) {
5452
		// Since the local options will hit the database directly, store the values
5453
		// in a transient to allow for autoloading and caching on subsequent views.
5454
		$local_options = get_transient( 'jetpack_idc_local' );
5455
		if ( false === $local_options ) {
5456
			$local_options = array(
5457
				'home'    => Functions::home_url(),
5458
				'siteurl' => Functions::site_url(),
5459
			);
5460
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
5461
		}
5462
5463
		$options = array_merge( $local_options, $response );
5464
5465
		$returned_values = array();
5466
		foreach ( $options as $key => $option ) {
5467
			if ( 'error_code' === $key ) {
5468
				$returned_values[ $key ] = $option;
5469
				continue;
5470
			}
5471
5472
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5473
				continue;
5474
			}
5475
5476
			$returned_values[ $key ] = $normalized_url;
5477
		}
5478
5479
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
5480
5481
		return $returned_values;
5482
	}
5483
5484
	/**
5485
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5486
	 * If set to true, the site will be put into staging mode.
5487
	 *
5488
	 * @since 4.3.2
5489
	 * @return bool
5490
	 */
5491
	public static function sync_idc_optin() {
5492
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5493
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5494
		} else {
5495
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5496
		}
5497
5498
		/**
5499
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
5500
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
5501
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5502
		 *
5503
		 * @since 4.3.2
5504
		 *
5505
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5506
		 */
5507
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5508
	}
5509
5510
	/**
5511
	 * Maybe Use a .min.css stylesheet, maybe not.
5512
	 *
5513
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5514
	 */
5515
	public static function maybe_min_asset( $url, $path, $plugin ) {
5516
		// Short out on things trying to find actual paths.
5517
		if ( ! $path || empty( $plugin ) ) {
5518
			return $url;
5519
		}
5520
5521
		$path = ltrim( $path, '/' );
5522
5523
		// Strip out the abspath.
5524
		$base = dirname( plugin_basename( $plugin ) );
5525
5526
		// Short out on non-Jetpack assets.
5527
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5528
			return $url;
5529
		}
5530
5531
		// File name parsing.
5532
		$file              = "{$base}/{$path}";
5533
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5534
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5535
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5536
		$extension         = array_shift( $file_name_parts_r );
5537
5538
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5539
			// Already pointing at the minified version.
5540
			if ( 'min' === $file_name_parts_r[0] ) {
5541
				return $url;
5542
			}
5543
5544
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5545
			if ( file_exists( $min_full_path ) ) {
5546
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5547
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
5548
				if ( 'css' === $extension ) {
5549
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
5550
					self::$min_assets[ $key ] = $path;
5551
				}
5552
			}
5553
		}
5554
5555
		return $url;
5556
	}
5557
5558
	/**
5559
	 * If the asset is minified, let's flag .min as the suffix.
5560
	 *
5561
	 * Attached to `style_loader_src` filter.
5562
	 *
5563
	 * @param string $src The tag that would link to the external asset.
5564
	 * @param string $handle The registered handle of the script in question.
5565
	 * @return string $href The url of the asset in question.
5566
	 */
5567
	public static function set_suffix_on_min( $src, $handle ) {
5568
		if ( false === strpos( $src, '.min.css' ) ) {
5569
			return $src;
5570
		}
5571
5572
		if ( ! empty( self::$min_assets ) ) {
5573
			foreach ( self::$min_assets as $file => $path ) {
5574
				if ( false !== strpos( $src, $file ) ) {
5575
					wp_style_add_data( $handle, 'suffix', '.min' );
5576
					return $src;
5577
				}
5578
			}
5579
		}
5580
5581
		return $src;
5582
	}
5583
5584
	/**
5585
	 * Maybe inlines a stylesheet.
5586
	 *
5587
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5588
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5589
	 *
5590
	 * Attached to `style_loader_tag` filter.
5591
	 *
5592
	 * @param string $tag The tag that would link to the external asset.
5593
	 * @param string $handle The registered handle of the script in question.
5594
	 *
5595
	 * @return string
5596
	 */
5597
	public static function maybe_inline_style( $tag, $handle ) {
5598
		global $wp_styles;
5599
		$item = $wp_styles->registered[ $handle ];
5600
5601
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5602
			return $tag;
5603
		}
5604
5605
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5606
			$href = $matches[1];
5607
			// Strip off query string.
5608
			if ( $pos = strpos( $href, '?' ) ) {
5609
				$href = substr( $href, 0, $pos );
5610
			}
5611
			// Strip off fragment.
5612
			if ( $pos = strpos( $href, '#' ) ) {
5613
				$href = substr( $href, 0, $pos );
5614
			}
5615
		} else {
5616
			return $tag;
5617
		}
5618
5619
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5620
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5621
			return $tag;
5622
		}
5623
5624
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5625
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5626
			// And this isn't the pass that actually deals with the RTL version...
5627
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5628
				// Short out, as the RTL version will deal with it in a moment.
5629
				return $tag;
5630
			}
5631
		}
5632
5633
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5634
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
5635
		if ( $css ) {
5636
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5637
			if ( empty( $item->extra['after'] ) ) {
5638
				wp_add_inline_style( $handle, $css );
5639
			} else {
5640
				array_unshift( $item->extra['after'], $css );
5641
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5642
			}
5643
		}
5644
5645
		return $tag;
5646
	}
5647
5648
	/**
5649
	 * Loads a view file from the views
5650
	 *
5651
	 * Data passed in with the $data parameter will be available in the
5652
	 * template file as $data['value']
5653
	 *
5654
	 * @param string $template Template file to load.
5655
	 *
5656
	 * @return boolean - If template file was found
5657
	 **/
5658
	public function load_view( $template ) {
5659
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
5660
5661
		if ( file_exists( $views_dir . $template ) ) {
5662
			require_once $views_dir . $template;
5663
			return true;
5664
		}
5665
5666
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
5667
		return false;
5668
	}
5669
5670
	/**
5671
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
5672
	 */
5673
	public function deprecated_hooks() {
5674
		$filter_deprecated_list = array(
5675
			'jetpack_bail_on_shortcode'                    => array(
5676
				'replacement' => 'jetpack_shortcodes_to_include',
5677
				'version'     => 'jetpack-3.1.0',
5678
			),
5679
			'wpl_sharing_2014_1'                           => array(
5680
				'replacement' => null,
5681
				'version'     => 'jetpack-3.6.0',
5682
			),
5683
			'jetpack-tools-to-include'                     => array(
5684
				'replacement' => 'jetpack_tools_to_include',
5685
				'version'     => 'jetpack-3.9.0',
5686
			),
5687
			'jetpack_identity_crisis_options_to_check'     => array(
5688
				'replacement' => null,
5689
				'version'     => 'jetpack-4.0.0',
5690
			),
5691
			'update_option_jetpack_single_user_site'       => array(
5692
				'replacement' => null,
5693
				'version'     => 'jetpack-4.3.0',
5694
			),
5695
			'audio_player_default_colors'                  => array(
5696
				'replacement' => null,
5697
				'version'     => 'jetpack-4.3.0',
5698
			),
5699
			'add_option_jetpack_featured_images_enabled'   => array(
5700
				'replacement' => null,
5701
				'version'     => 'jetpack-4.3.0',
5702
			),
5703
			'add_option_jetpack_update_details'            => array(
5704
				'replacement' => null,
5705
				'version'     => 'jetpack-4.3.0',
5706
			),
5707
			'add_option_jetpack_updates'                   => array(
5708
				'replacement' => null,
5709
				'version'     => 'jetpack-4.3.0',
5710
			),
5711
			'add_option_jetpack_network_name'              => array(
5712
				'replacement' => null,
5713
				'version'     => 'jetpack-4.3.0',
5714
			),
5715
			'add_option_jetpack_network_allow_new_registrations' => array(
5716
				'replacement' => null,
5717
				'version'     => 'jetpack-4.3.0',
5718
			),
5719
			'add_option_jetpack_network_add_new_users'     => array(
5720
				'replacement' => null,
5721
				'version'     => 'jetpack-4.3.0',
5722
			),
5723
			'add_option_jetpack_network_site_upload_space' => array(
5724
				'replacement' => null,
5725
				'version'     => 'jetpack-4.3.0',
5726
			),
5727
			'add_option_jetpack_network_upload_file_types' => array(
5728
				'replacement' => null,
5729
				'version'     => 'jetpack-4.3.0',
5730
			),
5731
			'add_option_jetpack_network_enable_administration_menus' => array(
5732
				'replacement' => null,
5733
				'version'     => 'jetpack-4.3.0',
5734
			),
5735
			'add_option_jetpack_is_multi_site'             => array(
5736
				'replacement' => null,
5737
				'version'     => 'jetpack-4.3.0',
5738
			),
5739
			'add_option_jetpack_is_main_network'           => array(
5740
				'replacement' => null,
5741
				'version'     => 'jetpack-4.3.0',
5742
			),
5743
			'add_option_jetpack_main_network_site'         => array(
5744
				'replacement' => null,
5745
				'version'     => 'jetpack-4.3.0',
5746
			),
5747
			'jetpack_sync_all_registered_options'          => array(
5748
				'replacement' => null,
5749
				'version'     => 'jetpack-4.3.0',
5750
			),
5751
			'jetpack_has_identity_crisis'                  => array(
5752
				'replacement' => 'jetpack_sync_error_idc_validation',
5753
				'version'     => 'jetpack-4.4.0',
5754
			),
5755
			'jetpack_is_post_mailable'                     => array(
5756
				'replacement' => null,
5757
				'version'     => 'jetpack-4.4.0',
5758
			),
5759
			'jetpack_seo_site_host'                        => array(
5760
				'replacement' => null,
5761
				'version'     => 'jetpack-5.1.0',
5762
			),
5763
			'jetpack_installed_plugin'                     => array(
5764
				'replacement' => 'jetpack_plugin_installed',
5765
				'version'     => 'jetpack-6.0.0',
5766
			),
5767
			'jetpack_holiday_snow_option_name'             => array(
5768
				'replacement' => null,
5769
				'version'     => 'jetpack-6.0.0',
5770
			),
5771
			'jetpack_holiday_chance_of_snow'               => array(
5772
				'replacement' => null,
5773
				'version'     => 'jetpack-6.0.0',
5774
			),
5775
			'jetpack_holiday_snow_js_url'                  => array(
5776
				'replacement' => null,
5777
				'version'     => 'jetpack-6.0.0',
5778
			),
5779
			'jetpack_is_holiday_snow_season'               => array(
5780
				'replacement' => null,
5781
				'version'     => 'jetpack-6.0.0',
5782
			),
5783
			'jetpack_holiday_snow_option_updated'          => array(
5784
				'replacement' => null,
5785
				'version'     => 'jetpack-6.0.0',
5786
			),
5787
			'jetpack_holiday_snowing'                      => array(
5788
				'replacement' => null,
5789
				'version'     => 'jetpack-6.0.0',
5790
			),
5791
			'jetpack_sso_auth_cookie_expirtation'          => array(
5792
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
5793
				'version'     => 'jetpack-6.1.0',
5794
			),
5795
			'jetpack_cache_plans'                          => array(
5796
				'replacement' => null,
5797
				'version'     => 'jetpack-6.1.0',
5798
			),
5799
5800
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
5801
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
5802
				'version'     => 'jetpack-6.5.0',
5803
			),
5804
			'jetpack_enable_site_verification'             => array(
5805
				'replacement' => null,
5806
				'version'     => 'jetpack-6.5.0',
5807
			),
5808
			'can_display_jetpack_manage_notice'            => array(
5809
				'replacement' => null,
5810
				'version'     => 'jetpack-7.3.0',
5811
			),
5812
			'atd_http_post_timeout'                        => array(
5813
				'replacement' => null,
5814
				'version'     => 'jetpack-7.3.0',
5815
			),
5816
			'atd_service_domain'                           => array(
5817
				'replacement' => null,
5818
				'version'     => 'jetpack-7.3.0',
5819
			),
5820
			'atd_load_scripts'                             => array(
5821
				'replacement' => null,
5822
				'version'     => 'jetpack-7.3.0',
5823
			),
5824
			'jetpack_widget_authors_exclude'               => array(
5825
				'replacement' => 'jetpack_widget_authors_params',
5826
				'version'     => 'jetpack-7.7.0',
5827
			),
5828
			// Removed in Jetpack 7.9.0.
5829
			'jetpack_pwa_manifest'                         => array(
5830
				'replacement' => null,
5831
				'version'     => 'jetpack-7.9.0',
5832
			),
5833
			'jetpack_pwa_background_color'                 => array(
5834
				'replacement' => null,
5835
				'version'     => 'jetpack-7.9.0',
5836
			),
5837
			'jetpack_check_mobile'                         => array(
5838
				'replacement' => null,
5839
				'version'     => 'jetpack-8.3.0',
5840
			),
5841
			'jetpack_mobile_stylesheet'                    => array(
5842
				'replacement' => null,
5843
				'version'     => 'jetpack-8.3.0',
5844
			),
5845
			'jetpack_mobile_template'                      => array(
5846
				'replacement' => null,
5847
				'version'     => 'jetpack-8.3.0',
5848
			),
5849
			'jetpack_mobile_theme_menu'                    => array(
5850
				'replacement' => null,
5851
				'version'     => 'jetpack-8.3.0',
5852
			),
5853
			'minileven_show_featured_images'               => array(
5854
				'replacement' => null,
5855
				'version'     => 'jetpack-8.3.0',
5856
			),
5857
			'minileven_attachment_size'                    => array(
5858
				'replacement' => null,
5859
				'version'     => 'jetpack-8.3.0',
5860
			),
5861
			'instagram_cache_oembed_api_response_body'     => array(
5862
				'replacement' => null,
5863
				'version'     => 'jetpack-9.1.0',
5864
			),
5865
			'jetpack_can_make_outbound_https'              => array(
5866
				'replacement' => null,
5867
				'version'     => 'jetpack-9.1.0',
5868
			),
5869
		);
5870
5871
		foreach ( $filter_deprecated_list as $tag => $args ) {
5872
			if ( has_filter( $tag ) ) {
5873
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
5874
			}
5875
		}
5876
5877
		$action_deprecated_list = array(
5878
			'jetpack_updated_theme'        => array(
5879
				'replacement' => 'jetpack_updated_themes',
5880
				'version'     => 'jetpack-6.2.0',
5881
			),
5882
			'atd_http_post_error'          => array(
5883
				'replacement' => null,
5884
				'version'     => 'jetpack-7.3.0',
5885
			),
5886
			'mobile_reject_mobile'         => array(
5887
				'replacement' => null,
5888
				'version'     => 'jetpack-8.3.0',
5889
			),
5890
			'mobile_force_mobile'          => array(
5891
				'replacement' => null,
5892
				'version'     => 'jetpack-8.3.0',
5893
			),
5894
			'mobile_app_promo_download'    => array(
5895
				'replacement' => null,
5896
				'version'     => 'jetpack-8.3.0',
5897
			),
5898
			'mobile_setup'                 => array(
5899
				'replacement' => null,
5900
				'version'     => 'jetpack-8.3.0',
5901
			),
5902
			'jetpack_mobile_footer_before' => array(
5903
				'replacement' => null,
5904
				'version'     => 'jetpack-8.3.0',
5905
			),
5906
			'wp_mobile_theme_footer'       => array(
5907
				'replacement' => null,
5908
				'version'     => 'jetpack-8.3.0',
5909
			),
5910
			'minileven_credits'            => array(
5911
				'replacement' => null,
5912
				'version'     => 'jetpack-8.3.0',
5913
			),
5914
			'jetpack_mobile_header_before' => array(
5915
				'replacement' => null,
5916
				'version'     => 'jetpack-8.3.0',
5917
			),
5918
			'jetpack_mobile_header_after'  => array(
5919
				'replacement' => null,
5920
				'version'     => 'jetpack-8.3.0',
5921
			),
5922
		);
5923
5924
		foreach ( $action_deprecated_list as $tag => $args ) {
5925
			if ( has_action( $tag ) ) {
5926
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
5927
			}
5928
		}
5929
	}
5930
5931
	/**
5932
	 * Converts any url in a stylesheet, to the correct absolute url.
5933
	 *
5934
	 * Considerations:
5935
	 *  - Normal, relative URLs     `feh.png`
5936
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
5937
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
5938
	 *  - Absolute URLs             `http://domain.com/feh.png`
5939
	 *  - Domain root relative URLs `/feh.png`
5940
	 *
5941
	 * @param string $css The raw CSS -- should be read in directly from the file.
5942
	 * @param string $css_file_url The URL that the file can be accessed at, for calculating paths from.
5943
	 *
5944
	 * @return mixed|string
5945
	 */
5946
	public static function absolutize_css_urls( $css, $css_file_url ) {
5947
		$pattern = '#url\((?P<path>[^)]*)\)#i';
5948
		$css_dir = dirname( $css_file_url );
5949
		$p       = wp_parse_url( $css_dir );
5950
		$domain  = sprintf(
5951
			'%1$s//%2$s%3$s%4$s',
5952
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
5953
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
5954
			$p['host'],
5955
			isset( $p['port'] ) ? ":{$p['port']}" : ''
5956
		);
5957
5958
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
5959
			$find = $replace = array();
5960
			foreach ( $matches as $match ) {
5961
				$url = trim( $match['path'], "'\" \t" );
5962
5963
				// If this is a data url, we don't want to mess with it.
5964
				if ( 'data:' === substr( $url, 0, 5 ) ) {
5965
					continue;
5966
				}
5967
5968
				// If this is an absolute or protocol-agnostic url,
5969
				// we don't want to mess with it.
5970
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
5971
					continue;
5972
				}
5973
5974
				switch ( substr( $url, 0, 1 ) ) {
5975
					case '/':
5976
						$absolute = $domain . $url;
5977
						break;
5978
					default:
5979
						$absolute = $css_dir . '/' . $url;
5980
				}
5981
5982
				$find[]    = $match[0];
5983
				$replace[] = sprintf( 'url("%s")', $absolute );
5984
			}
5985
			$css = str_replace( $find, $replace, $css );
5986
		}
5987
5988
		return $css;
5989
	}
5990
5991
	/**
5992
	 * This methods removes all of the registered css files on the front end
5993
	 * from Jetpack in favor of using a single file. In effect "imploding"
5994
	 * all the files into one file.
5995
	 *
5996
	 * Pros:
5997
	 * - Uses only ONE css asset connection instead of 15
5998
	 * - Saves a minimum of 56k
5999
	 * - Reduces server load
6000
	 * - Reduces time to first painted byte
6001
	 *
6002
	 * Cons:
6003
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6004
	 *      should not cause any issues with themes.
6005
	 * - Plugins/themes dequeuing styles no longer do anything. See
6006
	 *      jetpack_implode_frontend_css filter for a workaround
6007
	 *
6008
	 * For some situations developers may wish to disable css imploding and
6009
	 * instead operate in legacy mode where each file loads seperately and
6010
	 * can be edited individually or dequeued. This can be accomplished with
6011
	 * the following line:
6012
	 *
6013
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6014
	 *
6015
	 * @param bool $travis_test If this is a CI test.
6016
	 *
6017
	 * @since 3.2
6018
	 */
6019
	public function implode_frontend_css( $travis_test = false ) {
6020
		$do_implode = true;
6021
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6022
			$do_implode = false;
6023
		}
6024
6025
		// Do not implode CSS when the page loads via the AMP plugin.
6026
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6027
			$do_implode = false;
6028
		}
6029
6030
		/**
6031
		 * Allow CSS to be concatenated into a single jetpack.css file.
6032
		 *
6033
		 * @since 3.2.0
6034
		 *
6035
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6036
		 */
6037
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6038
6039
		// Do not use the imploded file when default behavior was altered through the filter.
6040
		if ( ! $do_implode ) {
6041
			return;
6042
		}
6043
6044
		// We do not want to use the imploded file in dev mode, or if not connected.
6045
		if ( ( new Status() )->is_offline_mode() || ! self::is_active() ) {
6046
			if ( ! $travis_test ) {
6047
				return;
6048
			}
6049
		}
6050
6051
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen.
6052
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6053
			return;
6054
		}
6055
6056
		/*
6057
		 * Now we assume Jetpack is connected and able to serve the single
6058
		 * file.
6059
		 *
6060
		 * In the future there will be a check here to serve the file locally
6061
		 * or potentially from the Jetpack CDN
6062
		 *
6063
		 * For now:
6064
		 * - Enqueue a single imploded css file
6065
		 * - Zero out the style_loader_tag for the bundled ones
6066
		 * - Be happy, drink scotch
6067
		 */
6068
6069
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6070
6071
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6072
6073
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6074
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6075
	}
6076
6077
	function concat_remove_style_loader_tag( $tag, $handle ) {
6078
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6079
			$tag = '';
6080
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6081
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6082
			}
6083
		}
6084
6085
		return $tag;
6086
	}
6087
6088
	/**
6089
	 * Check the heartbeat data
6090
	 *
6091
	 * Organizes the heartbeat data by severity.  For example, if the site
6092
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6093
	 *
6094
	 * Data will be added to "caution" array, if it either:
6095
	 *  - Out of date Jetpack version
6096
	 *  - Out of date WP version
6097
	 *  - Out of date PHP version
6098
	 *
6099
	 * $return array $filtered_data
6100
	 */
6101
	public static function jetpack_check_heartbeat_data() {
6102
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6103
6104
		$good    = array();
6105
		$caution = array();
6106
		$bad     = array();
6107
6108
		foreach ( $raw_data as $stat => $value ) {
6109
6110
			// Check jetpack version.
6111
			if ( 'version' == $stat ) {
6112
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6113
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6114
					continue;
6115
				}
6116
			}
6117
6118
			// Check WP version.
6119
			if ( 'wp-version' == $stat ) {
6120
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6121
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6122
					continue;
6123
				}
6124
			}
6125
6126
			// Check PHP version.
6127
			if ( 'php-version' == $stat ) {
6128
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6129
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6130
					continue;
6131
				}
6132
			}
6133
6134
			// Check ID crisis.
6135
			if ( 'identitycrisis' == $stat ) {
6136
				if ( 'yes' == $value ) {
6137
					$bad[ $stat ] = $value;
6138
					continue;
6139
				}
6140
			}
6141
6142
			// The rest are good :).
6143
			$good[ $stat ] = $value;
6144
		}
6145
6146
		$filtered_data = array(
6147
			'good'    => $good,
6148
			'caution' => $caution,
6149
			'bad'     => $bad,
6150
		);
6151
6152
		return $filtered_data;
6153
	}
6154
6155
	/**
6156
	 * This method is used to organize all options that can be reset
6157
	 * without disconnecting Jetpack.
6158
	 *
6159
	 * It is used in class.jetpack-cli.php to reset options
6160
	 *
6161
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6162
	 *
6163
	 * @return array of options to delete.
6164
	 */
6165
	public static function get_jetpack_options_for_reset() {
6166
		return Jetpack_Options::get_options_for_reset();
6167
	}
6168
6169
	/**
6170
	 * Sets up the JP Dashboard widgets
6171
	 */
6172
	public function wp_dashboard_setup() {
6173
		if ( self::is_active() ) {
6174
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6175
		}
6176
6177
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6178
			$jetpack_logo = new Jetpack_Logo();
6179
			$widget_title = sprintf(
6180
				/* translators: Placeholder is a Jetpack logo. */
6181
				__( 'Stats by %s', 'jetpack' ),
6182
				$jetpack_logo->get_jp_emblem( true )
6183
			);
6184
6185
			// Wrap title in span so Logo can be properly styled.
6186
			$widget_title = sprintf(
6187
				'<span>%s</span>',
6188
				$widget_title
6189
			);
6190
6191
			wp_add_dashboard_widget(
6192
				'jetpack_summary_widget',
6193
				$widget_title,
6194
				array( __CLASS__, 'dashboard_widget' )
6195
			);
6196
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6197
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6198
6199
			// If we're inactive and not in offline mode, sort our box to the top.
6200
			if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
6201
				global $wp_meta_boxes;
6202
6203
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6204
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6205
6206
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6207
			}
6208
		}
6209
	}
6210
6211
	/**
6212
	 * Get the meta box order for the dashboard
6213
	 *
6214
	 * @param mixed $sorted Value for the user's option.
6215
	 * @return mixed
6216
	 */
6217
	public function get_user_option_meta_box_order_dashboard( $sorted ) {
6218
		if ( ! is_array( $sorted ) ) {
6219
			return $sorted;
6220
		}
6221
6222
		foreach ( $sorted as $box_context => $ids ) {
6223
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6224
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6225
				continue;
6226
			}
6227
6228
			$ids_array = explode( ',', $ids );
6229
			$key       = array_search( 'dashboard_stats', $ids_array );
6230
6231
			if ( false !== $key ) {
6232
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example).
6233
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6234
				$sorted[ $box_context ] = implode( ',', $ids_array );
6235
				// We've found it, stop searching, and just return.
6236
				break;
6237
			}
6238
		}
6239
6240
		return $sorted;
6241
	}
6242
6243
	/**
6244
	 * Fires when the dashboard is loaded.
6245
	 */
6246
	public static function dashboard_widget() {
6247
		/**
6248
		 * Fires when the dashboard is loaded.
6249
		 *
6250
		 * @since 3.4.0
6251
		 */
6252
		do_action( 'jetpack_dashboard_widget' );
6253
	}
6254
6255
	/**
6256
	 * Displays dashboard widget footer
6257
	 */
6258
	public static function dashboard_widget_footer() {
6259
		?>
6260
		<footer>
6261
6262
		<div class="protect">
6263
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6264
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6265
				<p class="blocked-count">
6266
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6267
				</p>
6268
				<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>
6269
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
6270
				<a href="
6271
				<?php
6272
				echo esc_url(
6273
					wp_nonce_url(
6274
						self::admin_url(
6275
							array(
6276
								'action' => 'activate',
6277
								'module' => 'protect',
6278
							)
6279
						),
6280
						'jetpack_activate-protect'
6281
					)
6282
				);
6283
				?>
6284
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6285
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6286
				</a>
6287
			<?php else : ?>
6288
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6289
			<?php endif; ?>
6290
		</div>
6291
6292
		<div class="akismet">
6293
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6294
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6295
				<p class="blocked-count">
6296
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6297
				</p>
6298
				<p><?php echo esc_html_x( 'Blocked spam comments.', '{#} Spam comments blocked by Akismet -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
6299
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6300
				<a href="
6301
				<?php
6302
				echo esc_url(
6303
					wp_nonce_url(
6304
						add_query_arg(
6305
							array(
6306
								'action' => 'activate',
6307
								'plugin' => 'akismet/akismet.php',
6308
							),
6309
							admin_url( 'plugins.php' )
6310
						),
6311
						'activate-plugin_akismet/akismet.php'
6312
					)
6313
				);
6314
				?>
6315
							" class="button button-jetpack">
6316
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
6317
				</a>
6318
			<?php else : ?>
6319
				<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( 'Anti-spam can help to keep your blog safe from spam!', 'jetpack' ); ?></a></p>
6320
			<?php endif; ?>
6321
		</div>
6322
6323
		</footer>
6324
		<?php
6325
	}
6326
6327
	/**
6328
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6329
	 *
6330
	 * @param array $columns User list table columns.
6331
	 */
6332
	public function jetpack_icon_user_connected( $columns ) {
6333
		$columns['user_jetpack'] = '';
6334
		return $columns;
6335
	}
6336
6337
	/**
6338
	 * Show Jetpack icon if the user is linked.
6339
	 *
6340
	 * @param string     $val Icon.
6341
	 * @param string     $col Column on users table.
6342
	 * @param string|int $user_id User ID.
6343
	 *
6344
	 * @return string
6345
	 */
6346
	public function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6347
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
6348
			$jetpack_logo = new Jetpack_Logo();
6349
			$emblem_html  = sprintf(
6350
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6351
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6352
				$jetpack_logo->get_jp_emblem()
6353
			);
6354
			return $emblem_html;
6355
		}
6356
6357
		return $val;
6358
	}
6359
6360
	/**
6361
	 * Style the Jetpack user column
6362
	 */
6363
	public function jetpack_user_col_style() {
6364
		global $current_screen;
6365
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6366
			?>
6367
			<style>
6368
				.fixed .column-user_jetpack {
6369
					width: 21px;
6370
				}
6371
				.jp-emblem-user-admin svg {
6372
					width: 20px;
6373
					height: 20px;
6374
				}
6375
				.jp-emblem-user-admin path {
6376
					fill: #00BE28;
6377
				}
6378
			</style>
6379
			<?php
6380
		}
6381
	}
6382
6383
	/**
6384
	 * Checks if Akismet is active and working.
6385
	 *
6386
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6387
	 * that implied usage of methods present since more recent version.
6388
	 * See https://github.com/Automattic/jetpack/pull/9585
6389
	 *
6390
	 * @since  5.1.0
6391
	 *
6392
	 * @return bool True = Akismet available. False = Aksimet not available.
6393
	 */
6394
	public static function is_akismet_active() {
6395
		static $status = null;
6396
6397
		if ( ! is_null( $status ) ) {
6398
			return $status;
6399
		}
6400
6401
		// Check if a modern version of Akismet is active.
6402
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6403
			$status = false;
6404
			return $status;
6405
		}
6406
6407
		// Make sure there is a key known to Akismet at all before verifying key.
6408
		$akismet_key = Akismet::get_api_key();
6409
		if ( ! $akismet_key ) {
6410
			$status = false;
6411
			return $status;
6412
		}
6413
6414
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6415
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6416
6417
		// 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.
6418
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6419
		// We cache the result of the Akismet key verification for ten minutes.
6420
		if ( ! $akismet_key_state || $recheck ) {
6421
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6422
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6423
		}
6424
6425
		$status = 'valid' === $akismet_key_state;
6426
6427
		return $status;
6428
	}
6429
6430
	/**
6431
	 * Given a minified path, and a non-minified path, will return
6432
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6433
	 *
6434
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6435
	 * root Jetpack directory.
6436
	 *
6437
	 * @since 5.6.0
6438
	 *
6439
	 * @param string $min_path Minimized path.
6440
	 * @param string $non_min_path Source path.
6441
	 *
6442
	 * @return string The URL to the file
6443
	 */
6444
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6445
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6446
	}
6447
6448
	/**
6449
	 * Checks for whether Jetpack Backup is enabled.
6450
	 * Will return true if the state of Backup is anything except "unavailable".
6451
	 *
6452
	 * @return bool|int|mixed
6453
	 */
6454
	public static function is_rewind_enabled() {
6455
		if ( ! self::is_active() ) {
6456
			return false;
6457
		}
6458
6459
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6460
		if ( false === $rewind_enabled ) {
6461
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6462
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6463
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6464
				&& ! empty( $rewind_data['state'] )
6465
				&& 'active' === $rewind_data['state'] )
6466
				? 1
6467
				: 0;
6468
6469
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6470
		}
6471
		return $rewind_enabled;
6472
	}
6473
6474
	/**
6475
	 * Return Calypso environment value; used for developing Jetpack and pairing
6476
	 * it with different Calypso enrionments, such as localhost.
6477
	 *
6478
	 * @since 7.4.0
6479
	 *
6480
	 * @return string Calypso environment
6481
	 */
6482
	public static function get_calypso_env() {
6483
		if ( isset( $_GET['calypso_env'] ) ) {
6484
			return sanitize_key( $_GET['calypso_env'] );
6485
		}
6486
6487
		if ( getenv( 'CALYPSO_ENV' ) ) {
6488
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6489
		}
6490
6491
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6492
			return sanitize_key( CALYPSO_ENV );
6493
		}
6494
6495
		return '';
6496
	}
6497
6498
	/**
6499
	 * Returns the hostname with protocol for Calypso.
6500
	 * Used for developing Jetpack with Calypso.
6501
	 *
6502
	 * @since 8.4.0
6503
	 *
6504
	 * @return string Calypso host.
6505
	 */
6506
	public static function get_calypso_host() {
6507
		$calypso_env = self::get_calypso_env();
6508
		switch ( $calypso_env ) {
6509
			case 'development':
6510
				return 'http://calypso.localhost:3000/';
6511
			case 'wpcalypso':
6512
				return 'https://wpcalypso.wordpress.com/';
6513
			case 'horizon':
6514
				return 'https://horizon.wordpress.com/';
6515
			default:
6516
				return 'https://wordpress.com/';
6517
		}
6518
	}
6519
6520
	/**
6521
	 * Handles activating default modules as well general cleanup for the new connection.
6522
	 *
6523
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6524
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6525
	 * @param boolean $send_state_messages          Whether to send state messages.
6526
	 * @return void
6527
	 */
6528
	public static function handle_post_authorization_actions(
6529
		$activate_sso = false,
6530
		$redirect_on_activation_error = false,
6531
		$send_state_messages = true
6532
	) {
6533
		$other_modules = $activate_sso
6534
			? array( 'sso' )
6535
			: array();
6536
6537
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
6538
6539
		if ( $active_modules ) {
6540
			self::delete_active_modules();
6541
6542
			self::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...
6543
		} else {
6544
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6545
		}
6546
6547
		// Since this is a fresh connection, be sure to clear out IDC options.
6548
		Jetpack_IDC::clear_all_idc_options();
6549
6550
		if ( $send_state_messages ) {
6551
			self::state( 'message', 'authorized' );
6552
		}
6553
	}
6554
6555
	/**
6556
	 * Returns a boolean for whether backups UI should be displayed or not.
6557
	 *
6558
	 * @return bool Should backups UI be displayed?
6559
	 */
6560
	public static function show_backups_ui() {
6561
		/**
6562
		 * Whether UI for backups should be displayed.
6563
		 *
6564
		 * @since 6.5.0
6565
		 *
6566
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6567
		 */
6568
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6569
	}
6570
6571
	/**
6572
	 * Clean leftoveruser meta.
6573
	 *
6574
	 * Delete Jetpack-related user meta when it is no longer needed.
6575
	 *
6576
	 * @since 7.3.0
6577
	 *
6578
	 * @param int $user_id User ID being updated.
6579
	 */
6580
	public static function user_meta_cleanup( $user_id ) {
6581
		$meta_keys = array(
6582
			// AtD removed from Jetpack 7.3.
6583
			'AtD_options',
6584
			'AtD_check_when',
6585
			'AtD_guess_lang',
6586
			'AtD_ignored_phrases',
6587
		);
6588
6589
		foreach ( $meta_keys as $meta_key ) {
6590
			if ( get_user_meta( $user_id, $meta_key ) ) {
6591
				delete_user_meta( $user_id, $meta_key );
6592
			}
6593
		}
6594
	}
6595
6596
	/**
6597
	 * Checks if a Jetpack site is both active and not in offline mode.
6598
	 *
6599
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
6600
	 *
6601
	 * @since 8.8.0
6602
	 *
6603
	 * @return bool True if Jetpack is active and not in offline mode.
6604
	 */
6605
	public static function is_active_and_not_offline_mode() {
6606
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
6607
			return false;
6608
		}
6609
		return true;
6610
	}
6611
6612
	/**
6613
	 * Returns the list of products that we have available for purchase.
6614
	 */
6615
	public static function get_products_for_purchase() {
6616
		$products = array();
6617
		if ( ! is_multisite() ) {
6618
			$products[] = array(
6619
				'key'               => 'backup',
6620
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
6621
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
6622
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
6623
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
6624
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
6625
				'options'           => array(
6626
					array(
6627
						'type'        => 'daily',
6628
						'slug'        => 'jetpack-backup-daily',
6629
						'key'         => 'jetpack_backup_daily',
6630
						'name'        => __( 'Daily Backups', 'jetpack' ),
6631
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
6632
					),
6633
					array(
6634
						'type'        => 'realtime',
6635
						'slug'        => 'jetpack-backup-realtime',
6636
						'key'         => 'jetpack_backup_realtime',
6637
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
6638
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
6639
					),
6640
				),
6641
				'default_option'    => 'realtime',
6642
				'show_promotion'    => true,
6643
				'discount_percent'  => 70,
6644
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
6645
			);
6646
6647
			$products[] = array(
6648
				'key'               => 'scan',
6649
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
6650
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
6651
				'learn_more'        => __( 'Learn More', 'jetpack' ),
6652
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
6653
				'show_promotion'    => true,
6654
				'discount_percent'  => 30,
6655
				'options'           => array(
6656
					array(
6657
						'type' => 'scan',
6658
						'slug' => 'jetpack-scan',
6659
						'key'  => 'jetpack_scan',
6660
						'name' => __( 'Daily Scan', 'jetpack' ),
6661
					),
6662
				),
6663
				'default_option'    => 'scan',
6664
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
6665
			);
6666
		}
6667
6668
		$products[] = array(
6669
			'key'               => 'search',
6670
			'title'             => __( 'Jetpack Search', 'jetpack' ),
6671
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
6672
			'learn_more'        => __( 'Learn More', 'jetpack' ),
6673
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
6674
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
6675
			'options'           => array(
6676
				array(
6677
					'type' => 'search',
6678
					'slug' => 'jetpack-search',
6679
					'key'  => 'jetpack_search',
6680
					'name' => __( 'Search', 'jetpack' ),
6681
				),
6682
			),
6683
			'tears'             => array(),
6684
			'default_option'    => 'search',
6685
			'show_promotion'    => false,
6686
			'included_in_plans' => array( 'search-plan' ),
6687
		);
6688
6689
		$products[] = array(
6690
			'key'               => 'anti-spam',
6691
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
6692
			'short_description' => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
6693
			'learn_more'        => __( 'Learn More', 'jetpack' ),
6694
			'description'       => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
6695
			'options'           => array(
6696
				array(
6697
					'type' => 'anti-spam',
6698
					'slug' => 'jetpack-anti-spam',
6699
					'key'  => 'jetpack_anti_spam',
6700
					'name' => __( 'Anti-Spam', 'jetpack' ),
6701
				),
6702
			),
6703
			'default_option'    => 'anti-spam',
6704
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
6705
		);
6706
6707
		return $products;
6708
	}
6709
}
6710