Completed
Push — update/use-identity-crisis-pac... ( d14b6d...6e141b )
by
unknown
128:58 queued 119:18
created

Jetpack::get_module()   F

Complexity

Conditions 14
Paths 1026

Size

Total Lines 100

Duplication

Lines 12
Ratio 12 %

Importance

Changes 0
Metric Value
cc 14
nc 1026
nop 1
dl 12
loc 100
rs 1.68
c 0
b 0
f 0

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

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...
939
	 */
940 View Code Duplication
	public function setup_xmlrpc_handlers(
941
		$request_params,
942
		$is_active,
943
		$is_signed,
944
		Jetpack_XMLRPC_Server $xmlrpc_server = null
945
	) {
946
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
947
948
		if ( ! $this->connection_manager ) {
949
			$this->connection_manager = new Connection_Manager();
950
		}
951
952
		return $this->connection_manager->setup_xmlrpc_handlers(
953
			$request_params,
954
			$is_active,
955
			$is_signed,
956
			$xmlrpc_server
957
		);
958
	}
959
960
	/**
961
	 * Initialize REST API registration connector.
962
	 *
963
	 * @deprecated since 7.7.0
964
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
965
	 */
966 View Code Duplication
	public function initialize_rest_api_registration_connector() {
967
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
968
969
		if ( ! $this->connection_manager ) {
970
			$this->connection_manager = new Connection_Manager();
971
		}
972
973
		$this->connection_manager->initialize_rest_api_registration_connector();
974
	}
975
976
	/**
977
	 * This is ported over from the manage module, which has been deprecated and baked in here.
978
	 *
979
	 * @param $domains
980
	 */
981
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
982
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
983
	}
984
985
	/**
986
	 * Return $domains, with 'wordpress.com' appended.
987
	 * This is ported over from the manage module, which has been deprecated and baked in here.
988
	 *
989
	 * @param $domains
990
	 * @return array
991
	 */
992
	function allow_wpcom_domain( $domains ) {
993
		if ( empty( $domains ) ) {
994
			$domains = array();
995
		}
996
		$domains[] = 'wordpress.com';
997
		return array_unique( $domains );
998
	}
999
1000
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
1001
		$post = get_post( $post_id );
1002
1003
		if ( empty( $post ) ) {
1004
			return $default_url;
1005
		}
1006
1007
		$post_type = $post->post_type;
1008
1009
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1010
		// https://en.support.wordpress.com/custom-post-types/
1011
		$allowed_post_types = array(
1012
			'post',
1013
			'page',
1014
			'jetpack-portfolio',
1015
			'jetpack-testimonial',
1016
		);
1017
1018
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1019
			return $default_url;
1020
		}
1021
1022
		return Redirect::get_url(
1023
			'calypso-edit-' . $post_type,
1024
			array(
1025
				'path' => $post_id,
1026
			)
1027
		);
1028
	}
1029
1030
	function point_edit_comment_links_to_calypso( $url ) {
1031
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1032
		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...
1033
1034
		return Redirect::get_url(
1035
			'calypso-edit-comment',
1036
			array(
1037
				'path' => $query_args['amp;c'],
1038
			)
1039
		);
1040
1041
	}
1042
1043
	/**
1044
	 * Extend Sync callables with Jetpack Plugin functions.
1045
	 *
1046
	 * @param array $callables list of callables.
1047
	 *
1048
	 * @return array list of callables.
1049
	 */
1050
	public function filter_sync_callable_whitelist( $callables ) {
1051
1052
		// Jetpack Functions.
1053
		$jetpack_callables = array(
1054
			'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
1055
			'updates'                  => array( 'Jetpack', 'get_updates' ),
1056
			'active_modules'           => array( 'Jetpack', 'get_active_modules' ),
1057
			'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1058
		);
1059
		$callables         = array_merge( $callables, $jetpack_callables );
1060
1061
		// Jetpack_SSO_Helpers.
1062
		if ( include_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' ) {
1063
			$sso_helpers = array(
1064
				'sso_is_two_step_required'      => array( 'Jetpack_SSO_Helpers', 'is_two_step_required' ),
1065
				'sso_should_hide_login_form'    => array( 'Jetpack_SSO_Helpers', 'should_hide_login_form' ),
1066
				'sso_match_by_email'            => array( 'Jetpack_SSO_Helpers', 'match_by_email' ),
1067
				'sso_new_user_override'         => array( 'Jetpack_SSO_Helpers', 'new_user_override' ),
1068
				'sso_bypass_default_login_form' => array( 'Jetpack_SSO_Helpers', 'bypass_login_forward_wpcom' ),
1069
			);
1070
			$callables   = array_merge( $callables, $sso_helpers );
1071
		}
1072
1073
		return $callables;
1074
	}
1075
1076
	/**
1077
	 * Extend Sync multisite callables with Jetpack Plugin functions.
1078
	 *
1079
	 * @param array $callables list of callables.
1080
	 *
1081
	 * @return array list of callables.
1082
	 */
1083
	public function filter_sync_multisite_callable_whitelist( $callables ) {
1084
1085
		// Jetpack Funtions.
1086
		$jetpack_multisite_callables = array(
1087
			'network_name'                        => array( 'Jetpack', 'network_name' ),
1088
			'network_allow_new_registrations'     => array( 'Jetpack', 'network_allow_new_registrations' ),
1089
			'network_add_new_users'               => array( 'Jetpack', 'network_add_new_users' ),
1090
			'network_site_upload_space'           => array( 'Jetpack', 'network_site_upload_space' ),
1091
			'network_upload_file_types'           => array( 'Jetpack', 'network_upload_file_types' ),
1092
			'network_enable_administration_menus' => array( 'Jetpack', 'network_enable_administration_menus' ),
1093
		);
1094
		$callables                   = array_merge( $callables, $jetpack_multisite_callables );
1095
1096
		return $callables;
1097
	}
1098
1099
	function jetpack_track_last_sync_callback( $params ) {
1100
		/**
1101
		 * Filter to turn off jitm caching
1102
		 *
1103
		 * @since 5.4.0
1104
		 *
1105
		 * @param bool false Whether to cache just in time messages
1106
		 */
1107
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1108
			return $params;
1109
		}
1110
1111
		if ( is_array( $params ) && isset( $params[0] ) ) {
1112
			$option = $params[0];
1113
			if ( 'active_plugins' === $option ) {
1114
				// use the cache if we can, but not terribly important if it gets evicted
1115
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1116
			}
1117
		}
1118
1119
		return $params;
1120
	}
1121
1122
	function jetpack_connection_banner_callback() {
1123
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1124
1125
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1126
		if (
1127
			isset( $_REQUEST['dismissBanner'] ) &&
1128
			! Jetpack_Connection_Banner::force_display()
1129
		) {
1130
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1131
			wp_send_json_success();
1132
		}
1133
1134
		wp_die();
1135
	}
1136
1137
	/**
1138
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1139
	 * Only used in our alternate XML-RPC endpoint, where we want to
1140
	 * ensure that Core and other plugins' methods are not exposed.
1141
	 *
1142
	 * @deprecated since 7.7.0
1143
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1144
	 *
1145
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1146
	 * @return array Filtered $methods
1147
	 */
1148 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1149
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1150
1151
		if ( ! $this->connection_manager ) {
1152
			$this->connection_manager = new Connection_Manager();
1153
		}
1154
1155
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1156
	}
1157
1158
	/**
1159
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1160
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1161
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1162
	 * which is accessible via a different URI. Most of the below is copied directly
1163
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1164
	 *
1165
	 * @deprecated since 7.7.0
1166
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1167
	 */
1168 View Code Duplication
	public function alternate_xmlrpc() {
1169
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1170
1171
		if ( ! $this->connection_manager ) {
1172
			$this->connection_manager = new Connection_Manager();
1173
		}
1174
1175
		$this->connection_manager->alternate_xmlrpc();
1176
	}
1177
1178
	/**
1179
	 * The callback for the JITM ajax requests.
1180
	 *
1181
	 * @deprecated since 7.9.0
1182
	 */
1183
	function jetpack_jitm_ajax_callback() {
1184
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1185
	}
1186
1187
	/**
1188
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1189
	 */
1190
	function push_stats() {
1191
		if ( ! empty( $this->stats ) ) {
1192
			$this->do_stats( 'server_side' );
1193
		}
1194
	}
1195
1196
	/**
1197
	 * Sets the Jetpack custom capabilities.
1198
	 *
1199
	 * @param string[] $caps    Array of the user's capabilities.
1200
	 * @param string   $cap     Capability name.
1201
	 * @param int      $user_id The user ID.
1202
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1203
	 */
1204
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1205
		switch ( $cap ) {
1206
			case 'jetpack_manage_modules':
1207
			case 'jetpack_activate_modules':
1208
			case 'jetpack_deactivate_modules':
1209
				$caps = array( 'manage_options' );
1210
				break;
1211
			case 'jetpack_configure_modules':
1212
				$caps = array( 'manage_options' );
1213
				break;
1214
			case 'jetpack_manage_autoupdates':
1215
				$caps = array(
1216
					'manage_options',
1217
					'update_plugins',
1218
				);
1219
				break;
1220
			case 'jetpack_network_admin_page':
1221
			case 'jetpack_network_settings_page':
1222
				$caps = array( 'manage_network_plugins' );
1223
				break;
1224
			case 'jetpack_network_sites_page':
1225
				$caps = array( 'manage_sites' );
1226
				break;
1227 View Code Duplication
			case 'jetpack_admin_page':
1228
				$is_offline_mode = ( new Status() )->is_offline_mode();
1229
				if ( $is_offline_mode ) {
1230
					$caps = array( 'manage_options' );
1231
					break;
1232
				} else {
1233
					$caps = array( 'read' );
1234
				}
1235
				break;
1236
		}
1237
		return $caps;
1238
	}
1239
1240
	/**
1241
	 * Require a Jetpack authentication.
1242
	 *
1243
	 * @deprecated since 7.7.0
1244
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1245
	 */
1246 View Code Duplication
	public function require_jetpack_authentication() {
1247
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1248
1249
		if ( ! $this->connection_manager ) {
1250
			$this->connection_manager = new Connection_Manager();
1251
		}
1252
1253
		$this->connection_manager->require_jetpack_authentication();
1254
	}
1255
1256
	/**
1257
	 * Register assets for use in various modules and the Jetpack admin page.
1258
	 *
1259
	 * @uses wp_script_is, wp_register_script, plugins_url
1260
	 * @action wp_loaded
1261
	 * @return null
1262
	 */
1263
	public function register_assets() {
1264 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1265
			wp_register_script(
1266
				'jetpack-gallery-settings',
1267
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1268
				array( 'media-views' ),
1269
				'20121225'
1270
			);
1271
		}
1272
1273
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1274
			wp_register_script(
1275
				'jetpack-twitter-timeline',
1276
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1277
				array( 'jquery' ),
1278
				'4.0.0',
1279
				true
1280
			);
1281
		}
1282
1283
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1284
			wp_register_script(
1285
				'jetpack-facebook-embed',
1286
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1287
				array(),
1288
				null,
1289
				true
1290
			);
1291
1292
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1293
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1294
			if ( ! is_numeric( $fb_app_id ) ) {
1295
				$fb_app_id = '';
1296
			}
1297
			wp_localize_script(
1298
				'jetpack-facebook-embed',
1299
				'jpfbembed',
1300
				array(
1301
					'appid'  => $fb_app_id,
1302
					'locale' => $this->get_locale(),
1303
				)
1304
			);
1305
		}
1306
1307
		/**
1308
		 * As jetpack_register_genericons is by default fired off a hook,
1309
		 * the hook may have already fired by this point.
1310
		 * So, let's just trigger it manually.
1311
		 */
1312
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1313
		jetpack_register_genericons();
1314
1315
		/**
1316
		 * Register the social logos
1317
		 */
1318
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1319
		jetpack_register_social_logos();
1320
1321
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1322
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1323
		}
1324
	}
1325
1326
	/**
1327
	 * Guess locale from language code.
1328
	 *
1329
	 * @param string $lang Language code.
1330
	 * @return string|bool
1331
	 */
1332 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1333
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1334
			return 'en_US';
1335
		}
1336
1337
		if ( ! class_exists( 'GP_Locales' ) ) {
1338
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1339
				return false;
1340
			}
1341
1342
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1343
		}
1344
1345
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1346
			// WP.com: get_locale() returns 'it'
1347
			$locale = GP_Locales::by_slug( $lang );
1348
		} else {
1349
			// Jetpack: get_locale() returns 'it_IT';
1350
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1351
		}
1352
1353
		if ( ! $locale ) {
1354
			return false;
1355
		}
1356
1357
		if ( empty( $locale->facebook_locale ) ) {
1358
			if ( empty( $locale->wp_locale ) ) {
1359
				return false;
1360
			} else {
1361
				// Facebook SDK is smart enough to fall back to en_US if a
1362
				// locale isn't supported. Since supported Facebook locales
1363
				// can fall out of sync, we'll attempt to use the known
1364
				// wp_locale value and rely on said fallback.
1365
				return $locale->wp_locale;
1366
			}
1367
		}
1368
1369
		return $locale->facebook_locale;
1370
	}
1371
1372
	/**
1373
	 * Get the locale.
1374
	 *
1375
	 * @return string|bool
1376
	 */
1377
	function get_locale() {
1378
		$locale = $this->guess_locale_from_lang( get_locale() );
1379
1380
		if ( ! $locale ) {
1381
			$locale = 'en_US';
1382
		}
1383
1384
		return $locale;
1385
	}
1386
1387
	/**
1388
	 * Return the network_site_url so that .com knows what network this site is a part of.
1389
	 *
1390
	 * @param  bool $option
1391
	 * @return string
1392
	 */
1393
	public function jetpack_main_network_site_option( $option ) {
1394
		return network_site_url();
1395
	}
1396
	/**
1397
	 * Network Name.
1398
	 */
1399
	static function network_name( $option = null ) {
1400
		global $current_site;
1401
		return $current_site->site_name;
1402
	}
1403
	/**
1404
	 * Does the network allow new user and site registrations.
1405
	 *
1406
	 * @return string
1407
	 */
1408
	static function network_allow_new_registrations( $option = null ) {
1409
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1410
	}
1411
	/**
1412
	 * Does the network allow admins to add new users.
1413
	 *
1414
	 * @return boolian
1415
	 */
1416
	static function network_add_new_users( $option = null ) {
1417
		return (bool) get_site_option( 'add_new_users' );
1418
	}
1419
	/**
1420
	 * File upload psace left per site in MB.
1421
	 *  -1 means NO LIMIT.
1422
	 *
1423
	 * @return number
1424
	 */
1425
	static function network_site_upload_space( $option = null ) {
1426
		// value in MB
1427
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1428
	}
1429
1430
	/**
1431
	 * Network allowed file types.
1432
	 *
1433
	 * @return string
1434
	 */
1435
	static function network_upload_file_types( $option = null ) {
1436
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1437
	}
1438
1439
	/**
1440
	 * Maximum file upload size set by the network.
1441
	 *
1442
	 * @return number
1443
	 */
1444
	static function network_max_upload_file_size( $option = null ) {
1445
		// value in KB
1446
		return get_site_option( 'fileupload_maxk', 300 );
1447
	}
1448
1449
	/**
1450
	 * Lets us know if a site allows admins to manage the network.
1451
	 *
1452
	 * @return array
1453
	 */
1454
	static function network_enable_administration_menus( $option = null ) {
1455
		return get_site_option( 'menu_items' );
1456
	}
1457
1458
	/**
1459
	 * If a user has been promoted to or demoted from admin, we need to clear the
1460
	 * jetpack_other_linked_admins transient.
1461
	 *
1462
	 * @since 4.3.2
1463
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1464
	 *
1465
	 * @param int    $user_id   The user ID whose role changed.
1466
	 * @param string $role      The new role.
1467
	 * @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...
1468
	 */
1469
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1470
		if ( 'administrator' == $role
1471
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1472
			|| is_null( $old_roles )
1473
		) {
1474
			delete_transient( 'jetpack_other_linked_admins' );
1475
		}
1476
	}
1477
1478
	/**
1479
	 * Checks to see if there are any other users available to become primary
1480
	 * Users must both:
1481
	 * - Be linked to wpcom
1482
	 * - Be an admin
1483
	 *
1484
	 * @return mixed False if no other users are linked, Int if there are.
1485
	 */
1486
	static function get_other_linked_admins() {
1487
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1488
1489
		if ( false === $other_linked_users ) {
1490
			$admins = get_users( array( 'role' => 'administrator' ) );
1491
			if ( count( $admins ) > 1 ) {
1492
				$available = array();
1493
				foreach ( $admins as $admin ) {
1494
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1495
						$available[] = $admin->ID;
1496
					}
1497
				}
1498
1499
				$count_connected_admins = count( $available );
1500
				if ( count( $available ) > 1 ) {
1501
					$other_linked_users = $count_connected_admins;
1502
				} else {
1503
					$other_linked_users = 0;
1504
				}
1505
			} else {
1506
				$other_linked_users = 0;
1507
			}
1508
1509
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1510
		}
1511
1512
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1513
	}
1514
1515
	/**
1516
	 * Return whether we are dealing with a multi network setup or not.
1517
	 * The reason we are type casting this is because we want to avoid the situation where
1518
	 * the result is false since when is_main_network_option return false it cases
1519
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1520
	 * database which could be set to anything as opposed to what this function returns.
1521
	 *
1522
	 * @param  bool $option
1523
	 *
1524
	 * @return boolean
1525
	 */
1526
	public function is_main_network_option( $option ) {
1527
		// return '1' or ''
1528
		return (string) (bool) self::is_multi_network();
1529
	}
1530
1531
	/**
1532
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1533
	 *
1534
	 * @param  string $option
1535
	 * @return boolean
1536
	 */
1537
	public function is_multisite( $option ) {
1538
		return (string) (bool) is_multisite();
1539
	}
1540
1541
	/**
1542
	 * Implemented since there is no core is multi network function
1543
	 * Right now there is no way to tell if we which network is the dominant network on the system
1544
	 *
1545
	 * @since  3.3
1546
	 * @return boolean
1547
	 */
1548 View Code Duplication
	public static function is_multi_network() {
1549
		global  $wpdb;
1550
1551
		// if we don't have a multi site setup no need to do any more
1552
		if ( ! is_multisite() ) {
1553
			return false;
1554
		}
1555
1556
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1557
		if ( $num_sites > 1 ) {
1558
			return true;
1559
		} else {
1560
			return false;
1561
		}
1562
	}
1563
1564
	/**
1565
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1566
	 *
1567
	 * @return null
1568
	 */
1569
	function update_jetpack_main_network_site_option() {
1570
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1571
	}
1572
	/**
1573
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1574
	 */
1575
	function update_jetpack_network_settings() {
1576
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1577
		// Only sync this info for the main network site.
1578
	}
1579
1580
	/**
1581
	 * Get back if the current site is single user site.
1582
	 *
1583
	 * @return bool
1584
	 */
1585 View Code Duplication
	public static function is_single_user_site() {
1586
		global $wpdb;
1587
1588
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1589
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1590
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1591
		}
1592
		return 1 === (int) $some_users;
1593
	}
1594
1595
	/**
1596
	 * Returns true if the site has file write access false otherwise.
1597
	 *
1598
	 * @return string ( '1' | '0' )
1599
	 **/
1600
	public static function file_system_write_access() {
1601
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1602
			require_once ABSPATH . 'wp-admin/includes/file.php';
1603
		}
1604
1605
		require_once ABSPATH . 'wp-admin/includes/template.php';
1606
1607
		$filesystem_method = get_filesystem_method();
1608
		if ( $filesystem_method === 'direct' ) {
1609
			return 1;
1610
		}
1611
1612
		ob_start();
1613
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1614
		ob_end_clean();
1615
		if ( $filesystem_credentials_are_stored ) {
1616
			return 1;
1617
		}
1618
		return 0;
1619
	}
1620
1621
	/**
1622
	 * Finds out if a site is using a version control system.
1623
	 *
1624
	 * @return string ( '1' | '0' )
1625
	 **/
1626
	public static function is_version_controlled() {
1627
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1628
		return (string) (int) Functions::is_version_controlled();
1629
	}
1630
1631
	/**
1632
	 * Determines whether the current theme supports featured images or not.
1633
	 *
1634
	 * @return string ( '1' | '0' )
1635
	 */
1636
	public static function featured_images_enabled() {
1637
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1638
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1639
	}
1640
1641
	/**
1642
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1643
	 *
1644
	 * @deprecated 4.7 use get_avatar_url instead.
1645
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1646
	 * @param int               $size Size of the avatar image
1647
	 * @param string            $default URL to a default image to use if no avatar is available
1648
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1649
	 *
1650
	 * @return array
1651
	 */
1652
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1653
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1654
		return get_avatar_url(
1655
			$id_or_email,
1656
			array(
1657
				'size'          => $size,
1658
				'default'       => $default,
1659
				'force_default' => $force_display,
1660
			)
1661
		);
1662
	}
1663
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1664
	/**
1665
	 * jetpack_updates is saved in the following schema:
1666
	 *
1667
	 * array (
1668
	 *      'plugins'                       => (int) Number of plugin updates available.
1669
	 *      'themes'                        => (int) Number of theme updates available.
1670
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1671
	 *      'translations'                  => (int) Number of translation updates available.
1672
	 *      'total'                         => (int) Total of all available updates.
1673
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1674
	 * )
1675
	 *
1676
	 * @return array
1677
	 */
1678
	public static function get_updates() {
1679
		$update_data = wp_get_update_data();
1680
1681
		// Stores the individual update counts as well as the total count.
1682
		if ( isset( $update_data['counts'] ) ) {
1683
			$updates = $update_data['counts'];
1684
		}
1685
1686
		// If we need to update WordPress core, let's find the latest version number.
1687 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1688
			$cur = get_preferred_from_update_core();
1689
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1690
				$updates['wp_update_version'] = $cur->current;
1691
			}
1692
		}
1693
		return isset( $updates ) ? $updates : array();
1694
	}
1695
	// phpcs:enable
1696
1697
	public static function get_update_details() {
1698
		$update_details = array(
1699
			'update_core'    => get_site_transient( 'update_core' ),
1700
			'update_plugins' => get_site_transient( 'update_plugins' ),
1701
			'update_themes'  => get_site_transient( 'update_themes' ),
1702
		);
1703
		return $update_details;
1704
	}
1705
1706
	public static function refresh_update_data() {
1707
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1708
1709
	}
1710
1711
	public static function refresh_theme_data() {
1712
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1713
	}
1714
1715
	/**
1716
	 * Is Jetpack active?
1717
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1718
	 *
1719
	 * @return bool
1720
	 */
1721
	public static function is_active() {
1722
		return self::connection()->is_active();
1723
	}
1724
1725
	/**
1726
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1727
	 *
1728
	 * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1729
	 * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1730
	 * users and this option will be available by default for everybody.
1731
	 *
1732
	 * @since 9.6.0
1733
	 *
1734
	 * @return bool is the site connection ready to be used?
1735
	 */
1736
	public static function is_connection_ready() {
1737
		if ( ( new Status() )->is_no_user_testing_mode() ) {
1738
			return self::connection()->is_connected();
1739
		}
1740
		return (bool) self::connection()->has_connected_owner();
1741
	}
1742
1743
	/**
1744
	 * Make an API call to WordPress.com for plan status
1745
	 *
1746
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1747
	 *
1748
	 * @return bool True if plan is updated, false if no update
1749
	 */
1750
	public static function refresh_active_plan_from_wpcom() {
1751
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1752
		return Jetpack_Plan::refresh_from_wpcom();
1753
	}
1754
1755
	/**
1756
	 * Get the plan that this Jetpack site is currently using
1757
	 *
1758
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1759
	 * @return array Active Jetpack plan details.
1760
	 */
1761
	public static function get_active_plan() {
1762
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1763
		return Jetpack_Plan::get();
1764
	}
1765
1766
	/**
1767
	 * Determine whether the active plan supports a particular feature
1768
	 *
1769
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1770
	 * @return bool True if plan supports feature, false if not.
1771
	 */
1772
	public static function active_plan_supports( $feature ) {
1773
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1774
		return Jetpack_Plan::supports( $feature );
1775
	}
1776
1777
	/**
1778
	 * Deprecated: Is Jetpack in development (offline) mode?
1779
	 *
1780
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1781
	 * and themes still use it, and we do not want to flood them with notices.
1782
	 *
1783
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1784
	 *
1785
	 * @deprecated since 8.0.
1786
	 */
1787
	public static function is_development_mode() {
1788
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1789
		return ( new Status() )->is_offline_mode();
1790
	}
1791
1792
	/**
1793
	 * Whether the site is currently onboarding or not.
1794
	 * A site is considered as being onboarded if it currently has an onboarding token.
1795
	 *
1796
	 * @since 5.8
1797
	 *
1798
	 * @access public
1799
	 * @static
1800
	 *
1801
	 * @return bool True if the site is currently onboarding, false otherwise
1802
	 */
1803
	public static function is_onboarding() {
1804
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1805
	}
1806
1807
	/**
1808
	 * Determines reason for Jetpack offline mode.
1809
	 */
1810
	public static function development_mode_trigger_text() {
1811
		$status = new Status();
1812
1813
		if ( ! $status->is_offline_mode() ) {
1814
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1815
		}
1816
1817
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1818
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1819
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1820
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1821
		} elseif ( $status->is_local_site() ) {
1822
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1823
			/** This filter is documented in packages/status/src/class-status.php */
1824
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1825
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1826
		} else {
1827
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1828
		}
1829
1830
		return $notice;
1831
1832
	}
1833
	/**
1834
	 * Get Jetpack offline mode notice text and notice class.
1835
	 *
1836
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1837
	 */
1838
	public static function show_development_mode_notice() {
1839 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1840
			$notice = sprintf(
1841
				/* translators: %s is a URL */
1842
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1843
				Redirect::get_url( 'jetpack-support-development-mode' )
1844
			);
1845
1846
			$notice .= ' ' . self::development_mode_trigger_text();
1847
1848
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1849
		}
1850
1851
		// Throw up a notice if using a development version and as for feedback.
1852
		if ( self::is_development_version() ) {
1853
			/* translators: %s is a URL */
1854
			$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' ) );
1855
1856
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1857
		}
1858
		// Throw up a notice if using staging mode
1859 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1860
			/* translators: %s is a URL */
1861
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1862
1863
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1864
		}
1865
	}
1866
1867
	/**
1868
	 * Whether Jetpack's version maps to a public release, or a development version.
1869
	 */
1870
	public static function is_development_version() {
1871
		/**
1872
		 * Allows filtering whether this is a development version of Jetpack.
1873
		 *
1874
		 * This filter is especially useful for tests.
1875
		 *
1876
		 * @since 4.3.0
1877
		 *
1878
		 * @param bool $development_version Is this a develoment version of Jetpack?
1879
		 */
1880
		return (bool) apply_filters(
1881
			'jetpack_development_version',
1882
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1883
		);
1884
	}
1885
1886
	/**
1887
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1888
	 */
1889
	public static function is_user_connected( $user_id = false ) {
1890
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1891
		return self::connection()->is_user_connected( $user_id );
0 ignored issues
show
Documentation introduced by
$user_id is of type boolean, but the function expects a false|integer.

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...
1892
	}
1893
1894
	/**
1895
	 * Get the wpcom user data of the current|specified connected user.
1896
	 */
1897
	public static function get_connected_user_data( $user_id = null ) {
1898
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1899
		return self::connection()->get_connected_user_data( $user_id );
1900
	}
1901
1902
	/**
1903
	 * Get the wpcom email of the current|specified connected user.
1904
	 */
1905
	public static function get_connected_user_email( $user_id = null ) {
1906
		if ( ! $user_id ) {
1907
			$user_id = get_current_user_id();
1908
		}
1909
1910
		$xml = new Jetpack_IXR_Client(
1911
			array(
1912
				'user_id' => $user_id,
1913
			)
1914
		);
1915
		$xml->query( 'wpcom.getUserEmail' );
1916
		if ( ! $xml->isError() ) {
1917
			return $xml->getResponse();
1918
		}
1919
		return false;
1920
	}
1921
1922
	/**
1923
	 * Get the wpcom email of the master user.
1924
	 */
1925
	public static function get_master_user_email() {
1926
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1927
		if ( $master_user_id ) {
1928
			return self::get_connected_user_email( $master_user_id );
1929
		}
1930
		return '';
1931
	}
1932
1933
	/**
1934
	 * Whether the current user is the connection owner.
1935
	 *
1936
	 * @deprecated since 7.7
1937
	 *
1938
	 * @return bool Whether the current user is the connection owner.
1939
	 */
1940
	public function current_user_is_connection_owner() {
1941
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1942
		return self::connection()->is_connection_owner();
1943
	}
1944
1945
	/**
1946
	 * Gets current user IP address.
1947
	 *
1948
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1949
	 *
1950
	 * @return string                  Current user IP address.
1951
	 */
1952
	public static function current_user_ip( $check_all_headers = false ) {
1953
		if ( $check_all_headers ) {
1954
			foreach ( array(
1955
				'HTTP_CF_CONNECTING_IP',
1956
				'HTTP_CLIENT_IP',
1957
				'HTTP_X_FORWARDED_FOR',
1958
				'HTTP_X_FORWARDED',
1959
				'HTTP_X_CLUSTER_CLIENT_IP',
1960
				'HTTP_FORWARDED_FOR',
1961
				'HTTP_FORWARDED',
1962
				'HTTP_VIA',
1963
			) as $key ) {
1964
				if ( ! empty( $_SERVER[ $key ] ) ) {
1965
					return $_SERVER[ $key ];
1966
				}
1967
			}
1968
		}
1969
1970
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1971
	}
1972
1973
	/**
1974
	 * Synchronize connected user role changes
1975
	 */
1976
	function user_role_change( $user_id ) {
1977
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1978
		Users::user_role_change( $user_id );
1979
	}
1980
1981
	/**
1982
	 * Loads the currently active modules.
1983
	 */
1984
	public static function load_modules() {
1985
		$is_offline_mode = ( new Status() )->is_offline_mode();
1986
		if (
1987
			! self::is_active()
1988
			&& ! $is_offline_mode
1989
			&& ! self::is_onboarding()
1990
			&& (
1991
				! is_multisite()
1992
				|| ! get_site_option( 'jetpack_protect_active' )
1993
			)
1994
		) {
1995
			return;
1996
		}
1997
1998
		$version = Jetpack_Options::get_option( 'version' );
1999 View Code Duplication
		if ( ! $version ) {
2000
			$version = $old_version = JETPACK__VERSION . ':' . time();
2001
			/** This action is documented in class.jetpack.php */
2002
			do_action( 'updating_jetpack_version', $version, false );
2003
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2004
		}
2005
		list( $version ) = explode( ':', $version );
2006
2007
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
2008
2009
		$modules_data = array();
2010
2011
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
2012
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
2013
			$updated_modules = array();
2014
			foreach ( $modules as $module ) {
2015
				$modules_data[ $module ] = self::get_module( $module );
2016
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
2017
					continue;
2018
				}
2019
2020
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2021
					continue;
2022
				}
2023
2024
				$updated_modules[] = $module;
2025
			}
2026
2027
			$modules = array_diff( $modules, $updated_modules );
2028
		}
2029
2030
		foreach ( $modules as $index => $module ) {
2031
			// If we're in offline mode, disable modules requiring a connection.
2032
			if ( $is_offline_mode ) {
2033
				// Prime the pump if we need to
2034
				if ( empty( $modules_data[ $module ] ) ) {
2035
					$modules_data[ $module ] = self::get_module( $module );
2036
				}
2037
				// If the module requires a connection, but we're in local mode, don't include it.
2038
				if ( $modules_data[ $module ]['requires_connection'] ) {
2039
					continue;
2040
				}
2041
			}
2042
2043
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2044
				continue;
2045
			}
2046
2047
			if ( ! include_once self::get_module_path( $module ) ) {
2048
				unset( $modules[ $index ] );
2049
				self::update_active_modules( array_values( $modules ) );
2050
				continue;
2051
			}
2052
2053
			/**
2054
			 * Fires when a specific module is loaded.
2055
			 * The dynamic part of the hook, $module, is the module slug.
2056
			 *
2057
			 * @since 1.1.0
2058
			 */
2059
			do_action( 'jetpack_module_loaded_' . $module );
2060
		}
2061
2062
		/**
2063
		 * Fires when all the modules are loaded.
2064
		 *
2065
		 * @since 1.1.0
2066
		 */
2067
		do_action( 'jetpack_modules_loaded' );
2068
2069
		// 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.
2070
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2071
	}
2072
2073
	/**
2074
	 * Check if Jetpack's REST API compat file should be included
2075
	 *
2076
	 * @action plugins_loaded
2077
	 * @return null
2078
	 */
2079
	public function check_rest_api_compat() {
2080
		/**
2081
		 * Filters the list of REST API compat files to be included.
2082
		 *
2083
		 * @since 2.2.5
2084
		 *
2085
		 * @param array $args Array of REST API compat files to include.
2086
		 */
2087
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2088
2089
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2090
			require_once $_jetpack_rest_api_compat_include;
2091
		}
2092
	}
2093
2094
	/**
2095
	 * Gets all plugins currently active in values, regardless of whether they're
2096
	 * traditionally activated or network activated.
2097
	 *
2098
	 * @todo Store the result in core's object cache maybe?
2099
	 */
2100
	public static function get_active_plugins() {
2101
		$active_plugins = (array) get_option( 'active_plugins', array() );
2102
2103
		if ( is_multisite() ) {
2104
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2105
			// whereas active_plugins stores them in the values.
2106
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2107
			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...
2108
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2109
			}
2110
		}
2111
2112
		sort( $active_plugins );
2113
2114
		return array_unique( $active_plugins );
2115
	}
2116
2117
	/**
2118
	 * Gets and parses additional plugin data to send with the heartbeat data
2119
	 *
2120
	 * @since 3.8.1
2121
	 *
2122
	 * @return array Array of plugin data
2123
	 */
2124
	public static function get_parsed_plugin_data() {
2125
		if ( ! function_exists( 'get_plugins' ) ) {
2126
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2127
		}
2128
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2129
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2130
		$active_plugins = self::get_active_plugins();
2131
2132
		$plugins = array();
2133
		foreach ( $all_plugins as $path => $plugin_data ) {
2134
			$plugins[ $path ] = array(
2135
				'is_active' => in_array( $path, $active_plugins ),
2136
				'file'      => $path,
2137
				'name'      => $plugin_data['Name'],
2138
				'version'   => $plugin_data['Version'],
2139
				'author'    => $plugin_data['Author'],
2140
			);
2141
		}
2142
2143
		return $plugins;
2144
	}
2145
2146
	/**
2147
	 * Gets and parses theme data to send with the heartbeat data
2148
	 *
2149
	 * @since 3.8.1
2150
	 *
2151
	 * @return array Array of theme data
2152
	 */
2153
	public static function get_parsed_theme_data() {
2154
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2155
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2156
2157
		$themes = array();
2158
		foreach ( $all_themes as $slug => $theme_data ) {
2159
			$theme_headers = array();
2160
			foreach ( $header_keys as $header_key ) {
2161
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2162
			}
2163
2164
			$themes[ $slug ] = array(
2165
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2166
				'slug'            => $slug,
2167
				'theme_root'      => $theme_data->get_theme_root_uri(),
2168
				'parent'          => $theme_data->parent(),
2169
				'headers'         => $theme_headers,
2170
			);
2171
		}
2172
2173
		return $themes;
2174
	}
2175
2176
	/**
2177
	 * Checks whether a specific plugin is active.
2178
	 *
2179
	 * We don't want to store these in a static variable, in case
2180
	 * there are switch_to_blog() calls involved.
2181
	 */
2182
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2183
		return in_array( $plugin, self::get_active_plugins() );
2184
	}
2185
2186
	/**
2187
	 * Check if Jetpack's Open Graph tags should be used.
2188
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2189
	 *
2190
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2191
	 * @action plugins_loaded
2192
	 * @return null
2193
	 */
2194
	public function check_open_graph() {
2195
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2196
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2197
		}
2198
2199
		$active_plugins = self::get_active_plugins();
2200
2201
		if ( ! empty( $active_plugins ) ) {
2202
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2203
				if ( in_array( $plugin, $active_plugins ) ) {
2204
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2205
					break;
2206
				}
2207
			}
2208
		}
2209
2210
		/**
2211
		 * Allow the addition of Open Graph Meta Tags to all pages.
2212
		 *
2213
		 * @since 2.0.3
2214
		 *
2215
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2216
		 */
2217
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2218
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2219
		}
2220
	}
2221
2222
	/**
2223
	 * Check if Jetpack's Twitter tags should be used.
2224
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2225
	 *
2226
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2227
	 * @action plugins_loaded
2228
	 * @return null
2229
	 */
2230
	public function check_twitter_tags() {
2231
2232
		$active_plugins = self::get_active_plugins();
2233
2234
		if ( ! empty( $active_plugins ) ) {
2235
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2236
				if ( in_array( $plugin, $active_plugins ) ) {
2237
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2238
					break;
2239
				}
2240
			}
2241
		}
2242
2243
		/**
2244
		 * Allow Twitter Card Meta tags to be disabled.
2245
		 *
2246
		 * @since 2.6.0
2247
		 *
2248
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2249
		 */
2250
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2251
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2252
		}
2253
	}
2254
2255
	/**
2256
	 * Allows plugins to submit security reports.
2257
	 *
2258
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2259
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2260
	 * @param array  $args         See definitions above
2261
	 */
2262
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2263
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2264
	}
2265
2266
	/* Jetpack Options API */
2267
2268
	public static function get_option_names( $type = 'compact' ) {
2269
		return Jetpack_Options::get_option_names( $type );
2270
	}
2271
2272
	/**
2273
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2274
	 *
2275
	 * @param string $name    Option name
2276
	 * @param mixed  $default (optional)
2277
	 */
2278
	public static function get_option( $name, $default = false ) {
2279
		return Jetpack_Options::get_option( $name, $default );
2280
	}
2281
2282
	/**
2283
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2284
	 *
2285
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2286
	 * @param string $name  Option name
2287
	 * @param mixed  $value Option value
2288
	 */
2289
	public static function update_option( $name, $value ) {
2290
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2291
		return Jetpack_Options::update_option( $name, $value );
2292
	}
2293
2294
	/**
2295
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2296
	 *
2297
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2298
	 * @param array $array array( option name => option value, ... )
2299
	 */
2300
	public static function update_options( $array ) {
2301
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2302
		return Jetpack_Options::update_options( $array );
2303
	}
2304
2305
	/**
2306
	 * Deletes the given option.  May be passed multiple option names as an array.
2307
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2308
	 *
2309
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2310
	 * @param string|array $names
2311
	 */
2312
	public static function delete_option( $names ) {
2313
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2314
		return Jetpack_Options::delete_option( $names );
2315
	}
2316
2317
	/**
2318
	 * Enters a user token into the user_tokens option
2319
	 *
2320
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2321
	 *
2322
	 * @param int    $user_id The user id.
2323
	 * @param string $token The user token.
2324
	 * @param bool   $is_master_user Whether the user is the master user.
2325
	 * @return bool
2326
	 */
2327
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2328
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2329
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2330
	}
2331
2332
	/**
2333
	 * Returns an array of all PHP files in the specified absolute path.
2334
	 * Equivalent to glob( "$absolute_path/*.php" ).
2335
	 *
2336
	 * @param string $absolute_path The absolute path of the directory to search.
2337
	 * @return array Array of absolute paths to the PHP files.
2338
	 */
2339
	public static function glob_php( $absolute_path ) {
2340
		if ( function_exists( 'glob' ) ) {
2341
			return glob( "$absolute_path/*.php" );
2342
		}
2343
2344
		$absolute_path = untrailingslashit( $absolute_path );
2345
		$files         = array();
2346
		if ( ! $dir = @opendir( $absolute_path ) ) {
2347
			return $files;
2348
		}
2349
2350
		while ( false !== $file = readdir( $dir ) ) {
2351
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2352
				continue;
2353
			}
2354
2355
			$file = "$absolute_path/$file";
2356
2357
			if ( ! is_file( $file ) ) {
2358
				continue;
2359
			}
2360
2361
			$files[] = $file;
2362
		}
2363
2364
		closedir( $dir );
2365
2366
		return $files;
2367
	}
2368
2369
	public static function activate_new_modules( $redirect = false ) {
2370
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2371
			return;
2372
		}
2373
2374
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2375 View Code Duplication
		if ( ! $jetpack_old_version ) {
2376
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2377
			/** This action is documented in class.jetpack.php */
2378
			do_action( 'updating_jetpack_version', $version, false );
2379
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2380
		}
2381
2382
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2383
2384
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2385
			return;
2386
		}
2387
2388
		$active_modules     = self::get_active_modules();
2389
		$reactivate_modules = array();
2390
		foreach ( $active_modules as $active_module ) {
2391
			$module = self::get_module( $active_module );
2392
			if ( ! isset( $module['changed'] ) ) {
2393
				continue;
2394
			}
2395
2396
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2397
				continue;
2398
			}
2399
2400
			$reactivate_modules[] = $active_module;
2401
			self::deactivate_module( $active_module );
2402
		}
2403
2404
		$new_version = JETPACK__VERSION . ':' . time();
2405
		/** This action is documented in class.jetpack.php */
2406
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2407
		Jetpack_Options::update_options(
2408
			array(
2409
				'version'     => $new_version,
2410
				'old_version' => $jetpack_old_version,
2411
			)
2412
		);
2413
2414
		self::state( 'message', 'modules_activated' );
2415
2416
		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...
2417
2418
		if ( $redirect ) {
2419
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2420
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2421
				$page = $_GET['page'];
2422
			}
2423
2424
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2425
			exit;
2426
		}
2427
	}
2428
2429
	/**
2430
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2431
	 * Make sure to tuck away module "library" files in a sub-directory.
2432
	 *
2433
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2434
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2435
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2436
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2437
	 *
2438
	 * @return array $modules Array of module slugs
2439
	 */
2440
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2441
		static $modules = null;
2442
2443
		if ( ! isset( $modules ) ) {
2444
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2445
			// Use the cache if we're on the front-end and it's available...
2446
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2447
				$modules = $available_modules_option[ JETPACK__VERSION ];
2448
			} else {
2449
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2450
2451
				$modules = array();
2452
2453
				foreach ( $files as $file ) {
2454
					if ( ! $headers = self::get_module( $file ) ) {
2455
						continue;
2456
					}
2457
2458
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2459
				}
2460
2461
				Jetpack_Options::update_option(
2462
					'available_modules',
2463
					array(
2464
						JETPACK__VERSION => $modules,
2465
					)
2466
				);
2467
			}
2468
		}
2469
2470
		/**
2471
		 * Filters the array of modules available to be activated.
2472
		 *
2473
		 * @since 2.4.0
2474
		 *
2475
		 * @param array $modules Array of available modules.
2476
		 * @param string $min_version Minimum version number required to use modules.
2477
		 * @param string $max_version Maximum version number required to use modules.
2478
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2479
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2480
		 */
2481
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version, $requires_connection, $requires_user_connection );
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...
2482
2483
		if ( ! $min_version && ! $max_version && is_null( $requires_connection ) && is_null( $requires_user_connection ) ) {
2484
			return array_keys( $mods );
2485
		}
2486
2487
		$r = array();
2488
		foreach ( $mods as $slug => $introduced ) {
2489
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2490
				continue;
2491
			}
2492
2493
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2494
				continue;
2495
			}
2496
2497
			$mod_details = self::get_module( $slug );
2498
2499
			if ( null !== $requires_connection && (bool) $requires_connection !== $mod_details['requires_connection'] ) {
2500
				continue;
2501
			}
2502
2503
			if ( null !== $requires_user_connection && (bool) $requires_user_connection !== $mod_details['requires_user_connection'] ) {
2504
				continue;
2505
			}
2506
2507
			$r[] = $slug;
2508
		}
2509
2510
		return $r;
2511
	}
2512
2513
	/**
2514
	 * Get default modules loaded on activation.
2515
	 *
2516
	 * @param bool|string $min_version Onlu return modules introduced in this version or later. Default is false, do not filter.
2517
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2518
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2519
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2520
	 *
2521
	 * @return array $modules Array of module slugs
2522
	 */
2523
	public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2524
		$return = array();
2525
2526
		foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2527
			$module_data = self::get_module( $module );
2528
2529
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2530
				case 'yes':
2531
					$return[] = $module;
2532
					break;
2533
				case 'public':
2534
					if ( Jetpack_Options::get_option( 'public' ) ) {
2535
						$return[] = $module;
2536
					}
2537
					break;
2538
				case 'no':
2539
				default:
2540
					break;
2541
			}
2542
		}
2543
		/**
2544
		 * Filters the array of default modules.
2545
		 *
2546
		 * @since 2.5.0
2547
		 *
2548
		 * @param array $return Array of default modules.
2549
		 * @param string $min_version Minimum version number required to use modules.
2550
		 * @param string $max_version Maximum version number required to use modules.
2551
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2552
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2553
		 */
2554
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version, $requires_connection, $requires_user_connection );
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...
2555
	}
2556
2557
	/**
2558
	 * Checks activated modules during auto-activation to determine
2559
	 * if any of those modules are being deprecated.  If so, close
2560
	 * them out, and add any replacement modules.
2561
	 *
2562
	 * Runs at priority 99 by default.
2563
	 *
2564
	 * This is run late, so that it can still activate a module if
2565
	 * the new module is a replacement for another that the user
2566
	 * currently has active, even if something at the normal priority
2567
	 * would kibosh everything.
2568
	 *
2569
	 * @since 2.6
2570
	 * @uses jetpack_get_default_modules filter
2571
	 * @param array $modules
2572
	 * @return array
2573
	 */
2574
	function handle_deprecated_modules( $modules ) {
2575
		$deprecated_modules = array(
2576
			'debug'            => null,  // Closed out and moved to the debugger library.
2577
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2578
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2579
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2580
		);
2581
2582
		// Don't activate SSO if they never completed activating WPCC.
2583
		if ( self::is_module_active( 'wpcc' ) ) {
2584
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2585
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2586
				$deprecated_modules['wpcc'] = null;
2587
			}
2588
		}
2589
2590
		foreach ( $deprecated_modules as $module => $replacement ) {
2591
			if ( self::is_module_active( $module ) ) {
2592
				self::deactivate_module( $module );
2593
				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...
2594
					$modules[] = $replacement;
2595
				}
2596
			}
2597
		}
2598
2599
		return array_unique( $modules );
2600
	}
2601
2602
	/**
2603
	 * Checks activated plugins during auto-activation to determine
2604
	 * if any of those plugins are in the list with a corresponding module
2605
	 * that is not compatible with the plugin. The module will not be allowed
2606
	 * to auto-activate.
2607
	 *
2608
	 * @since 2.6
2609
	 * @uses jetpack_get_default_modules filter
2610
	 * @param array $modules
2611
	 * @return array
2612
	 */
2613
	function filter_default_modules( $modules ) {
2614
2615
		$active_plugins = self::get_active_plugins();
2616
2617
		if ( ! empty( $active_plugins ) ) {
2618
2619
			// For each module we'd like to auto-activate...
2620
			foreach ( $modules as $key => $module ) {
2621
				// If there are potential conflicts for it...
2622
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2623
					// For each potential conflict...
2624
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2625
						// If that conflicting plugin is active...
2626
						if ( in_array( $plugin, $active_plugins ) ) {
2627
							// Remove that item from being auto-activated.
2628
							unset( $modules[ $key ] );
2629
						}
2630
					}
2631
				}
2632
			}
2633
		}
2634
2635
		return $modules;
2636
	}
2637
2638
	/**
2639
	 * Extract a module's slug from its full path.
2640
	 */
2641
	public static function get_module_slug( $file ) {
2642
		return str_replace( '.php', '', basename( $file ) );
2643
	}
2644
2645
	/**
2646
	 * Generate a module's path from its slug.
2647
	 */
2648
	public static function get_module_path( $slug ) {
2649
		/**
2650
		 * Filters the path of a modules.
2651
		 *
2652
		 * @since 7.4.0
2653
		 *
2654
		 * @param array $return The absolute path to a module's root php file
2655
		 * @param string $slug The module slug
2656
		 */
2657
		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...
2658
	}
2659
2660
	/**
2661
	 * Load module data from module file. Headers differ from WordPress
2662
	 * plugin headers to avoid them being identified as standalone
2663
	 * plugins on the WordPress plugins page.
2664
	 */
2665
	public static function get_module( $module ) {
2666
		$headers = array(
2667
			'name'                      => 'Module Name',
2668
			'description'               => 'Module Description',
2669
			'sort'                      => 'Sort Order',
2670
			'recommendation_order'      => 'Recommendation Order',
2671
			'introduced'                => 'First Introduced',
2672
			'changed'                   => 'Major Changes In',
2673
			'deactivate'                => 'Deactivate',
2674
			'free'                      => 'Free',
2675
			'requires_connection'       => 'Requires Connection',
2676
			'requires_user_connection'  => 'Requires User Connection',
2677
			'auto_activate'             => 'Auto Activate',
2678
			'module_tags'               => 'Module Tags',
2679
			'feature'                   => 'Feature',
2680
			'additional_search_queries' => 'Additional Search Queries',
2681
			'plan_classes'              => 'Plans',
2682
		);
2683
2684
		static $modules_details;
2685
		$file = self::get_module_path( self::get_module_slug( $module ) );
2686
2687
		if ( isset( $modules_details[ $module ] ) ) {
2688
			$mod = $modules_details[ $module ];
2689
		} else {
2690
2691
			$mod = self::get_file_data( $file, $headers );
2692
			if ( empty( $mod['name'] ) ) {
2693
				return false;
2694
			}
2695
2696
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2697
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2698
			$mod['deactivate']               = empty( $mod['deactivate'] );
2699
			$mod['free']                     = empty( $mod['free'] );
2700
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2701
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2702
2703
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2704
				$mod['auto_activate'] = 'No';
2705
			} else {
2706
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2707
			}
2708
2709
			if ( $mod['module_tags'] ) {
2710
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2711
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2712
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2713
			} else {
2714
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2715
			}
2716
2717 View Code Duplication
			if ( $mod['plan_classes'] ) {
2718
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2719
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2720
			} else {
2721
				$mod['plan_classes'] = array( 'free' );
2722
			}
2723
2724 View Code Duplication
			if ( $mod['feature'] ) {
2725
				$mod['feature'] = explode( ',', $mod['feature'] );
2726
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2727
			} else {
2728
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2729
			}
2730
2731
			$modules_details[ $module ] = $mod;
2732
2733
		}
2734
2735
		/**
2736
		 * Filters the feature array on a module.
2737
		 *
2738
		 * This filter allows you to control where each module is filtered: Recommended,
2739
		 * and the default "Other" listing.
2740
		 *
2741
		 * @since 3.5.0
2742
		 *
2743
		 * @param array   $mod['feature'] The areas to feature this module:
2744
		 *     'Recommended' shows on the main Jetpack admin screen.
2745
		 *     'Other' should be the default if no other value is in the array.
2746
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2747
		 * @param array   $mod All the currently assembled module data.
2748
		 */
2749
		$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...
2750
2751
		/**
2752
		 * Filter the returned data about a module.
2753
		 *
2754
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2755
		 * so please be careful.
2756
		 *
2757
		 * @since 3.6.0
2758
		 *
2759
		 * @param array   $mod    The details of the requested module.
2760
		 * @param string  $module The slug of the module, e.g. sharedaddy
2761
		 * @param string  $file   The path to the module source file.
2762
		 */
2763
		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...
2764
	}
2765
2766
	/**
2767
	 * Like core's get_file_data implementation, but caches the result.
2768
	 */
2769
	public static function get_file_data( $file, $headers ) {
2770
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2771
		$file_name = basename( $file );
2772
2773
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2774
2775
		$file_data_option = get_transient( $cache_key );
2776
2777
		if ( ! is_array( $file_data_option ) ) {
2778
			delete_transient( $cache_key );
2779
			$file_data_option = false;
2780
		}
2781
2782
		if ( false === $file_data_option ) {
2783
			$file_data_option = array();
2784
		}
2785
2786
		$key           = md5( $file_name . serialize( $headers ) );
2787
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2788
2789
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2790
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2791
			return $file_data_option[ $key ];
2792
		}
2793
2794
		$data = get_file_data( $file, $headers );
2795
2796
		$file_data_option[ $key ] = $data;
2797
2798
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2799
2800
		return $data;
2801
	}
2802
2803
	/**
2804
	 * Return translated module tag.
2805
	 *
2806
	 * @param string $tag Tag as it appears in each module heading.
2807
	 *
2808
	 * @return mixed
2809
	 */
2810
	public static function translate_module_tag( $tag ) {
2811
		return jetpack_get_module_i18n_tag( $tag );
2812
	}
2813
2814
	/**
2815
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2816
	 *
2817
	 * @since 3.9.2
2818
	 *
2819
	 * @param array $modules
2820
	 *
2821
	 * @return string|void
2822
	 */
2823
	public static function get_translated_modules( $modules ) {
2824
		foreach ( $modules as $index => $module ) {
2825
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2826
			if ( isset( $module['name'] ) ) {
2827
				$modules[ $index ]['name'] = $i18n_module['name'];
2828
			}
2829
			if ( isset( $module['description'] ) ) {
2830
				$modules[ $index ]['description']       = $i18n_module['description'];
2831
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2832
			}
2833
		}
2834
		return $modules;
2835
	}
2836
2837
	/**
2838
	 * Get a list of activated modules as an array of module slugs.
2839
	 */
2840
	public static function get_active_modules() {
2841
		$active = Jetpack_Options::get_option( 'active_modules' );
2842
2843
		if ( ! is_array( $active ) ) {
2844
			$active = array();
2845
		}
2846
2847
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2848
			$active[] = 'vaultpress';
2849
		} else {
2850
			$active = array_diff( $active, array( 'vaultpress' ) );
2851
		}
2852
2853
		// If protect is active on the main site of a multisite, it should be active on all sites.
2854
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2855
			$active[] = 'protect';
2856
		}
2857
2858
		/**
2859
		 * Allow filtering of the active modules.
2860
		 *
2861
		 * Gives theme and plugin developers the power to alter the modules that
2862
		 * are activated on the fly.
2863
		 *
2864
		 * @since 5.8.0
2865
		 *
2866
		 * @param array $active Array of active module slugs.
2867
		 */
2868
		$active = apply_filters( 'jetpack_active_modules', $active );
2869
2870
		return array_unique( $active );
2871
	}
2872
2873
	/**
2874
	 * Check whether or not a Jetpack module is active.
2875
	 *
2876
	 * @param string $module The slug of a Jetpack module.
2877
	 * @return bool
2878
	 *
2879
	 * @static
2880
	 */
2881
	public static function is_module_active( $module ) {
2882
		return in_array( $module, self::get_active_modules() );
2883
	}
2884
2885
	public static function is_module( $module ) {
2886
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2887
	}
2888
2889
	/**
2890
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2891
	 *
2892
	 * @param bool $catch True to start catching, False to stop.
2893
	 *
2894
	 * @static
2895
	 */
2896
	public static function catch_errors( $catch ) {
2897
		static $display_errors, $error_reporting;
2898
2899
		if ( $catch ) {
2900
			$display_errors  = @ini_set( 'display_errors', 1 );
2901
			$error_reporting = @error_reporting( E_ALL );
2902
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2903
		} else {
2904
			@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...
2905
			@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...
2906
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2907
		}
2908
	}
2909
2910
	/**
2911
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2912
	 */
2913
	public static function catch_errors_on_shutdown() {
2914
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2915
	}
2916
2917
	/**
2918
	 * Rewrite any string to make paths easier to read.
2919
	 *
2920
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2921
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2922
	 *
2923
	 * @param $string
2924
	 * @return mixed
2925
	 */
2926
	public static function alias_directories( $string ) {
2927
		// ABSPATH has a trailing slash.
2928
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2929
		// WP_CONTENT_DIR does not have a trailing slash.
2930
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2931
2932
		return $string;
2933
	}
2934
2935
	public static function activate_default_modules(
2936
		$min_version = false,
2937
		$max_version = false,
2938
		$other_modules = array(),
2939
		$redirect = null,
2940
		$send_state_messages = null,
2941
		$requires_connection = null,
2942
		$requires_user_connection = null
2943
	) {
2944
		$jetpack = self::init();
2945
2946
		if ( is_null( $redirect ) ) {
2947
			if (
2948
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2949
			||
2950
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2951
			||
2952
				( defined( 'WP_CLI' ) && WP_CLI )
2953
			||
2954
				( defined( 'DOING_CRON' ) && DOING_CRON )
2955
			||
2956
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2957
			) {
2958
				$redirect = false;
2959
			} elseif ( is_admin() ) {
2960
				$redirect = true;
2961
			} else {
2962
				$redirect = false;
2963
			}
2964
		}
2965
2966
		if ( is_null( $send_state_messages ) ) {
2967
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2968
		}
2969
2970
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2971
		$modules = array_merge( $other_modules, $modules );
2972
2973
		// Look for standalone plugins and disable if active.
2974
2975
		$to_deactivate = array();
2976
		foreach ( $modules as $module ) {
2977
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2978
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2979
			}
2980
		}
2981
2982
		$deactivated = array();
2983
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2984
			list( $probable_file, $probable_title ) = $deactivate_me;
2985
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2986
				$deactivated[] = $module;
2987
			}
2988
		}
2989
2990
		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...
2991
			if ( $send_state_messages ) {
2992
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2993
			}
2994
2995
			if ( $redirect ) {
2996
				$url = add_query_arg(
2997
					array(
2998
						'action'   => 'activate_default_modules',
2999
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
3000
					),
3001
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
3002
				);
3003
				wp_safe_redirect( $url );
3004
				exit;
3005
			}
3006
		}
3007
3008
		/**
3009
		 * Fires before default modules are activated.
3010
		 *
3011
		 * @since 1.9.0
3012
		 *
3013
		 * @param string    $min_version Minimum version number required to use modules.
3014
		 * @param string    $max_version Maximum version number required to use modules.
3015
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3016
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3017
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3018
		 */
3019
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3020
3021
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3022
		if ( $send_state_messages ) {
3023
			self::restate();
3024
			self::catch_errors( true );
3025
		}
3026
3027
		$active = self::get_active_modules();
3028
3029
		foreach ( $modules as $module ) {
3030
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3031
				$active[] = $module;
3032
				self::update_active_modules( $active );
3033
				continue;
3034
			}
3035
3036
			if ( $send_state_messages && in_array( $module, $active ) ) {
3037
				$module_info = self::get_module( $module );
3038 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3039
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3040
					if ( $active_state = self::state( $state ) ) {
3041
						$active_state = explode( ',', $active_state );
3042
					} else {
3043
						$active_state = array();
3044
					}
3045
					$active_state[] = $module;
3046
					self::state( $state, implode( ',', $active_state ) );
3047
				}
3048
				continue;
3049
			}
3050
3051
			$file = self::get_module_path( $module );
3052
			if ( ! file_exists( $file ) ) {
3053
				continue;
3054
			}
3055
3056
			// we'll override this later if the plugin can be included without fatal error
3057
			if ( $redirect ) {
3058
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3059
			}
3060
3061
			if ( $send_state_messages ) {
3062
				self::state( 'error', 'module_activation_failed' );
3063
				self::state( 'module', $module );
3064
			}
3065
3066
			ob_start();
3067
			require_once $file;
3068
3069
			$active[] = $module;
3070
3071 View Code Duplication
			if ( $send_state_messages ) {
3072
3073
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3074
				if ( $active_state = self::state( $state ) ) {
3075
					$active_state = explode( ',', $active_state );
3076
				} else {
3077
					$active_state = array();
3078
				}
3079
				$active_state[] = $module;
3080
				self::state( $state, implode( ',', $active_state ) );
3081
			}
3082
3083
			self::update_active_modules( $active );
3084
3085
			ob_end_clean();
3086
		}
3087
3088
		if ( $send_state_messages ) {
3089
			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...
3090
			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...
3091
		}
3092
3093
		self::catch_errors( false );
3094
		/**
3095
		 * Fires when default modules are activated.
3096
		 *
3097
		 * @since 1.9.0
3098
		 *
3099
		 * @param string    $min_version Minimum version number required to use modules.
3100
		 * @param string    $max_version Maximum version number required to use modules.
3101
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3102
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3103
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3104
		 */
3105
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3106
	}
3107
3108
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3109
		/**
3110
		 * Fires before a module is activated.
3111
		 *
3112
		 * @since 2.6.0
3113
		 *
3114
		 * @param string $module Module slug.
3115
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3116
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3117
		 */
3118
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3119
3120
		$jetpack = self::init();
3121
3122
		if ( ! strlen( $module ) ) {
3123
			return false;
3124
		}
3125
3126
		if ( ! self::is_module( $module ) ) {
3127
			return false;
3128
		}
3129
3130
		// If it's already active, then don't do it again
3131
		$active = self::get_active_modules();
3132
		foreach ( $active as $act ) {
3133
			if ( $act == $module ) {
3134
				return true;
3135
			}
3136
		}
3137
3138
		$module_data = self::get_module( $module );
3139
3140
		$is_offline_mode = ( new Status() )->is_offline_mode();
3141
		if ( ! self::is_active() ) {
3142
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3143
				return false;
3144
			}
3145
3146
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3147
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3148
				return false;
3149
			}
3150
		}
3151
3152
		// Check and see if the old plugin is active
3153
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3154
			// Deactivate the old plugin
3155
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3156
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3157
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3158
				self::state( 'deactivated_plugins', $module );
3159
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3160
				exit;
3161
			}
3162
		}
3163
3164
		// Protect won't work with mis-configured IPs
3165
		if ( 'protect' === $module ) {
3166
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3167
			if ( ! jetpack_protect_get_ip() ) {
3168
				self::state( 'message', 'protect_misconfigured_ip' );
3169
				return false;
3170
			}
3171
		}
3172
3173
		if ( ! Jetpack_Plan::supports( $module ) ) {
3174
			return false;
3175
		}
3176
3177
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3178
		self::state( 'module', $module );
3179
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3180
3181
		self::catch_errors( true );
3182
		ob_start();
3183
		require self::get_module_path( $module );
3184
		/** This action is documented in class.jetpack.php */
3185
		do_action( 'jetpack_activate_module', $module );
3186
		$active[] = $module;
3187
		self::update_active_modules( $active );
3188
3189
		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...
3190
		ob_end_clean();
3191
		self::catch_errors( false );
3192
3193
		if ( $redirect ) {
3194
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3195
		}
3196
		if ( $exit ) {
3197
			exit;
3198
		}
3199
		return true;
3200
	}
3201
3202
	function activate_module_actions( $module ) {
3203
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3204
	}
3205
3206
	public static function deactivate_module( $module ) {
3207
		/**
3208
		 * Fires when a module is deactivated.
3209
		 *
3210
		 * @since 1.9.0
3211
		 *
3212
		 * @param string $module Module slug.
3213
		 */
3214
		do_action( 'jetpack_pre_deactivate_module', $module );
3215
3216
		$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...
3217
3218
		$active = self::get_active_modules();
3219
		$new    = array_filter( array_diff( $active, (array) $module ) );
3220
3221
		return self::update_active_modules( $new );
3222
	}
3223
3224
	public static function enable_module_configurable( $module ) {
3225
		$module = self::get_module_slug( $module );
3226
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3227
	}
3228
3229
	/**
3230
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3231
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3232
	 *
3233
	 * @param string $module Module slug
3234
	 * @return string $url module configuration URL
3235
	 */
3236
	public static function module_configuration_url( $module ) {
3237
		$module      = self::get_module_slug( $module );
3238
		$default_url = self::admin_url() . "#/settings?term=$module";
3239
		/**
3240
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3241
		 *
3242
		 * @since 6.9.0
3243
		 *
3244
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3245
		 */
3246
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3247
3248
		return $url;
3249
	}
3250
3251
	/* Installation */
3252
	public static function bail_on_activation( $message, $deactivate = true ) {
3253
		?>
3254
<!doctype html>
3255
<html>
3256
<head>
3257
<meta charset="<?php bloginfo( 'charset' ); ?>">
3258
<style>
3259
* {
3260
	text-align: center;
3261
	margin: 0;
3262
	padding: 0;
3263
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3264
}
3265
p {
3266
	margin-top: 1em;
3267
	font-size: 18px;
3268
}
3269
</style>
3270
<body>
3271
<p><?php echo esc_html( $message ); ?></p>
3272
</body>
3273
</html>
3274
		<?php
3275
		if ( $deactivate ) {
3276
			$plugins = get_option( 'active_plugins' );
3277
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3278
			$update  = false;
3279
			foreach ( $plugins as $i => $plugin ) {
3280
				if ( $plugin === $jetpack ) {
3281
					$plugins[ $i ] = false;
3282
					$update        = true;
3283
				}
3284
			}
3285
3286
			if ( $update ) {
3287
				update_option( 'active_plugins', array_filter( $plugins ) );
3288
			}
3289
		}
3290
		exit;
3291
	}
3292
3293
	/**
3294
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3295
	 *
3296
	 * @static
3297
	 */
3298
	public static function plugin_activation( $network_wide ) {
3299
		Jetpack_Options::update_option( 'activated', 1 );
3300
3301
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3302
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3303
		}
3304
3305
		if ( $network_wide ) {
3306
			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...
3307
		}
3308
3309
		// For firing one-off events (notices) immediately after activation
3310
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3311
3312
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3313
3314
		Health::on_jetpack_activated();
3315
3316
		self::plugin_initialize();
3317
	}
3318
3319
	public static function get_activation_source( $referer_url ) {
3320
3321
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3322
			return array( 'wp-cli', null );
3323
		}
3324
3325
		$referer = wp_parse_url( $referer_url );
3326
3327
		$source_type  = 'unknown';
3328
		$source_query = null;
3329
3330
		if ( ! is_array( $referer ) ) {
3331
			return array( $source_type, $source_query );
3332
		}
3333
3334
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3335
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3336
3337
		if ( isset( $referer['query'] ) ) {
3338
			parse_str( $referer['query'], $query_parts );
3339
		} else {
3340
			$query_parts = array();
3341
		}
3342
3343
		if ( $plugins_path === $referer['path'] ) {
3344
			$source_type = 'list';
3345
		} elseif ( $plugins_install_path === $referer['path'] ) {
3346
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3347
			switch ( $tab ) {
3348
				case 'popular':
3349
					$source_type = 'popular';
3350
					break;
3351
				case 'recommended':
3352
					$source_type = 'recommended';
3353
					break;
3354
				case 'favorites':
3355
					$source_type = 'favorites';
3356
					break;
3357
				case 'search':
3358
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3359
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3360
					break;
3361
				default:
3362
					$source_type = 'featured';
3363
			}
3364
		}
3365
3366
		return array( $source_type, $source_query );
3367
	}
3368
3369
	/**
3370
	 * Runs before bumping version numbers up to a new version
3371
	 *
3372
	 * @param string $version    Version:timestamp.
3373
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3374
	 */
3375
	public static function do_version_bump( $version, $old_version ) {
3376
		if ( $old_version ) { // For existing Jetpack installations.
3377
3378
			// If a front end page is visited after the update, the 'wp' action will fire.
3379
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3380
3381
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3382
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3383
		}
3384
	}
3385
3386
	/**
3387
	 * Sets the display_update_modal state.
3388
	 */
3389
	public static function set_update_modal_display() {
3390
		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...
3391
	}
3392
3393
	/**
3394
	 * Sets the internal version number and activation state.
3395
	 *
3396
	 * @static
3397
	 */
3398
	public static function plugin_initialize() {
3399
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3400
			Jetpack_Options::update_option( 'activated', 2 );
3401
		}
3402
3403 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3404
			$version = $old_version = JETPACK__VERSION . ':' . time();
3405
			/** This action is documented in class.jetpack.php */
3406
			do_action( 'updating_jetpack_version', $version, false );
3407
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3408
		}
3409
3410
		self::load_modules();
3411
3412
		Jetpack_Options::delete_option( 'do_activate' );
3413
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3414
	}
3415
3416
	/**
3417
	 * Removes all connection options
3418
	 *
3419
	 * @static
3420
	 */
3421
	public static function plugin_deactivation() {
3422
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3423
		$tracking = new Tracking();
3424
		$tracking->record_user_event( 'deactivate_plugin', array() );
3425
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3426
			Jetpack_Network::init()->deactivate();
3427
		} else {
3428
			self::disconnect( false );
3429
			// Jetpack_Heartbeat::init()->deactivate();
3430
		}
3431
	}
3432
3433
	/**
3434
	 * Disconnects from the Jetpack servers.
3435
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3436
	 *
3437
	 * @static
3438
	 */
3439
	public static function disconnect( $update_activated_state = true ) {
3440
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3441
3442
		$connection = self::connection();
3443
3444
		( new Nonce_Handler() )->clean_all();
3445
3446
		// If the site is in an IDC because sync is not allowed,
3447
		// let's make sure to not disconnect the production site.
3448
		if ( ! self::validate_sync_error_idc_option() ) {
3449
			$tracking = new Tracking();
3450
			$tracking->record_user_event( 'disconnect_site', array() );
3451
3452
			$connection->disconnect_site_wpcom( true );
3453
		}
3454
3455
		$connection->delete_all_connection_tokens( true );
3456
		Identity_Crisis::clear_all_idc_options();
3457
3458
		if ( $update_activated_state ) {
3459
			Jetpack_Options::update_option( 'activated', 4 );
3460
		}
3461
3462
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3463
			// Check then record unique disconnection if site has never been disconnected previously
3464
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3465
				$jetpack_unique_connection['disconnected'] = 1;
3466
			} else {
3467
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3468
					// track unique disconnect
3469
					$jetpack = self::init();
3470
3471
					$jetpack->stat( 'connections', 'unique-disconnect' );
3472
					$jetpack->do_stats( 'server_side' );
3473
				}
3474
				// increment number of times disconnected
3475
				$jetpack_unique_connection['disconnected'] += 1;
3476
			}
3477
3478
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3479
		}
3480
3481
		// Delete all the sync related data. Since it could be taking up space.
3482
		Sender::get_instance()->uninstall();
3483
3484
	}
3485
3486
	/**
3487
	 * Disconnects the user
3488
	 *
3489
	 * @param int $user_id The user ID to disconnect.
3490
	 */
3491
	public function disconnect_user( $user_id ) {
3492
		$this->connection_manager->disconnect_user( $user_id );
3493
	}
3494
3495
	/**
3496
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3497
	 */
3498
	public static function try_registration() {
3499
		$terms_of_service = new Terms_Of_Service();
3500
		// The user has agreed to the TOS at some point by now.
3501
		$terms_of_service->agree();
3502
3503
		// Let's get some testing in beta versions and such.
3504
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3505
			// Before attempting to connect, let's make sure that the domains are viable.
3506
			$domains_to_check = array_unique(
3507
				array(
3508
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3509
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3510
				)
3511
			);
3512
			foreach ( $domains_to_check as $domain ) {
3513
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3512 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...
3514
				if ( is_wp_error( $result ) ) {
3515
					return $result;
3516
				}
3517
			}
3518
		}
3519
3520
		$result = self::register();
3521
3522
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3523
		if ( ! $result || is_wp_error( $result ) ) {
3524
			return $result;
3525
		} else {
3526
			return true;
3527
		}
3528
	}
3529
3530
	/**
3531
	 * Tracking an internal event log. Try not to put too much chaff in here.
3532
	 *
3533
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3534
	 */
3535
	public static function log( $code, $data = null ) {
3536
		// only grab the latest 200 entries
3537
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3538
3539
		// Append our event to the log
3540
		$log_entry = array(
3541
			'time'    => time(),
3542
			'user_id' => get_current_user_id(),
3543
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3544
			'code'    => $code,
3545
		);
3546
		// Don't bother storing it unless we've got some.
3547
		if ( ! is_null( $data ) ) {
3548
			$log_entry['data'] = $data;
3549
		}
3550
		$log[] = $log_entry;
3551
3552
		// Try add_option first, to make sure it's not autoloaded.
3553
		// @todo: Add an add_option method to Jetpack_Options
3554
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3555
			Jetpack_Options::update_option( 'log', $log );
3556
		}
3557
3558
		/**
3559
		 * Fires when Jetpack logs an internal event.
3560
		 *
3561
		 * @since 3.0.0
3562
		 *
3563
		 * @param array $log_entry {
3564
		 *  Array of details about the log entry.
3565
		 *
3566
		 *  @param string time Time of the event.
3567
		 *  @param int user_id ID of the user who trigerred the event.
3568
		 *  @param int blog_id Jetpack Blog ID.
3569
		 *  @param string code Unique name for the event.
3570
		 *  @param string data Data about the event.
3571
		 * }
3572
		 */
3573
		do_action( 'jetpack_log_entry', $log_entry );
3574
	}
3575
3576
	/**
3577
	 * Get the internal event log.
3578
	 *
3579
	 * @param $event (string) - only return the specific log events
3580
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3581
	 *
3582
	 * @return array of log events || WP_Error for invalid params
3583
	 */
3584
	public static function get_log( $event = false, $num = false ) {
3585
		if ( $event && ! is_string( $event ) ) {
3586
			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...
3587
		}
3588
3589
		if ( $num && ! is_numeric( $num ) ) {
3590
			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...
3591
		}
3592
3593
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3594
3595
		// If nothing set - act as it did before, otherwise let's start customizing the output
3596
		if ( ! $num && ! $event ) {
3597
			return $entire_log;
3598
		} else {
3599
			$entire_log = array_reverse( $entire_log );
3600
		}
3601
3602
		$custom_log_output = array();
3603
3604
		if ( $event ) {
3605
			foreach ( $entire_log as $log_event ) {
3606
				if ( $event == $log_event['code'] ) {
3607
					$custom_log_output[] = $log_event;
3608
				}
3609
			}
3610
		} else {
3611
			$custom_log_output = $entire_log;
3612
		}
3613
3614
		if ( $num ) {
3615
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3616
		}
3617
3618
		return $custom_log_output;
3619
	}
3620
3621
	/**
3622
	 * Log modification of important settings.
3623
	 */
3624
	public static function log_settings_change( $option, $old_value, $value ) {
3625
		switch ( $option ) {
3626
			case 'jetpack_sync_non_public_post_stati':
3627
				self::log( $option, $value );
3628
				break;
3629
		}
3630
	}
3631
3632
	/**
3633
	 * Return stat data for WPCOM sync
3634
	 */
3635
	public static function get_stat_data( $encode = true, $extended = true ) {
3636
		$data = Jetpack_Heartbeat::generate_stats_array();
3637
3638
		if ( $extended ) {
3639
			$additional_data = self::get_additional_stat_data();
3640
			$data            = array_merge( $data, $additional_data );
3641
		}
3642
3643
		if ( $encode ) {
3644
			return json_encode( $data );
3645
		}
3646
3647
		return $data;
3648
	}
3649
3650
	/**
3651
	 * Get additional stat data to sync to WPCOM
3652
	 */
3653
	public static function get_additional_stat_data( $prefix = '' ) {
3654
		$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...
3655
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3656
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3657
		$return[ "{$prefix}site-count" ]    = 0;
3658
3659
		if ( function_exists( 'get_blog_count' ) ) {
3660
			$return[ "{$prefix}site-count" ] = get_blog_count();
3661
		}
3662
		return $return;
3663
	}
3664
3665
	private static function get_site_user_count() {
3666
		global $wpdb;
3667
3668
		if ( function_exists( 'wp_is_large_network' ) ) {
3669
			if ( wp_is_large_network( 'users' ) ) {
3670
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3671
			}
3672
		}
3673
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3674
			// It wasn't there, so regenerate the data and save the transient
3675
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3676
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3677
		}
3678
		return $user_count;
3679
	}
3680
3681
	/* Admin Pages */
3682
3683
	function admin_init() {
3684
		// If the plugin is not connected, display a connect message.
3685
		if (
3686
			// the plugin was auto-activated and needs its candy
3687
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3688
		||
3689
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3690
			! Jetpack_Options::get_option( 'activated' )
3691
		) {
3692
			self::plugin_initialize();
3693
		}
3694
3695
		$is_offline_mode = ( new Status() )->is_offline_mode();
3696
		if ( ! self::is_active() && ! $is_offline_mode ) {
3697
			Jetpack_Connection_Banner::init();
3698
			/** Already documented in automattic/jetpack-connection::src/class-client.php */
3699
		} elseif ( ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) && ! apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
3700
			// Upgrade: 1.1 -> 1.1.1
3701
			// Check and see if host can verify the Jetpack servers' SSL certificate
3702
			$args = array();
3703
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3704
		}
3705
3706
		Jetpack_Recommendations_Banner::init();
3707
3708
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3709
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3710
		}
3711
3712
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3713
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3714
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3715
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3716
3717
		if ( self::is_active() || $is_offline_mode ) {
3718
			// Artificially throw errors in certain specific cases during plugin activation.
3719
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3720
		}
3721
3722
		// Add custom column in wp-admin/users.php to show whether user is linked.
3723
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3724
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3725
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3726
	}
3727
3728
	function admin_body_class( $admin_body_class = '' ) {
3729
		$classes = explode( ' ', trim( $admin_body_class ) );
3730
3731
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3732
3733
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3734
		return " $admin_body_class ";
3735
	}
3736
3737
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3738
		return $admin_body_class . ' jetpack-pagestyles ';
3739
	}
3740
3741
	/**
3742
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3743
	 * This function artificially throws errors for such cases (per a specific list).
3744
	 *
3745
	 * @param string $plugin The activated plugin.
3746
	 */
3747
	function throw_error_on_activate_plugin( $plugin ) {
3748
		$active_modules = self::get_active_modules();
3749
3750
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3751
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3752
			$throw = false;
3753
3754
			// Try and make sure it really was the stats plugin
3755
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3756
				if ( 'stats.php' == basename( $plugin ) ) {
3757
					$throw = true;
3758
				}
3759
			} else {
3760
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3761
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3762
					$throw = true;
3763
				}
3764
			}
3765
3766
			if ( $throw ) {
3767
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3768
			}
3769
		}
3770
	}
3771
3772
	function intercept_plugin_error_scrape_init() {
3773
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3774
	}
3775
3776
	function intercept_plugin_error_scrape( $action, $result ) {
3777
		if ( ! $result ) {
3778
			return;
3779
		}
3780
3781
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3782
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3783
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3784
			}
3785
		}
3786
	}
3787
3788
	/**
3789
	 * Register the remote file upload request handlers, if needed.
3790
	 *
3791
	 * @access public
3792
	 */
3793
	public function add_remote_request_handlers() {
3794
		// Remote file uploads are allowed only via AJAX requests.
3795
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3796
			return;
3797
		}
3798
3799
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3800
		$remote_request_actions = array(
3801
			'jetpack_upload_file',
3802
			'jetpack_update_file',
3803
		);
3804
3805
		// phpcs:ignore WordPress.Security.NonceVerification
3806
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3807
			return;
3808
		}
3809
3810
		// Require Jetpack authentication for the remote file upload AJAX requests.
3811
		if ( ! $this->connection_manager ) {
3812
			$this->connection_manager = new Connection_Manager();
3813
		}
3814
3815
		$this->connection_manager->require_jetpack_authentication();
3816
3817
		// Register the remote file upload AJAX handlers.
3818
		foreach ( $remote_request_actions as $action ) {
3819
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3820
		}
3821
	}
3822
3823
	/**
3824
	 * Handler for Jetpack remote file uploads.
3825
	 *
3826
	 * @access public
3827
	 */
3828
	public function remote_request_handlers() {
3829
		$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...
3830
3831
		switch ( current_filter() ) {
3832
			case 'wp_ajax_nopriv_jetpack_upload_file':
3833
				$response = $this->upload_handler();
3834
				break;
3835
3836
			case 'wp_ajax_nopriv_jetpack_update_file':
3837
				$response = $this->upload_handler( true );
3838
				break;
3839
			default:
3840
				$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...
3841
				break;
3842
		}
3843
3844
		if ( ! $response ) {
3845
			$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...
3846
		}
3847
3848
		if ( is_wp_error( $response ) ) {
3849
			$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...
3850
			$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...
3851
			$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...
3852
3853
			if ( ! is_int( $status_code ) ) {
3854
				$status_code = 400;
3855
			}
3856
3857
			status_header( $status_code );
3858
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3859
		}
3860
3861
		status_header( 200 );
3862
		if ( true === $response ) {
3863
			exit;
3864
		}
3865
3866
		die( json_encode( (object) $response ) );
3867
	}
3868
3869
	/**
3870
	 * Uploads a file gotten from the global $_FILES.
3871
	 * If `$update_media_item` is true and `post_id` is defined
3872
	 * the attachment file of the media item (gotten through of the post_id)
3873
	 * will be updated instead of add a new one.
3874
	 *
3875
	 * @param  boolean $update_media_item - update media attachment
3876
	 * @return array - An array describing the uploadind files process
3877
	 */
3878
	function upload_handler( $update_media_item = false ) {
3879
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3880
			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...
3881
		}
3882
3883
		$user = wp_authenticate( '', '' );
3884
		if ( ! $user || is_wp_error( $user ) ) {
3885
			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...
3886
		}
3887
3888
		wp_set_current_user( $user->ID );
3889
3890
		if ( ! current_user_can( 'upload_files' ) ) {
3891
			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...
3892
		}
3893
3894
		if ( empty( $_FILES ) ) {
3895
			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...
3896
		}
3897
3898
		foreach ( array_keys( $_FILES ) as $files_key ) {
3899
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3900
				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...
3901
			}
3902
		}
3903
3904
		$media_keys = array_keys( $_FILES['media'] );
3905
3906
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3907
		if ( ! $token || is_wp_error( $token ) ) {
3908
			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...
3909
		}
3910
3911
		$uploaded_files = array();
3912
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3913
		unset( $GLOBALS['post'] );
3914
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3915
			$file = array();
3916
			foreach ( $media_keys as $media_key ) {
3917
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3918
			}
3919
3920
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3921
3922
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3923
			if ( $hmac_provided !== $hmac_file ) {
3924
				$uploaded_files[ $index ] = (object) array(
3925
					'error'             => 'invalid_hmac',
3926
					'error_description' => 'The corresponding HMAC for this file does not match',
3927
				);
3928
				continue;
3929
			}
3930
3931
			$_FILES['.jetpack.upload.'] = $file;
3932
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3933
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3934
				$post_id = 0;
3935
			}
3936
3937
			if ( $update_media_item ) {
3938
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3939
					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...
3940
				}
3941
3942
				$media_array = $_FILES['media'];
3943
3944
				$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...
3945
				$file_array['type']     = $media_array['type'][0];
3946
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3947
				$file_array['error']    = $media_array['error'][0];
3948
				$file_array['size']     = $media_array['size'][0];
3949
3950
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3951
3952
				if ( is_wp_error( $edited_media_item ) ) {
3953
					return $edited_media_item;
3954
				}
3955
3956
				$response = (object) array(
3957
					'id'   => (string) $post_id,
3958
					'file' => (string) $edited_media_item->post_title,
3959
					'url'  => (string) wp_get_attachment_url( $post_id ),
3960
					'type' => (string) $edited_media_item->post_mime_type,
3961
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3962
				);
3963
3964
				return (array) array( $response );
3965
			}
3966
3967
			$attachment_id = media_handle_upload(
3968
				'.jetpack.upload.',
3969
				$post_id,
3970
				array(),
3971
				array(
3972
					'action' => 'jetpack_upload_file',
3973
				)
3974
			);
3975
3976
			if ( ! $attachment_id ) {
3977
				$uploaded_files[ $index ] = (object) array(
3978
					'error'             => 'unknown',
3979
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3980
				);
3981
			} elseif ( is_wp_error( $attachment_id ) ) {
3982
				$uploaded_files[ $index ] = (object) array(
3983
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3984
					'error_description' => $attachment_id->get_error_message(),
3985
				);
3986
			} else {
3987
				$attachment               = get_post( $attachment_id );
3988
				$uploaded_files[ $index ] = (object) array(
3989
					'id'   => (string) $attachment_id,
3990
					'file' => $attachment->post_title,
3991
					'url'  => wp_get_attachment_url( $attachment_id ),
3992
					'type' => $attachment->post_mime_type,
3993
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3994
				);
3995
				// Zip files uploads are not supported unless they are done for installation purposed
3996
				// lets delete them in case something goes wrong in this whole process
3997
				if ( 'application/zip' === $attachment->post_mime_type ) {
3998
					// Schedule a cleanup for 2 hours from now in case of failed install.
3999
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
4000
				}
4001
			}
4002
		}
4003
		if ( ! is_null( $global_post ) ) {
4004
			$GLOBALS['post'] = $global_post;
4005
		}
4006
4007
		return $uploaded_files;
4008
	}
4009
4010
	/**
4011
	 * Add help to the Jetpack page
4012
	 *
4013
	 * @since Jetpack (1.2.3)
4014
	 * @return false if not the Jetpack page
4015
	 */
4016
	function admin_help() {
4017
		$current_screen = get_current_screen();
4018
4019
		// Overview
4020
		$current_screen->add_help_tab(
4021
			array(
4022
				'id'      => 'home',
4023
				'title'   => __( 'Home', 'jetpack' ),
4024
				'content' =>
4025
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4026
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4027
					'<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>',
4028
			)
4029
		);
4030
4031
		// Screen Content
4032
		if ( current_user_can( 'manage_options' ) ) {
4033
			$current_screen->add_help_tab(
4034
				array(
4035
					'id'      => 'settings',
4036
					'title'   => __( 'Settings', 'jetpack' ),
4037
					'content' =>
4038
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4039
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4040
						'<ol>' .
4041
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4042
							'<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>' .
4043
						'</ol>' .
4044
						'<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>',
4045
				)
4046
			);
4047
		}
4048
4049
		// Help Sidebar
4050
		$support_url = Redirect::get_url( 'jetpack-support' );
4051
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4052
		$current_screen->set_help_sidebar(
4053
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4054
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4055
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4056
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4057
		);
4058
	}
4059
4060
	function admin_menu_css() {
4061
		wp_enqueue_style( 'jetpack-icons' );
4062
	}
4063
4064
	function admin_menu_order() {
4065
		return true;
4066
	}
4067
4068
	function jetpack_menu_order( $menu_order ) {
4069
		$jp_menu_order = array();
4070
4071
		foreach ( $menu_order as $index => $item ) {
4072
			if ( $item != 'jetpack' ) {
4073
				$jp_menu_order[] = $item;
4074
			}
4075
4076
			if ( $index == 0 ) {
4077
				$jp_menu_order[] = 'jetpack';
4078
			}
4079
		}
4080
4081
		return $jp_menu_order;
4082
	}
4083
4084
	function admin_banner_styles() {
4085
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4086
4087
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4088
			wp_register_style(
4089
				'jetpack-dops-style',
4090
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4091
				array(),
4092
				JETPACK__VERSION
4093
			);
4094
		}
4095
4096
		wp_enqueue_style(
4097
			'jetpack',
4098
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4099
			array( 'jetpack-dops-style' ),
4100
			JETPACK__VERSION . '-20121016'
4101
		);
4102
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4103
		wp_style_add_data( 'jetpack', 'suffix', $min );
4104
	}
4105
4106
	function plugin_action_links( $actions ) {
4107
4108
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4109
4110
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
4111
			return array_merge(
4112
				$jetpack_home,
4113
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4114
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4115
				$actions
4116
			);
4117
		}
4118
4119
		return array_merge( $jetpack_home, $actions );
4120
	}
4121
4122
	/**
4123
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4124
	 *
4125
	 * @param string $hook The current admin page.
4126
	 *
4127
	 * @return void
4128
	 */
4129
	public function deactivate_dialog( $hook ) {
4130
		if (
4131
			'plugins.php' === $hook
4132
			&& self::is_active()
4133
		) {
4134
4135
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4136
4137
			if ( count( $active_plugins_using_connection ) > 1 ) {
4138
4139
				add_thickbox();
4140
4141
				wp_register_script(
4142
					'jp-tracks',
4143
					'//stats.wp.com/w.js',
4144
					array(),
4145
					gmdate( 'YW' ),
4146
					true
4147
				);
4148
4149
				wp_register_script(
4150
					'jp-tracks-functions',
4151
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4152
					array( 'jp-tracks' ),
4153
					JETPACK__VERSION,
4154
					false
4155
				);
4156
4157
				wp_enqueue_script(
4158
					'jetpack-deactivate-dialog-js',
4159
					Assets::get_file_url_for_environment(
4160
						'_inc/build/jetpack-deactivate-dialog.min.js',
4161
						'_inc/jetpack-deactivate-dialog.js'
4162
					),
4163
					array( 'jquery', 'jp-tracks-functions' ),
4164
					JETPACK__VERSION,
4165
					true
4166
				);
4167
4168
				wp_localize_script(
4169
					'jetpack-deactivate-dialog-js',
4170
					'deactivate_dialog',
4171
					array(
4172
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4173
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4174
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4175
					)
4176
				);
4177
4178
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4179
4180
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4181
			}
4182
		}
4183
	}
4184
4185
	/**
4186
	 * Outputs the content of the deactivation modal
4187
	 *
4188
	 * @return void
4189
	 */
4190
	public function deactivate_dialog_content() {
4191
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4192
		unset( $active_plugins_using_connection['jetpack'] );
4193
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
Bug introduced by
It seems like $active_plugins_using_connection defined by \Automattic\Jetpack\Conn...ugin_Storage::get_all() on line 4191 can also be of type object<WP_Error>; however, Jetpack::load_view() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4194
	}
4195
4196
	/**
4197
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4198
	 *
4199
	 * @param string $login_url The wp-login URL.
4200
	 * @param string $redirect  URL to redirect users after logging in.
4201
	 * @since Jetpack 8.4
4202
	 * @return string
4203
	 */
4204
	public function login_url( $login_url, $redirect ) {
4205
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4206
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4207
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4208
		}
4209
		return $login_url;
4210
	}
4211
4212
	/**
4213
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4214
	 *
4215
	 * @since Jetpack 8.4
4216
	 */
4217
	public function login_init() {
4218
		// phpcs:ignore WordPress.Security.NonceVerification
4219
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4220
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4221
			wp_safe_redirect(
4222
				add_query_arg(
4223
					array(
4224
						'forceInstall' => 1,
4225
						'url'          => rawurlencode( get_site_url() ),
4226
					),
4227
					// @todo provide way to go to specific calypso env.
4228
					self::get_calypso_host() . 'jetpack/connect'
4229
				)
4230
			);
4231
			exit;
4232
		}
4233
	}
4234
4235
	/*
4236
	 * Registration flow:
4237
	 * 1 - ::admin_page_load() action=register
4238
	 * 2 - ::try_registration()
4239
	 * 3 - ::register()
4240
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4241
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4242
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4243
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4244
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4245
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4246
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4247
	 *       jetpack_id, jetpack_secret, jetpack_public
4248
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4249
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4250
	 * 5 - user logs in with WP.com account
4251
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4252
	 *		- Manager::authorize()
4253
	 *		- Manager::get_token()
4254
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4255
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4256
	 *			- which responds with access_token, token_type, scope
4257
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4258
	 *		- Jetpack::activate_default_modules()
4259
	 *     		- Deactivates deprecated plugins
4260
	 *     		- Activates all default modules
4261
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4262
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4263
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4264
	 *     Done!
4265
	 */
4266
4267
	/**
4268
	 * Handles the page load events for the Jetpack admin page
4269
	 */
4270
	function admin_page_load() {
4271
		$error = false;
4272
4273
		// Make sure we have the right body class to hook stylings for subpages off of.
4274
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4275
4276
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4277
			// Should only be used in intermediate redirects to preserve state across redirects
4278
			self::restate();
4279
		}
4280
4281
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4282
			// @todo: Add validation against a known allowed list.
4283
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4284
			// User clicked in the iframe to link their accounts
4285
			if ( ! self::connection()->is_user_connected() ) {
4286
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4287
4288
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4289
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4290
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4291
4292
				if ( isset( $_GET['notes_iframe'] ) ) {
4293
					$connect_url .= '&notes_iframe';
4294
				}
4295
				wp_redirect( $connect_url );
4296
				exit;
4297
			} else {
4298
				if ( ! isset( $_GET['calypso_env'] ) ) {
4299
					self::state( 'message', 'already_authorized' );
4300
					wp_safe_redirect( self::admin_url() );
4301
					exit;
4302
				} else {
4303
					$connect_url  = $this->build_connect_url( true, false, $from );
4304
					$connect_url .= '&already_authorized=true';
4305
					wp_redirect( $connect_url );
4306
					exit;
4307
				}
4308
			}
4309
		}
4310
4311
		if ( isset( $_GET['action'] ) ) {
4312
			switch ( $_GET['action'] ) {
4313
				case 'authorize_redirect':
4314
					self::log( 'authorize_redirect' );
4315
4316
					add_filter(
4317
						'allowed_redirect_hosts',
4318
						function ( $domains ) {
4319
							$domains[] = 'jetpack.com';
4320
							$domains[] = 'jetpack.wordpress.com';
4321
							$domains[] = 'wordpress.com';
4322
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4323
							return array_unique( $domains );
4324
						}
4325
					);
4326
4327
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4328
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4329
4330
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4331
						// The destination URL is missing or invalid, nothing to do here.
4332
						exit;
4333
					}
4334
4335
					if ( static::is_active() && static::connection()->is_user_connected() ) {
4336
						// The user is either already connected, or finished the connection process.
4337
						wp_safe_redirect( $dest_url );
4338
						exit;
4339
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4340
						// The user decided not to proceed with setting up the connection.
4341
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4342
						exit;
4343
					}
4344
4345
					$redirect_url = self::admin_url(
4346
						array(
4347
							'page'     => 'jetpack',
4348
							'action'   => 'authorize_redirect',
4349
							'dest_url' => rawurlencode( $dest_url ),
4350
							'done'     => '1',
4351
						)
4352
					);
4353
4354
					wp_safe_redirect( static::build_authorize_url( $redirect_url ) );
0 ignored issues
show
Documentation introduced by
$redirect_url 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...
4355
					exit;
4356
				case 'authorize':
4357
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4358
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4359
					exit;
4360
				case 'register':
4361
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4362
						$error = 'cheatin';
4363
						break;
4364
					}
4365
					check_admin_referer( 'jetpack-register' );
4366
					self::log( 'register' );
4367
					self::maybe_set_version_option();
4368
					$registered = self::try_registration();
4369
					if ( is_wp_error( $registered ) ) {
4370
						$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...
4371
						self::state( 'error', $error );
4372
						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...
4373
4374
						/**
4375
						 * Jetpack registration Error.
4376
						 *
4377
						 * @since 7.5.0
4378
						 *
4379
						 * @param string|int $error The error code.
4380
						 * @param \WP_Error $registered The error object.
4381
						 */
4382
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4383
						break;
4384
					}
4385
4386
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4387
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4388
4389
					/**
4390
					 * Jetpack registration Success.
4391
					 *
4392
					 * @since 7.5.0
4393
					 *
4394
					 * @param string $from 'from' GET parameter;
4395
					 */
4396
					do_action( 'jetpack_connection_register_success', $from );
4397
4398
					$url = $this->build_connect_url( true, $redirect, $from );
4399
4400
					if ( ! empty( $_GET['onboarding'] ) ) {
4401
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4402
					}
4403
4404
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4405
						$url = add_query_arg( 'auth_approved', 'true', $url );
4406
					}
4407
4408
					wp_redirect( $url );
4409
					exit;
4410
				case 'activate':
4411
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4412
						$error = 'cheatin';
4413
						break;
4414
					}
4415
4416
					$module = stripslashes( $_GET['module'] );
4417
					check_admin_referer( "jetpack_activate-$module" );
4418
					self::log( 'activate', $module );
4419
					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...
4420
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4421
					}
4422
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4423
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4424
					exit;
4425
				case 'activate_default_modules':
4426
					check_admin_referer( 'activate_default_modules' );
4427
					self::log( 'activate_default_modules' );
4428
					self::restate();
4429
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4430
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4431
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4432
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4433
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4434
					exit;
4435 View Code Duplication
				case 'disconnect':
4436
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4437
						$error = 'cheatin';
4438
						break;
4439
					}
4440
4441
					check_admin_referer( 'jetpack-disconnect' );
4442
					self::log( 'disconnect' );
4443
					self::disconnect();
4444
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4445
					exit;
4446 View Code Duplication
				case 'reconnect':
4447
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4448
						$error = 'cheatin';
4449
						break;
4450
					}
4451
4452
					check_admin_referer( 'jetpack-reconnect' );
4453
					self::log( 'reconnect' );
4454
					self::disconnect();
4455
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4456
					exit;
4457 View Code Duplication
				case 'deactivate':
4458
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4459
						$error = 'cheatin';
4460
						break;
4461
					}
4462
4463
					$modules = stripslashes( $_GET['module'] );
4464
					check_admin_referer( "jetpack_deactivate-$modules" );
4465
					foreach ( explode( ',', $modules ) as $module ) {
4466
						self::log( 'deactivate', $module );
4467
						self::deactivate_module( $module );
4468
						self::state( 'message', 'module_deactivated' );
4469
					}
4470
					self::state( 'module', $modules );
4471
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4472
					exit;
4473
				case 'unlink':
4474
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4475
					check_admin_referer( 'jetpack-unlink' );
4476
					self::log( 'unlink' );
4477
					$this->connection_manager->disconnect_user();
4478
					self::state( 'message', 'unlinked' );
4479
					if ( 'sub-unlink' == $redirect ) {
4480
						wp_safe_redirect( admin_url() );
4481
					} else {
4482
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4483
					}
4484
					exit;
4485
				case 'onboard':
4486
					if ( ! current_user_can( 'manage_options' ) ) {
4487
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4488
					} else {
4489
						self::create_onboarding_token();
4490
						$url = $this->build_connect_url( true );
4491
4492
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4493
							$url = add_query_arg( 'onboarding', $token, $url );
4494
						}
4495
4496
						$calypso_env = $this->get_calypso_env();
4497
						if ( ! empty( $calypso_env ) ) {
4498
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4499
						}
4500
4501
						wp_redirect( $url );
4502
						exit;
4503
					}
4504
					exit;
4505
				default:
4506
					/**
4507
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4508
					 *
4509
					 * @since 2.6.0
4510
					 *
4511
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4512
					 */
4513
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4514
			}
4515
		}
4516
4517
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4518
			self::activate_new_modules( true );
4519
		}
4520
4521
		$message_code = self::state( 'message' );
4522
		if ( self::state( 'optin-manage' ) ) {
4523
			$activated_manage = $message_code;
4524
			$message_code     = 'jetpack-manage';
4525
		}
4526
4527
		switch ( $message_code ) {
4528
			case 'jetpack-manage':
4529
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4530
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4531
				$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>';
4532
				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...
4533
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4534
				}
4535
				break;
4536
4537
		}
4538
4539
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4540
4541
		if ( ! empty( $deactivated_plugins ) ) {
4542
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4543
			$deactivated_titles  = array();
4544
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4545
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4546
					continue;
4547
				}
4548
4549
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4550
			}
4551
4552
			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...
4553
				if ( $this->message ) {
4554
					$this->message .= "<br /><br />\n";
4555
				}
4556
4557
				$this->message .= wp_sprintf(
4558
					_n(
4559
						'Jetpack contains the most recent version of the old %l plugin.',
4560
						'Jetpack contains the most recent versions of the old %l plugins.',
4561
						count( $deactivated_titles ),
4562
						'jetpack'
4563
					),
4564
					$deactivated_titles
4565
				);
4566
4567
				$this->message .= "<br />\n";
4568
4569
				$this->message .= _n(
4570
					'The old version has been deactivated and can be removed from your site.',
4571
					'The old versions have been deactivated and can be removed from your site.',
4572
					count( $deactivated_titles ),
4573
					'jetpack'
4574
				);
4575
			}
4576
		}
4577
4578
		$this->privacy_checks = self::state( 'privacy_checks' );
4579
4580
		if ( $this->message || $this->error || $this->privacy_checks ) {
4581
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4582
		}
4583
4584
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4585
	}
4586
4587
	function admin_notices() {
4588
4589
		if ( $this->error ) {
4590
			?>
4591
<div id="message" class="jetpack-message jetpack-err">
4592
	<div class="squeezer">
4593
		<h2>
4594
			<?php
4595
			echo wp_kses(
4596
				$this->error,
4597
				array(
4598
					'a'      => array( 'href' => array() ),
4599
					'small'  => true,
4600
					'code'   => true,
4601
					'strong' => true,
4602
					'br'     => true,
4603
					'b'      => true,
4604
				)
4605
			);
4606
			?>
4607
			</h2>
4608
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4609
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4610
<?php	endif; ?>
4611
	</div>
4612
</div>
4613
			<?php
4614
		}
4615
4616
		if ( $this->message ) {
4617
			?>
4618
<div id="message" class="jetpack-message">
4619
	<div class="squeezer">
4620
		<h2>
4621
			<?php
4622
			echo wp_kses(
4623
				$this->message,
4624
				array(
4625
					'strong' => array(),
4626
					'a'      => array( 'href' => true ),
4627
					'br'     => true,
4628
				)
4629
			);
4630
			?>
4631
			</h2>
4632
	</div>
4633
</div>
4634
			<?php
4635
		}
4636
4637
		if ( $this->privacy_checks ) :
4638
			$module_names = $module_slugs = array();
4639
4640
			$privacy_checks = explode( ',', $this->privacy_checks );
4641
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4642
			foreach ( $privacy_checks as $module_slug ) {
4643
				$module = self::get_module( $module_slug );
4644
				if ( ! $module ) {
4645
					continue;
4646
				}
4647
4648
				$module_slugs[] = $module_slug;
4649
				$module_names[] = "<strong>{$module['name']}</strong>";
4650
			}
4651
4652
			$module_slugs = join( ',', $module_slugs );
4653
			?>
4654
<div id="message" class="jetpack-message jetpack-err">
4655
	<div class="squeezer">
4656
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4657
		<p>
4658
			<?php
4659
			echo wp_kses(
4660
				wptexturize(
4661
					wp_sprintf(
4662
						_nx(
4663
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4664
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4665
							count( $privacy_checks ),
4666
							'%l = list of Jetpack module/feature names',
4667
							'jetpack'
4668
						),
4669
						$module_names
4670
					)
4671
				),
4672
				array( 'strong' => true )
4673
			);
4674
4675
			echo "\n<br />\n";
4676
4677
			echo wp_kses(
4678
				sprintf(
4679
					_nx(
4680
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4681
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4682
						count( $privacy_checks ),
4683
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4684
						'jetpack'
4685
					),
4686
					wp_nonce_url(
4687
						self::admin_url(
4688
							array(
4689
								'page'   => 'jetpack',
4690
								'action' => 'deactivate',
4691
								'module' => urlencode( $module_slugs ),
4692
							)
4693
						),
4694
						"jetpack_deactivate-$module_slugs"
4695
					),
4696
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4697
				),
4698
				array(
4699
					'a' => array(
4700
						'href'  => true,
4701
						'title' => true,
4702
					),
4703
				)
4704
			);
4705
			?>
4706
		</p>
4707
	</div>
4708
</div>
4709
			<?php
4710
endif;
4711
	}
4712
4713
	/**
4714
	 * We can't always respond to a signed XML-RPC request with a
4715
	 * helpful error message. In some circumstances, doing so could
4716
	 * leak information.
4717
	 *
4718
	 * Instead, track that the error occurred via a Jetpack_Option,
4719
	 * and send that data back in the heartbeat.
4720
	 * All this does is increment a number, but it's enough to find
4721
	 * trends.
4722
	 *
4723
	 * @param WP_Error $xmlrpc_error The error produced during
4724
	 *                               signature validation.
4725
	 */
4726
	function track_xmlrpc_error( $xmlrpc_error ) {
4727
		$code = is_wp_error( $xmlrpc_error )
4728
			? $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...
4729
			: 'should-not-happen';
4730
4731
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4732
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4733
			// No need to update the option if we already have
4734
			// this code stored.
4735
			return;
4736
		}
4737
		$xmlrpc_errors[ $code ] = true;
4738
4739
		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...
4740
	}
4741
4742
	/**
4743
	 * Initialize the jetpack stats instance only when needed
4744
	 *
4745
	 * @return void
4746
	 */
4747
	private function initialize_stats() {
4748
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4749
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4750
		}
4751
	}
4752
4753
	/**
4754
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4755
	 */
4756
	function stat( $group, $detail ) {
4757
		$this->initialize_stats();
4758
		$this->a8c_mc_stats_instance->add( $group, $detail );
4759
4760
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4761
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4762
	}
4763
4764
	/**
4765
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4766
	 */
4767
	function do_stats( $method = '' ) {
4768
		$this->initialize_stats();
4769
		if ( 'server_side' === $method ) {
4770
			$this->a8c_mc_stats_instance->do_server_side_stats();
4771
		} else {
4772
			$this->a8c_mc_stats_instance->do_stats();
4773
		}
4774
4775
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4776
		$this->stats = array();
4777
	}
4778
4779
	/**
4780
	 * Runs stats code for a one-off, server-side.
4781
	 *
4782
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4783
	 *
4784
	 * @return bool If it worked.
4785
	 */
4786
	static function do_server_side_stat( $args ) {
4787
		$url                   = self::build_stats_url( $args );
4788
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4789
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4790
	}
4791
4792
	/**
4793
	 * Builds the stats url.
4794
	 *
4795
	 * @param $args array|string The arguments to append to the URL.
4796
	 *
4797
	 * @return string The URL to be pinged.
4798
	 */
4799
	static function build_stats_url( $args ) {
4800
4801
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4802
		return $a8c_mc_stats_instance->build_stats_url( $args );
4803
4804
	}
4805
4806
	/**
4807
	 * Builds a URL to the Jetpack connection auth page
4808
	 *
4809
	 * @since 3.9.5
4810
	 *
4811
	 * @param bool        $raw If true, URL will not be escaped.
4812
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4813
	 *                              If string, will be a custom redirect.
4814
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4815
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4816
	 *
4817
	 * @return string Connect URL
4818
	 */
4819
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4820
		$site_id    = Jetpack_Options::get_option( 'id' );
4821
		$blog_token = ( new Tokens() )->get_access_token();
4822
4823
		if ( $register || ! $blog_token || ! $site_id ) {
4824
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4825
4826
			if ( ! empty( $redirect ) ) {
4827
				$url = add_query_arg(
4828
					'redirect',
4829
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4830
					$url
4831
				);
4832
			}
4833
4834
			if ( is_network_admin() ) {
4835
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4836
			}
4837
4838
			$calypso_env = self::get_calypso_env();
4839
4840
			if ( ! empty( $calypso_env ) ) {
4841
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4842
			}
4843
		} else {
4844
4845
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4846
			// because otherwise this logic can get us in to a loop.
4847
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4848
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4849
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4850
4851
				$response = Client::wpcom_json_api_request_as_blog(
4852
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4853
					'1.1'
4854
				);
4855
4856
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4857
4858
					// Generating a register URL instead to refresh the existing token
4859
					return $this->build_connect_url( $raw, $redirect, $from, true );
4860
				}
4861
			}
4862
4863
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4819 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...
4864
		}
4865
4866
		if ( $from ) {
4867
			$url = add_query_arg( 'from', $from, $url );
4868
		}
4869
4870
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4871
		/**
4872
		 * Filter the URL used when connecting a user to a WordPress.com account.
4873
		 *
4874
		 * @since 8.1.0
4875
		 *
4876
		 * @param string $url Connection URL.
4877
		 * @param bool   $raw If true, URL will not be escaped.
4878
		 */
4879
		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...
4880
	}
4881
4882
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4883
4884
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4885
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4886
4887
		if ( $iframe ) {
4888
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4889
		}
4890
4891
		$c8n = self::connection();
4892
		$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...
4893
4894
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4895
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4896
4897
		if ( $iframe ) {
4898
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4899
		}
4900
4901
		/**
4902
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4903
		 *
4904
		 * @since 8.9.0
4905
		 *
4906
		 * @param string $url Connection URL.
4907
		 */
4908
		return apply_filters( 'jetpack_build_authorize_url', $url );
4909
	}
4910
4911
	/**
4912
	 * Filters the connection URL parameter array.
4913
	 *
4914
	 * @param array $args default URL parameters used by the package.
4915
	 * @return array the modified URL arguments array.
4916
	 */
4917
	public static function filter_connect_request_body( $args ) {
4918
		if (
4919
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4920
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4921
		) {
4922
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4923
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4924
				? $gp_locale->slug
4925
				: '';
4926
		}
4927
4928
		$tracking        = new Tracking();
4929
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4930
4931
		$args = array_merge(
4932
			$args,
4933
			array(
4934
				'_ui' => $tracks_identity['_ui'],
4935
				'_ut' => $tracks_identity['_ut'],
4936
			)
4937
		);
4938
4939
		$calypso_env = self::get_calypso_env();
4940
4941
		if ( ! empty( $calypso_env ) ) {
4942
			$args['calypso_env'] = $calypso_env;
4943
		}
4944
4945
		return $args;
4946
	}
4947
4948
	/**
4949
	 * Filters the URL that will process the connection data. It can be different from the URL
4950
	 * that we send the user to after everything is done.
4951
	 *
4952
	 * @param String $processing_url the default redirect URL used by the package.
4953
	 * @return String the modified URL.
4954
	 *
4955
	 * @deprecated since Jetpack 9.5.0
4956
	 */
4957
	public static function filter_connect_processing_url( $processing_url ) {
4958
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4959
4960
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4961
		return $processing_url;
4962
	}
4963
4964
	/**
4965
	 * Filters the redirection URL that is used for connect requests. The redirect
4966
	 * URL should return the user back to the Jetpack console.
4967
	 *
4968
	 * @param String $redirect the default redirect URL used by the package.
4969
	 * @return String the modified URL.
4970
	 */
4971
	public static function filter_connect_redirect_url( $redirect ) {
4972
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4973
		$redirect           = $redirect
4974
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4975
			: $jetpack_admin_page;
4976
4977
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4978
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4979
		}
4980
4981
		return $redirect;
4982
	}
4983
4984
	/**
4985
	 * This action fires at the beginning of the Manager::authorize method.
4986
	 */
4987
	public static function authorize_starting() {
4988
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4989
		// Checking if site has been active/connected previously before recording unique connection.
4990
		if ( ! $jetpack_unique_connection ) {
4991
			// jetpack_unique_connection option has never been set.
4992
			$jetpack_unique_connection = array(
4993
				'connected'    => 0,
4994
				'disconnected' => 0,
4995
				'version'      => '3.6.1',
4996
			);
4997
4998
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4999
5000
			// Track unique connection.
5001
			$jetpack = self::init();
5002
5003
			$jetpack->stat( 'connections', 'unique-connection' );
5004
			$jetpack->do_stats( 'server_side' );
5005
		}
5006
5007
		// Increment number of times connected.
5008
		$jetpack_unique_connection['connected'] += 1;
5009
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5010
	}
5011
5012
	/**
5013
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5014
	 * linked.
5015
	 */
5016
	public static function authorize_ending_linked() {
5017
		// Don't activate anything since we are just connecting a user.
5018
		self::state( 'message', 'linked' );
5019
	}
5020
5021
	/**
5022
	 * This action fires at the end of the Manager::authorize method when the master user is
5023
	 * authorized.
5024
	 *
5025
	 * @param array $data The request data.
5026
	 */
5027
	public static function authorize_ending_authorized( $data ) {
5028
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5029
		self::invalidate_onboarding_token();
5030
5031
		// If redirect_uri is SSO, ensure SSO module is enabled.
5032
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5033
5034
		/** This filter is documented in class.jetpack-cli.php */
5035
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5036
5037
		$activate_sso = (
5038
			isset( $redirect_options['action'] ) &&
5039
			'jetpack-sso' === $redirect_options['action'] &&
5040
			$jetpack_start_enable_sso
5041
		);
5042
5043
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5044
5045
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5046
	}
5047
5048
	/**
5049
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5050
	 */
5051
	public static function activate_default_modules_on_site_register() {
5052
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5053
		if ( $active_modules ) {
5054
			self::delete_active_modules();
5055
5056
			// If there was previously activated modules (a reconnection), re-activate them all including those that require a user, and do not re-activate those that have been deactivated.
5057
			self::activate_default_modules( 999, 1, $active_modules, false );
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...
5058
		} else {
5059
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5060
			self::activate_default_modules( false, false, array(), false, null, null, false );
5061
		}
5062
5063
		// Since this is a fresh connection, be sure to clear out IDC options.
5064
		Jetpack_IDC::clear_all_idc_options();
5065
	}
5066
5067
	/**
5068
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5069
	 * reconnect process is completed.
5070
	 * Note that this currently only happens when we don't need the user to re-authorize
5071
	 * their WP.com account, eg in cases where we are restoring a connection with
5072
	 * unhealthy blog token.
5073
	 */
5074
	public static function reconnection_completed() {
5075
		self::state( 'message', 'reconnection_completed' );
5076
	}
5077
5078
	/**
5079
	 * Get our assumed site creation date.
5080
	 * Calculated based on the earlier date of either:
5081
	 * - Earliest admin user registration date.
5082
	 * - Earliest date of post of any post type.
5083
	 *
5084
	 * @since 7.2.0
5085
	 * @deprecated since 7.8.0
5086
	 *
5087
	 * @return string Assumed site creation date and time.
5088
	 */
5089
	public static function get_assumed_site_creation_date() {
5090
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5091
		return self::connection()->get_assumed_site_creation_date();
5092
	}
5093
5094 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5095
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5096
5097
		if ( $activation_source_name ) {
5098
			$args['_as'] = urlencode( $activation_source_name );
5099
		}
5100
5101
		if ( $activation_source_keyword ) {
5102
			$args['_ak'] = urlencode( $activation_source_keyword );
5103
		}
5104
	}
5105
5106
	function build_reconnect_url( $raw = false ) {
5107
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5108
		return $raw ? $url : esc_url( $url );
5109
	}
5110
5111
	public static function admin_url( $args = null ) {
5112
		$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...
5113
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5114
		return $url;
5115
	}
5116
5117
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5118
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5119
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5120
	}
5121
5122
	function dismiss_jetpack_notice() {
5123
5124
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5125
			return;
5126
		}
5127
5128
		switch ( $_GET['jetpack-notice'] ) {
5129
			case 'dismiss':
5130
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5131
5132
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5133
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5134
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5135
				}
5136
				break;
5137
		}
5138
	}
5139
5140
	public static function sort_modules( $a, $b ) {
5141
		if ( $a['sort'] == $b['sort'] ) {
5142
			return 0;
5143
		}
5144
5145
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5146
	}
5147
5148
	function ajax_recheck_ssl() {
5149
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5150
		$result = self::permit_ssl( true );
5151
		wp_send_json(
5152
			array(
5153
				'enabled' => $result,
5154
				'message' => get_transient( 'jetpack_https_test_message' ),
5155
			)
5156
		);
5157
	}
5158
5159
	/* Client API */
5160
5161
	/**
5162
	 * Returns the requested Jetpack API URL
5163
	 *
5164
	 * @deprecated since 7.7
5165
	 * @return string
5166
	 */
5167
	public static function api_url( $relative_url ) {
5168
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5169
		$connection = self::connection();
5170
		return $connection->api_url( $relative_url );
5171
	}
5172
5173
	/**
5174
	 * @deprecated 8.0
5175
	 *
5176
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5177
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5178
	 */
5179
	public static function fix_url_for_bad_hosts( $url ) {
5180
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5181
		return $url;
5182
	}
5183
5184
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5185
		// Default to a blog token.
5186
		$token_type = 'blog';
5187
5188
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5189
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5190
			if ( ! empty( $_GET['onboarding'] ) ) {
5191
				$jpo = $_GET;
5192
			} else {
5193
				$jpo = json_decode( $request_data, true );
5194
			}
5195
5196
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5197
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5198
5199
			if (
5200
				isset( $jpo_user )
5201
				&& isset( $jpo_token )
5202
				&& is_email( $jpo_user )
5203
				&& ctype_alnum( $jpo_token )
5204
				&& isset( $_GET['rest_route'] )
5205
				&& self::validate_onboarding_token_action(
5206
					$jpo_token,
5207
					$_GET['rest_route']
5208
				)
5209
			) {
5210
				$jp_user = get_user_by( 'email', $jpo_user );
5211
				if ( is_a( $jp_user, 'WP_User' ) ) {
5212
					wp_set_current_user( $jp_user->ID );
5213
					$user_can = is_multisite()
5214
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5215
						: current_user_can( 'manage_options' );
5216
					if ( $user_can ) {
5217
						$token_type              = 'user';
5218
						$token->external_user_id = $jp_user->ID;
5219
					}
5220
				}
5221
			}
5222
5223
			$token_data['type']    = $token_type;
5224
			$token_data['user_id'] = $token->external_user_id;
5225
		}
5226
5227
		return $token_data;
5228
	}
5229
5230
	/**
5231
	 * Create a random secret for validating onboarding payload
5232
	 *
5233
	 * @return string Secret token
5234
	 */
5235
	public static function create_onboarding_token() {
5236
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5237
			$token = wp_generate_password( 32, false );
5238
			Jetpack_Options::update_option( 'onboarding', $token );
5239
		}
5240
5241
		return $token;
5242
	}
5243
5244
	/**
5245
	 * Remove the onboarding token
5246
	 *
5247
	 * @return bool True on success, false on failure
5248
	 */
5249
	public static function invalidate_onboarding_token() {
5250
		return Jetpack_Options::delete_option( 'onboarding' );
5251
	}
5252
5253
	/**
5254
	 * Validate an onboarding token for a specific action
5255
	 *
5256
	 * @return boolean True if token/action pair is accepted, false if not
5257
	 */
5258
	public static function validate_onboarding_token_action( $token, $action ) {
5259
		// Compare tokens, bail if tokens do not match
5260
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5261
			return false;
5262
		}
5263
5264
		// List of valid actions we can take
5265
		$valid_actions = array(
5266
			'/jetpack/v4/settings',
5267
		);
5268
5269
		// Only allow valid actions.
5270
		if ( ! in_array( $action, $valid_actions ) ) {
5271
			return false;
5272
		}
5273
5274
		return true;
5275
	}
5276
5277
	/**
5278
	 * Checks to see if the URL is using SSL to connect with Jetpack
5279
	 *
5280
	 * @since 2.3.3
5281
	 * @return boolean
5282
	 */
5283
	public static function permit_ssl( $force_recheck = false ) {
5284
		// Do some fancy tests to see if ssl is being supported
5285
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5286
			$message = '';
5287
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5288
				$ssl = 0;
5289
			} else {
5290
				$ssl = 1;
5291
5292
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5293
					$ssl     = 0;
5294
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5295
				} else {
5296
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5297
					if ( is_wp_error( $response ) ) {
5298
						$ssl     = 0;
5299
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5300
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5301
						$ssl     = 0;
5302
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5303
					}
5304
				}
5305
			}
5306
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5307
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5308
		}
5309
5310
		return (bool) $ssl;
5311
	}
5312
5313
	/*
5314
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5315
	 */
5316
	public function alert_auto_ssl_fail() {
5317
		if ( ! current_user_can( 'manage_options' ) ) {
5318
			return;
5319
		}
5320
5321
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5322
		?>
5323
5324
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5325
			<div class="jp-banner__content">
5326
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5327
				<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>
5328
				<p>
5329
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5330
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5331
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5332
				</p>
5333
				<p>
5334
					<?php
5335
					printf(
5336
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5337
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5338
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5339
					);
5340
					?>
5341
				</p>
5342
			</div>
5343
		</div>
5344
		<style>
5345
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5346
		</style>
5347
		<script type="text/javascript">
5348
			jQuery( document ).ready( function( $ ) {
5349
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5350
					var $this = $( this );
5351
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5352
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5353
					e.preventDefault();
5354
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5355
					$.post( ajaxurl, data )
5356
					  .done( function( response ) {
5357
						  if ( response.enabled ) {
5358
							  $( '#jetpack-ssl-warning' ).hide();
5359
						  } else {
5360
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5361
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5362
						  }
5363
					  }.bind( $this ) );
5364
				} );
5365
			} );
5366
		</script>
5367
5368
		<?php
5369
	}
5370
5371
	/**
5372
	 * Returns the Jetpack XML-RPC API
5373
	 *
5374
	 * @deprecated 8.0 Use Connection_Manager instead.
5375
	 * @return string
5376
	 */
5377
	public static function xmlrpc_api_url() {
5378
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5379
		return self::connection()->xmlrpc_api_url();
5380
	}
5381
5382
	/**
5383
	 * Returns the connection manager object.
5384
	 *
5385
	 * @return Automattic\Jetpack\Connection\Manager
5386
	 */
5387
	public static function connection() {
5388
		$jetpack = static::init();
5389
5390
		// If the connection manager hasn't been instantiated, do that now.
5391
		if ( ! $jetpack->connection_manager ) {
5392
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5393
		}
5394
5395
		return $jetpack->connection_manager;
5396
	}
5397
5398
	/**
5399
	 * Creates two secret tokens and the end of life timestamp for them.
5400
	 *
5401
	 * Note these tokens are unique per call, NOT static per site for connecting.
5402
	 *
5403
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5404
	 *
5405
	 * @since 2.6
5406
	 * @param String  $action  The action name.
5407
	 * @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...
5408
	 * @param Integer $exp     Expiration time in seconds.
5409
	 * @return array
5410
	 */
5411
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5412
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5413
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5414
	}
5415
5416
	public static function get_secrets( $action, $user_id ) {
5417
		$secrets = ( new Secrets() )->get( $action, $user_id );
5418
5419
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5420
			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...
5421
		}
5422
5423
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5424
			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...
5425
		}
5426
5427
		return $secrets;
5428
	}
5429
5430
	/**
5431
	 * Builds the timeout limit for queries talking with the wpcom servers.
5432
	 *
5433
	 * Based on local php max_execution_time in php.ini
5434
	 *
5435
	 * @since 2.6
5436
	 * @return int
5437
	 * @deprecated
5438
	 **/
5439
	public function get_remote_query_timeout_limit() {
5440
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5441
		return self::get_max_execution_time();
5442
	}
5443
5444
	/**
5445
	 * Builds the timeout limit for queries talking with the wpcom servers.
5446
	 *
5447
	 * Based on local php max_execution_time in php.ini
5448
	 *
5449
	 * @since 5.4
5450
	 * @return int
5451
	 **/
5452
	public static function get_max_execution_time() {
5453
		$timeout = (int) ini_get( 'max_execution_time' );
5454
5455
		// Ensure exec time set in php.ini
5456
		if ( ! $timeout ) {
5457
			$timeout = 30;
5458
		}
5459
		return $timeout;
5460
	}
5461
5462
	/**
5463
	 * Sets a minimum request timeout, and returns the current timeout
5464
	 *
5465
	 * @since 5.4
5466
	 **/
5467 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5468
		$timeout = self::get_max_execution_time();
5469
		if ( $timeout < $min_timeout ) {
5470
			$timeout = $min_timeout;
5471
			set_time_limit( $timeout );
5472
		}
5473
		return $timeout;
5474
	}
5475
5476
	/**
5477
	 * Takes the response from the Jetpack register new site endpoint and
5478
	 * verifies it worked properly.
5479
	 *
5480
	 * @since 2.6
5481
	 * @deprecated since 7.7.0
5482
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5483
	 **/
5484
	public function validate_remote_register_response() {
5485
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5486
	}
5487
5488
	/**
5489
	 * @return bool|WP_Error
5490
	 */
5491
	public static function register() {
5492
		$tracking = new Tracking();
5493
		$tracking->record_user_event( 'jpc_register_begin' );
5494
5495
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5496
5497
		$connection   = self::connection();
5498
		$registration = $connection->register();
5499
5500
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5501
5502
		if ( ! $registration || is_wp_error( $registration ) ) {
5503
			return $registration;
5504
		}
5505
5506
		return true;
5507
	}
5508
5509
	/**
5510
	 * Filters the registration request body to include tracking properties.
5511
	 *
5512
	 * @param array $properties
5513
	 * @return array amended properties.
5514
	 */
5515 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5516
		$tracking        = new Tracking();
5517
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5518
5519
		return array_merge(
5520
			$properties,
5521
			array(
5522
				'_ui' => $tracks_identity['_ui'],
5523
				'_ut' => $tracks_identity['_ut'],
5524
			)
5525
		);
5526
	}
5527
5528
	/**
5529
	 * Filters the token request body to include tracking properties.
5530
	 *
5531
	 * @param array $properties
5532
	 * @return array amended properties.
5533
	 */
5534 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5535
		$tracking        = new Tracking();
5536
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5537
5538
		return array_merge(
5539
			$properties,
5540
			array(
5541
				'_ui' => $tracks_identity['_ui'],
5542
				'_ut' => $tracks_identity['_ut'],
5543
			)
5544
		);
5545
	}
5546
5547
	/**
5548
	 * If the db version is showing something other that what we've got now, bump it to current.
5549
	 *
5550
	 * @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...
5551
	 */
5552
	public static function maybe_set_version_option() {
5553
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5554
		if ( JETPACK__VERSION != $version ) {
5555
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5556
5557
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5558
				/** This action is documented in class.jetpack.php */
5559
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5560
			}
5561
5562
			return true;
5563
		}
5564
		return false;
5565
	}
5566
5567
	/* Client Server API */
5568
5569
	/**
5570
	 * Loads the Jetpack XML-RPC client.
5571
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5572
	 *
5573
	 * @deprecated since 7.7.0
5574
	 */
5575
	public static function load_xml_rpc_client() {
5576
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5577
	}
5578
5579
	/**
5580
	 * Resets the saved authentication state in between testing requests.
5581
	 *
5582
	 * @deprecated since 8.9.0
5583
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5584
	 */
5585
	public function reset_saved_auth_state() {
5586
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5587
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5588
	}
5589
5590
	/**
5591
	 * Verifies the signature of the current request.
5592
	 *
5593
	 * @deprecated since 7.7.0
5594
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5595
	 *
5596
	 * @return false|array
5597
	 */
5598
	public function verify_xml_rpc_signature() {
5599
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5600
		return self::connection()->verify_xml_rpc_signature();
5601
	}
5602
5603
	/**
5604
	 * Verifies the signature of the current request.
5605
	 *
5606
	 * This function has side effects and should not be used. Instead,
5607
	 * use the memoized version `->verify_xml_rpc_signature()`.
5608
	 *
5609
	 * @deprecated since 7.7.0
5610
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5611
	 * @internal
5612
	 */
5613
	private function internal_verify_xml_rpc_signature() {
5614
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5615
	}
5616
5617
	/**
5618
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5619
	 *
5620
	 * @deprecated since 7.7.0
5621
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5622
	 *
5623
	 * @param \WP_User|mixed $user     User object if authenticated.
5624
	 * @param string         $username Username.
5625
	 * @param string         $password Password string.
5626
	 * @return \WP_User|mixed Authenticated user or error.
5627
	 */
5628 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5629
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5630
5631
		if ( ! $this->connection_manager ) {
5632
			$this->connection_manager = new Connection_Manager();
5633
		}
5634
5635
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5636
	}
5637
5638
	/**
5639
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5640
	 * Uses the existing XMLRPC request signing implementation.
5641
	 *
5642
	 * @deprecated since 8.9.0
5643
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5644
	 */
5645
	function wp_rest_authenticate( $user ) {
5646
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5647
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5648
	}
5649
5650
	/**
5651
	 * Report authentication status to the WP REST API.
5652
	 *
5653
	 * @deprecated since 8.9.0
5654
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5655
	 *
5656
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5657
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5658
	 */
5659
	public function wp_rest_authentication_errors( $value ) {
5660
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5661
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5662
	}
5663
5664
	/**
5665
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5666
	 * Capture it here so we can verify the signature later.
5667
	 *
5668
	 * @deprecated since 7.7.0
5669
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5670
	 *
5671
	 * @param array $methods XMLRPC methods.
5672
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5673
	 */
5674 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5675
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5676
5677
		if ( ! $this->connection_manager ) {
5678
			$this->connection_manager = new Connection_Manager();
5679
		}
5680
5681
		return $this->connection_manager->xmlrpc_methods( $methods );
5682
	}
5683
5684
	/**
5685
	 * Register additional public XMLRPC methods.
5686
	 *
5687
	 * @deprecated since 7.7.0
5688
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5689
	 *
5690
	 * @param array $methods Public XMLRPC methods.
5691
	 * @return array Public XMLRPC methods, with the getOptions one.
5692
	 */
5693 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5694
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5695
5696
		if ( ! $this->connection_manager ) {
5697
			$this->connection_manager = new Connection_Manager();
5698
		}
5699
5700
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5701
	}
5702
5703
	/**
5704
	 * Handles a getOptions XMLRPC method call.
5705
	 *
5706
	 * @deprecated since 7.7.0
5707
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5708
	 *
5709
	 * @param array $args method call arguments.
5710
	 * @return array an amended XMLRPC server options array.
5711
	 */
5712 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5713
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5714
5715
		if ( ! $this->connection_manager ) {
5716
			$this->connection_manager = new Connection_Manager();
5717
		}
5718
5719
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
Bug introduced by
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
5720
	}
5721
5722
	/**
5723
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5724
	 *
5725
	 * @deprecated since 7.7.0
5726
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5727
	 *
5728
	 * @param array $options Standard Core options.
5729
	 * @return array Amended options.
5730
	 */
5731 View Code Duplication
	public function xmlrpc_options( $options ) {
5732
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5733
5734
		if ( ! $this->connection_manager ) {
5735
			$this->connection_manager = new Connection_Manager();
5736
		}
5737
5738
		return $this->connection_manager->xmlrpc_options( $options );
5739
	}
5740
5741
	/**
5742
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5743
	 * SET: state( $key, $value );
5744
	 * GET: $value = state( $key );
5745
	 *
5746
	 * @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...
5747
	 * @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...
5748
	 * @param bool   $restate private
5749
	 */
5750
	public static function state( $key = null, $value = null, $restate = false ) {
5751
		static $state = array();
5752
		static $path, $domain;
5753
		if ( ! isset( $path ) ) {
5754
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5755
			$admin_url = self::admin_url();
5756
			$bits      = wp_parse_url( $admin_url );
5757
5758
			if ( is_array( $bits ) ) {
5759
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5760
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5761
			} else {
5762
				$path = $domain = null;
5763
			}
5764
		}
5765
5766
		// Extract state from cookies and delete cookies
5767
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5768
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5769
			unset( $_COOKIE['jetpackState'] );
5770
			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...
5771
				if ( strlen( $v ) ) {
5772
					$state[ $k ] = $v;
5773
				}
5774
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5775
			}
5776
		}
5777
5778
		if ( $restate ) {
5779
			foreach ( $state as $k => $v ) {
5780
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5781
			}
5782
			return;
5783
		}
5784
5785
		// Get a state variable.
5786
		if ( isset( $key ) && ! isset( $value ) ) {
5787
			if ( array_key_exists( $key, $state ) ) {
5788
				return $state[ $key ];
5789
			}
5790
			return null;
5791
		}
5792
5793
		// Set a state variable.
5794
		if ( isset( $key ) && isset( $value ) ) {
5795
			if ( is_array( $value ) && isset( $value[0] ) ) {
5796
				$value = $value[0];
5797
			}
5798
			$state[ $key ] = $value;
5799
			if ( ! headers_sent() ) {
5800
				if ( self::should_set_cookie( $key ) ) {
5801
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5802
				}
5803
			}
5804
		}
5805
	}
5806
5807
	public static function restate() {
5808
		self::state( null, null, true );
5809
	}
5810
5811
	/**
5812
	 * Determines whether the jetpackState[$key] value should be added to the
5813
	 * cookie.
5814
	 *
5815
	 * @param string $key The state key.
5816
	 *
5817
	 * @return boolean Whether the value should be added to the cookie.
5818
	 */
5819
	public static function should_set_cookie( $key ) {
5820
		global $current_screen;
5821
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5822
5823
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5824
			return false;
5825
		}
5826
5827
		return true;
5828
	}
5829
5830
	public static function check_privacy( $file ) {
5831
		static $is_site_publicly_accessible = null;
5832
5833
		if ( is_null( $is_site_publicly_accessible ) ) {
5834
			$is_site_publicly_accessible = false;
5835
5836
			$rpc = new Jetpack_IXR_Client();
5837
5838
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5839
			if ( $success ) {
5840
				$response = $rpc->getResponse();
5841
				if ( $response ) {
5842
					$is_site_publicly_accessible = true;
5843
				}
5844
			}
5845
5846
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5847
		}
5848
5849
		if ( $is_site_publicly_accessible ) {
5850
			return;
5851
		}
5852
5853
		$module_slug = self::get_module_slug( $file );
5854
5855
		$privacy_checks = self::state( 'privacy_checks' );
5856
		if ( ! $privacy_checks ) {
5857
			$privacy_checks = $module_slug;
5858
		} else {
5859
			$privacy_checks .= ",$module_slug";
5860
		}
5861
5862
		self::state( 'privacy_checks', $privacy_checks );
5863
	}
5864
5865
	/**
5866
	 * Helper method for multicall XMLRPC.
5867
	 *
5868
	 * @deprecated since 8.9.0
5869
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5870
	 *
5871
	 * @param ...$args Args for the async_call.
5872
	 */
5873
	public static function xmlrpc_async_call( ...$args ) {
5874
5875
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5876
5877
		global $blog_id;
5878
		static $clients = array();
5879
5880
		$client_blog_id = is_multisite() ? $blog_id : 0;
5881
5882
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5883
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5884
			if ( function_exists( 'ignore_user_abort' ) ) {
5885
				ignore_user_abort( true );
5886
			}
5887
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5888
		}
5889
5890
		if ( ! empty( $args[0] ) ) {
5891
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5892
		} elseif ( is_multisite() ) {
5893
			foreach ( $clients as $client_blog_id => $client ) {
5894
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5895
					continue;
5896
				}
5897
5898
				$switch_success = switch_to_blog( $client_blog_id, true );
5899
				if ( ! $switch_success ) {
5900
					continue;
5901
				}
5902
5903
				flush();
5904
				$client->query();
5905
5906
				restore_current_blog();
5907
			}
5908
		} else {
5909
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5910
				flush();
5911
				$clients[0]->query();
5912
			}
5913
		}
5914
	}
5915
5916
	/**
5917
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5918
	 *
5919
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5920
	 *
5921
	 * @param string $url WordPress.com static resource URL.
5922
	 */
5923
	public static function staticize_subdomain( $url ) {
5924
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5925
		return Assets::staticize_subdomain( $url );
5926
	}
5927
5928
	/* JSON API Authorization */
5929
5930
	/**
5931
	 * Handles the login action for Authorizing the JSON API
5932
	 */
5933
	function login_form_json_api_authorization() {
5934
		$this->verify_json_api_authorization_request();
5935
5936
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5937
5938
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5939
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5940
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5941
	}
5942
5943
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5944
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5945
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5946
			return $url;
5947
		}
5948
5949
		$parsed_url = wp_parse_url( $url );
5950
		$url        = strtok( $url, '?' );
5951
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5952
		if ( ! empty( $parsed_url['query'] ) ) {
5953
			$url .= "&{$parsed_url['query']}";
5954
		}
5955
5956
		return $url;
5957
	}
5958
5959
	// Make sure the POSTed request is handled by the same action
5960
	function preserve_action_in_login_form_for_json_api_authorization() {
5961
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5962
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5963
	}
5964
5965
	// If someone logs in to approve API access, store the Access Code in usermeta
5966
	function store_json_api_authorization_token( $user_login, $user ) {
5967
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5968
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5969
		$token = wp_generate_password( 32, false );
5970
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5971
	}
5972
5973
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5974
	function allow_wpcom_public_api_domain( $domains ) {
5975
		$domains[] = 'public-api.wordpress.com';
5976
		return $domains;
5977
	}
5978
5979
	static function is_redirect_encoded( $redirect_url ) {
5980
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5981
	}
5982
5983
	// Add all wordpress.com environments to the safe redirect allowed list.
5984
	function allow_wpcom_environments( $domains ) {
5985
		$domains[] = 'wordpress.com';
5986
		$domains[] = 'wpcalypso.wordpress.com';
5987
		$domains[] = 'horizon.wordpress.com';
5988
		$domains[] = 'calypso.localhost';
5989
		return $domains;
5990
	}
5991
5992
	// Add the Access Code details to the public-api.wordpress.com redirect
5993
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5994
		return add_query_arg(
5995
			urlencode_deep(
5996
				array(
5997
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5998
					'jetpack-user-id' => (int) $user->ID,
5999
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6000
				)
6001
			),
6002
			$redirect_to
6003
		);
6004
	}
6005
6006
	/**
6007
	 * Verifies the request by checking the signature
6008
	 *
6009
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6010
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6011
	 *
6012
	 * @param null|array $environment
6013
	 */
6014
	function verify_json_api_authorization_request( $environment = null ) {
6015
		$environment = is_null( $environment )
6016
			? $_REQUEST
6017
			: $environment;
6018
6019
		//phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
6020
		list( $env_token, $env_version, $env_user_id ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $env_version 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...
6021
		$token = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
6022
		if ( ! $token || empty( $token->secret ) ) {
6023
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6024
		}
6025
6026
		$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' );
6027
6028
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6029
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6030
			/**
6031
			 * Jetpack authorisation request Error.
6032
			 *
6033
			 * @since 7.5.0
6034
			 */
6035
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6036
			$die_error = sprintf(
6037
				/* translators: %s is a URL */
6038
				__( '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' ),
6039
				Redirect::get_url( 'jetpack-support-double-encoding' )
6040
			);
6041
		}
6042
6043
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6044
6045
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6046
			$signature = $jetpack_signature->sign_request(
6047
				$environment['token'],
6048
				$environment['timestamp'],
6049
				$environment['nonce'],
6050
				'',
6051
				'GET',
6052
				$environment['jetpack_json_api_original_query'],
6053
				null,
6054
				true
6055
			);
6056
		} else {
6057
			$signature = $jetpack_signature->sign_current_request(
6058
				array(
6059
					'body'   => null,
6060
					'method' => 'GET',
6061
				)
6062
			);
6063
		}
6064
6065
		if ( ! $signature ) {
6066
			wp_die( $die_error );
6067
		} elseif ( is_wp_error( $signature ) ) {
6068
			wp_die( $die_error );
6069
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6070
			if ( is_ssl() ) {
6071
				// 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
6072
				$signature = $jetpack_signature->sign_current_request(
6073
					array(
6074
						'scheme' => 'http',
6075
						'body'   => null,
6076
						'method' => 'GET',
6077
					)
6078
				);
6079
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6080
					wp_die( $die_error );
6081
				}
6082
			} else {
6083
				wp_die( $die_error );
6084
			}
6085
		}
6086
6087
		$timestamp = (int) $environment['timestamp'];
6088
		$nonce     = stripslashes( (string) $environment['nonce'] );
6089
6090
		if ( ! $this->connection_manager ) {
6091
			$this->connection_manager = new Connection_Manager();
6092
		}
6093
6094
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
6095
			// De-nonce the nonce, at least for 5 minutes.
6096
			// 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)
6097
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6098
			if ( $old_nonce_time < time() - 300 ) {
6099
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6100
			}
6101
		}
6102
6103
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6104
		$data_filters = array(
6105
			'state'        => 'opaque',
6106
			'client_id'    => 'int',
6107
			'client_title' => 'string',
6108
			'client_image' => 'url',
6109
		);
6110
6111
		foreach ( $data_filters as $key => $sanitation ) {
6112
			if ( ! isset( $data->$key ) ) {
6113
				wp_die( $die_error );
6114
			}
6115
6116
			switch ( $sanitation ) {
6117
				case 'int':
6118
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6119
					break;
6120
				case 'opaque':
6121
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6122
					break;
6123
				case 'string':
6124
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6125
					break;
6126
				case 'url':
6127
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6128
					break;
6129
			}
6130
		}
6131
6132
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6133
			wp_die( $die_error );
6134
		}
6135
	}
6136
6137
	function login_message_json_api_authorization( $message ) {
6138
		return '<p class="message">' . sprintf(
6139
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6140
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6141
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6142
	}
6143
6144
	/**
6145
	 * Get $content_width, but with a <s>twist</s> filter.
6146
	 */
6147
	public static function get_content_width() {
6148
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6149
			? $GLOBALS['content_width']
6150
			: false;
6151
		/**
6152
		 * Filter the Content Width value.
6153
		 *
6154
		 * @since 2.2.3
6155
		 *
6156
		 * @param string $content_width Content Width value.
6157
		 */
6158
		return apply_filters( 'jetpack_content_width', $content_width );
6159
	}
6160
6161
	/**
6162
	 * Pings the WordPress.com Mirror Site for the specified options.
6163
	 *
6164
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6165
	 *
6166
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6167
	 */
6168
	public function get_cloud_site_options( $option_names ) {
6169
		$option_names = array_filter( (array) $option_names, 'is_string' );
6170
6171
		$xml = new Jetpack_IXR_Client();
6172
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6173
		if ( $xml->isError() ) {
6174
			return array(
6175
				'error_code' => $xml->getErrorCode(),
6176
				'error_msg'  => $xml->getErrorMessage(),
6177
			);
6178
		}
6179
		$cloud_site_options = $xml->getResponse();
6180
6181
		return $cloud_site_options;
6182
	}
6183
6184
	/**
6185
	 * Checks if the site is currently in an identity crisis.
6186
	 *
6187
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6188
	 */
6189 View Code Duplication
	public static function check_identity_crisis() {
6190
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6191
			return false;
6192
		}
6193
6194
		return Jetpack_Options::get_option( 'sync_error_idc' );
6195
	}
6196
6197
	/**
6198
	 * Checks whether the home and siteurl specifically are allowed.
6199
	 * Written so that we don't have re-check $key and $value params every time
6200
	 * we want to check if this site is allowed, for example in footer.php
6201
	 *
6202
	 * @since  3.8.0
6203
	 * @return bool True = already allowed False = not on the allowed list.
6204
	 */
6205
	public static function is_staging_site() {
6206
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6207
		return ( new Status() )->is_staging_site();
6208
	}
6209
6210
	/**
6211
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6212
	 *
6213
	 * @since 4.4.0
6214
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6215
	 *
6216
	 * @return bool
6217
	 */
6218 View Code Duplication
	public static function validate_sync_error_idc_option() {
6219
		$is_valid = false;
6220
6221
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6222
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6223
		if ( $sync_error && self::sync_idc_optin() ) {
6224
			$local_options = self::get_sync_error_idc_option();
6225
			// Ensure all values are set.
6226
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6227
6228
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6229
				if (
6230
						isset( $sync_error['wpcom_home'] ) &&
6231
						isset( $sync_error['wpcom_siteurl'] ) &&
6232
						$sync_error['wpcom_home'] === $local_options['home'] &&
6233
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6234
				) {
6235
					$is_valid = false;
6236
					// Enable migrate_for_idc so that sync actions are accepted.
6237
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6238
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6239
					$is_valid = true;
6240
				}
6241
			}
6242
		}
6243
6244
		/**
6245
		 * Filters whether the sync_error_idc option is valid.
6246
		 *
6247
		 * @since 4.4.0
6248
		 *
6249
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6250
		 */
6251
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6252
6253
		if ( ! $is_valid && $sync_error ) {
6254
			// Since the option exists, and did not validate, delete it
6255
			Jetpack_Options::delete_option( 'sync_error_idc' );
6256
		}
6257
6258
		return $is_valid;
6259
	}
6260
6261
	/**
6262
	 * Normalizes a url by doing three things:
6263
	 *  - Strips protocol
6264
	 *  - Strips www
6265
	 *  - Adds a trailing slash
6266
	 *
6267
	 * @since 4.4.0
6268
	 * @param string $url
6269
	 * @return WP_Error|string
6270
	 */
6271 View Code Duplication
	public static function normalize_url_protocol_agnostic( $url ) {
6272
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6273
		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...
6274
			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...
6275
		}
6276
6277
		// Strip www and protocols
6278
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6279
		return $url;
6280
	}
6281
6282
	/**
6283
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6284
	 *
6285
	 * @since 4.4.0
6286
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6287
	 *
6288
	 * @param array $response
6289
	 * @return array Array of the local urls, wpcom urls, and error code
6290
	 */
6291 View Code Duplication
	public static function get_sync_error_idc_option( $response = array() ) {
6292
		// Since the local options will hit the database directly, store the values
6293
		// in a transient to allow for autoloading and caching on subsequent views.
6294
		$local_options = get_transient( 'jetpack_idc_local' );
6295
		if ( false === $local_options ) {
6296
			$local_options = array(
6297
				'home'    => Functions::home_url(),
6298
				'siteurl' => Functions::site_url(),
6299
			);
6300
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6301
		}
6302
6303
		$options = array_merge( $local_options, $response );
6304
6305
		$returned_values = array();
6306
		foreach ( $options as $key => $option ) {
6307
			if ( 'error_code' === $key ) {
6308
				$returned_values[ $key ] = $option;
6309
				continue;
6310
			}
6311
6312
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6313
				continue;
6314
			}
6315
6316
			$returned_values[ $key ] = $normalized_url;
6317
		}
6318
6319
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6320
6321
		return $returned_values;
6322
	}
6323
6324
	/**
6325
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6326
	 * If set to true, the site will be put into staging mode.
6327
	 *
6328
	 * @since 4.3.2
6329
	 * @return bool
6330
	 */
6331 View Code Duplication
	public static function sync_idc_optin() {
6332
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6333
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6334
		} else {
6335
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6336
		}
6337
6338
		/**
6339
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
6340
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
6341
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6342
		 *
6343
		 * @since 4.3.2
6344
		 *
6345
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6346
		 */
6347
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6348
	}
6349
6350
	/**
6351
	 * Maybe Use a .min.css stylesheet, maybe not.
6352
	 *
6353
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6354
	 */
6355
	public static function maybe_min_asset( $url, $path, $plugin ) {
6356
		// Short out on things trying to find actual paths.
6357
		if ( ! $path || empty( $plugin ) ) {
6358
			return $url;
6359
		}
6360
6361
		$path = ltrim( $path, '/' );
6362
6363
		// Strip out the abspath.
6364
		$base = dirname( plugin_basename( $plugin ) );
6365
6366
		// Short out on non-Jetpack assets.
6367
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6368
			return $url;
6369
		}
6370
6371
		// File name parsing.
6372
		$file              = "{$base}/{$path}";
6373
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6374
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6375
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6376
		$extension         = array_shift( $file_name_parts_r );
6377
6378
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6379
			// Already pointing at the minified version.
6380
			if ( 'min' === $file_name_parts_r[0] ) {
6381
				return $url;
6382
			}
6383
6384
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6385
			if ( file_exists( $min_full_path ) ) {
6386
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6387
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6388
				if ( 'css' === $extension ) {
6389
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6390
					self::$min_assets[ $key ] = $path;
6391
				}
6392
			}
6393
		}
6394
6395
		return $url;
6396
	}
6397
6398
	/**
6399
	 * If the asset is minified, let's flag .min as the suffix.
6400
	 *
6401
	 * Attached to `style_loader_src` filter.
6402
	 *
6403
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

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

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

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

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

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

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

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

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

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

Loading history...
6406
	 */
6407
	public static function set_suffix_on_min( $src, $handle ) {
6408
		if ( false === strpos( $src, '.min.css' ) ) {
6409
			return $src;
6410
		}
6411
6412
		if ( ! empty( self::$min_assets ) ) {
6413
			foreach ( self::$min_assets as $file => $path ) {
6414
				if ( false !== strpos( $src, $file ) ) {
6415
					wp_style_add_data( $handle, 'suffix', '.min' );
6416
					return $src;
6417
				}
6418
			}
6419
		}
6420
6421
		return $src;
6422
	}
6423
6424
	/**
6425
	 * Maybe inlines a stylesheet.
6426
	 *
6427
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6428
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6429
	 *
6430
	 * Attached to `style_loader_tag` filter.
6431
	 *
6432
	 * @param string $tag The tag that would link to the external asset.
6433
	 * @param string $handle The registered handle of the script in question.
6434
	 *
6435
	 * @return string
6436
	 */
6437
	public static function maybe_inline_style( $tag, $handle ) {
6438
		global $wp_styles;
6439
		$item = $wp_styles->registered[ $handle ];
6440
6441
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6442
			return $tag;
6443
		}
6444
6445
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6446
			$href = $matches[1];
6447
			// Strip off query string
6448
			if ( $pos = strpos( $href, '?' ) ) {
6449
				$href = substr( $href, 0, $pos );
6450
			}
6451
			// Strip off fragment
6452
			if ( $pos = strpos( $href, '#' ) ) {
6453
				$href = substr( $href, 0, $pos );
6454
			}
6455
		} else {
6456
			return $tag;
6457
		}
6458
6459
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6460
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6461
			return $tag;
6462
		}
6463
6464
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6465
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6466
			// And this isn't the pass that actually deals with the RTL version...
6467
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6468
				// Short out, as the RTL version will deal with it in a moment.
6469
				return $tag;
6470
			}
6471
		}
6472
6473
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6474
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6475
		if ( $css ) {
6476
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6477
			if ( empty( $item->extra['after'] ) ) {
6478
				wp_add_inline_style( $handle, $css );
6479
			} else {
6480
				array_unshift( $item->extra['after'], $css );
6481
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6482
			}
6483
		}
6484
6485
		return $tag;
6486
	}
6487
6488
	/**
6489
	 * Loads a view file from the views
6490
	 *
6491
	 * Data passed in with the $data parameter will be available in the
6492
	 * template file as $data['value']
6493
	 *
6494
	 * @param string $template - Template file to load
6495
	 * @param array  $data - Any data to pass along to the template
6496
	 * @return boolean - If template file was found
6497
	 **/
6498
	public function load_view( $template, $data = array() ) {
6499
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6500
6501
		if ( file_exists( $views_dir . $template ) ) {
6502
			require_once $views_dir . $template;
6503
			return true;
6504
		}
6505
6506
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6507
		return false;
6508
	}
6509
6510
	/**
6511
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6512
	 */
6513
	public function deprecated_hooks() {
6514
		$filter_deprecated_list = array(
6515
			'jetpack_bail_on_shortcode'                    => array(
6516
				'replacement' => 'jetpack_shortcodes_to_include',
6517
				'version'     => 'jetpack-3.1.0',
6518
			),
6519
			'wpl_sharing_2014_1'                           => array(
6520
				'replacement' => null,
6521
				'version'     => 'jetpack-3.6.0',
6522
			),
6523
			'jetpack-tools-to-include'                     => array(
6524
				'replacement' => 'jetpack_tools_to_include',
6525
				'version'     => 'jetpack-3.9.0',
6526
			),
6527
			'jetpack_identity_crisis_options_to_check'     => array(
6528
				'replacement' => null,
6529
				'version'     => 'jetpack-4.0.0',
6530
			),
6531
			'update_option_jetpack_single_user_site'       => array(
6532
				'replacement' => null,
6533
				'version'     => 'jetpack-4.3.0',
6534
			),
6535
			'audio_player_default_colors'                  => array(
6536
				'replacement' => null,
6537
				'version'     => 'jetpack-4.3.0',
6538
			),
6539
			'add_option_jetpack_featured_images_enabled'   => array(
6540
				'replacement' => null,
6541
				'version'     => 'jetpack-4.3.0',
6542
			),
6543
			'add_option_jetpack_update_details'            => array(
6544
				'replacement' => null,
6545
				'version'     => 'jetpack-4.3.0',
6546
			),
6547
			'add_option_jetpack_updates'                   => array(
6548
				'replacement' => null,
6549
				'version'     => 'jetpack-4.3.0',
6550
			),
6551
			'add_option_jetpack_network_name'              => array(
6552
				'replacement' => null,
6553
				'version'     => 'jetpack-4.3.0',
6554
			),
6555
			'add_option_jetpack_network_allow_new_registrations' => array(
6556
				'replacement' => null,
6557
				'version'     => 'jetpack-4.3.0',
6558
			),
6559
			'add_option_jetpack_network_add_new_users'     => array(
6560
				'replacement' => null,
6561
				'version'     => 'jetpack-4.3.0',
6562
			),
6563
			'add_option_jetpack_network_site_upload_space' => array(
6564
				'replacement' => null,
6565
				'version'     => 'jetpack-4.3.0',
6566
			),
6567
			'add_option_jetpack_network_upload_file_types' => array(
6568
				'replacement' => null,
6569
				'version'     => 'jetpack-4.3.0',
6570
			),
6571
			'add_option_jetpack_network_enable_administration_menus' => array(
6572
				'replacement' => null,
6573
				'version'     => 'jetpack-4.3.0',
6574
			),
6575
			'add_option_jetpack_is_multi_site'             => array(
6576
				'replacement' => null,
6577
				'version'     => 'jetpack-4.3.0',
6578
			),
6579
			'add_option_jetpack_is_main_network'           => array(
6580
				'replacement' => null,
6581
				'version'     => 'jetpack-4.3.0',
6582
			),
6583
			'add_option_jetpack_main_network_site'         => array(
6584
				'replacement' => null,
6585
				'version'     => 'jetpack-4.3.0',
6586
			),
6587
			'jetpack_sync_all_registered_options'          => array(
6588
				'replacement' => null,
6589
				'version'     => 'jetpack-4.3.0',
6590
			),
6591
			'jetpack_has_identity_crisis'                  => array(
6592
				'replacement' => 'jetpack_sync_error_idc_validation',
6593
				'version'     => 'jetpack-4.4.0',
6594
			),
6595
			'jetpack_is_post_mailable'                     => array(
6596
				'replacement' => null,
6597
				'version'     => 'jetpack-4.4.0',
6598
			),
6599
			'jetpack_seo_site_host'                        => array(
6600
				'replacement' => null,
6601
				'version'     => 'jetpack-5.1.0',
6602
			),
6603
			'jetpack_installed_plugin'                     => array(
6604
				'replacement' => 'jetpack_plugin_installed',
6605
				'version'     => 'jetpack-6.0.0',
6606
			),
6607
			'jetpack_holiday_snow_option_name'             => array(
6608
				'replacement' => null,
6609
				'version'     => 'jetpack-6.0.0',
6610
			),
6611
			'jetpack_holiday_chance_of_snow'               => array(
6612
				'replacement' => null,
6613
				'version'     => 'jetpack-6.0.0',
6614
			),
6615
			'jetpack_holiday_snow_js_url'                  => array(
6616
				'replacement' => null,
6617
				'version'     => 'jetpack-6.0.0',
6618
			),
6619
			'jetpack_is_holiday_snow_season'               => array(
6620
				'replacement' => null,
6621
				'version'     => 'jetpack-6.0.0',
6622
			),
6623
			'jetpack_holiday_snow_option_updated'          => array(
6624
				'replacement' => null,
6625
				'version'     => 'jetpack-6.0.0',
6626
			),
6627
			'jetpack_holiday_snowing'                      => array(
6628
				'replacement' => null,
6629
				'version'     => 'jetpack-6.0.0',
6630
			),
6631
			'jetpack_sso_auth_cookie_expirtation'          => array(
6632
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6633
				'version'     => 'jetpack-6.1.0',
6634
			),
6635
			'jetpack_cache_plans'                          => array(
6636
				'replacement' => null,
6637
				'version'     => 'jetpack-6.1.0',
6638
			),
6639
6640
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6641
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6642
				'version'     => 'jetpack-6.5.0',
6643
			),
6644
			'jetpack_enable_site_verification'             => array(
6645
				'replacement' => null,
6646
				'version'     => 'jetpack-6.5.0',
6647
			),
6648
			'can_display_jetpack_manage_notice'            => array(
6649
				'replacement' => null,
6650
				'version'     => 'jetpack-7.3.0',
6651
			),
6652
			'atd_http_post_timeout'                        => array(
6653
				'replacement' => null,
6654
				'version'     => 'jetpack-7.3.0',
6655
			),
6656
			'atd_service_domain'                           => array(
6657
				'replacement' => null,
6658
				'version'     => 'jetpack-7.3.0',
6659
			),
6660
			'atd_load_scripts'                             => array(
6661
				'replacement' => null,
6662
				'version'     => 'jetpack-7.3.0',
6663
			),
6664
			'jetpack_widget_authors_exclude'               => array(
6665
				'replacement' => 'jetpack_widget_authors_params',
6666
				'version'     => 'jetpack-7.7.0',
6667
			),
6668
			// Removed in Jetpack 7.9.0
6669
			'jetpack_pwa_manifest'                         => array(
6670
				'replacement' => null,
6671
				'version'     => 'jetpack-7.9.0',
6672
			),
6673
			'jetpack_pwa_background_color'                 => array(
6674
				'replacement' => null,
6675
				'version'     => 'jetpack-7.9.0',
6676
			),
6677
			'jetpack_check_mobile'                         => array(
6678
				'replacement' => null,
6679
				'version'     => 'jetpack-8.3.0',
6680
			),
6681
			'jetpack_mobile_stylesheet'                    => array(
6682
				'replacement' => null,
6683
				'version'     => 'jetpack-8.3.0',
6684
			),
6685
			'jetpack_mobile_template'                      => array(
6686
				'replacement' => null,
6687
				'version'     => 'jetpack-8.3.0',
6688
			),
6689
			'jetpack_mobile_theme_menu'                    => array(
6690
				'replacement' => null,
6691
				'version'     => 'jetpack-8.3.0',
6692
			),
6693
			'minileven_show_featured_images'               => array(
6694
				'replacement' => null,
6695
				'version'     => 'jetpack-8.3.0',
6696
			),
6697
			'minileven_attachment_size'                    => array(
6698
				'replacement' => null,
6699
				'version'     => 'jetpack-8.3.0',
6700
			),
6701
			'instagram_cache_oembed_api_response_body'     => array(
6702
				'replacement' => null,
6703
				'version'     => 'jetpack-9.1.0',
6704
			),
6705
			'jetpack_can_make_outbound_https'              => array(
6706
				'replacement' => null,
6707
				'version'     => 'jetpack-9.1.0',
6708
			),
6709
		);
6710
6711
		foreach ( $filter_deprecated_list as $tag => $args ) {
6712
			if ( has_filter( $tag ) ) {
6713
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6714
			}
6715
		}
6716
6717
		$action_deprecated_list = array(
6718
			'jetpack_updated_theme'        => array(
6719
				'replacement' => 'jetpack_updated_themes',
6720
				'version'     => 'jetpack-6.2.0',
6721
			),
6722
			'atd_http_post_error'          => array(
6723
				'replacement' => null,
6724
				'version'     => 'jetpack-7.3.0',
6725
			),
6726
			'mobile_reject_mobile'         => array(
6727
				'replacement' => null,
6728
				'version'     => 'jetpack-8.3.0',
6729
			),
6730
			'mobile_force_mobile'          => array(
6731
				'replacement' => null,
6732
				'version'     => 'jetpack-8.3.0',
6733
			),
6734
			'mobile_app_promo_download'    => array(
6735
				'replacement' => null,
6736
				'version'     => 'jetpack-8.3.0',
6737
			),
6738
			'mobile_setup'                 => array(
6739
				'replacement' => null,
6740
				'version'     => 'jetpack-8.3.0',
6741
			),
6742
			'jetpack_mobile_footer_before' => array(
6743
				'replacement' => null,
6744
				'version'     => 'jetpack-8.3.0',
6745
			),
6746
			'wp_mobile_theme_footer'       => array(
6747
				'replacement' => null,
6748
				'version'     => 'jetpack-8.3.0',
6749
			),
6750
			'minileven_credits'            => array(
6751
				'replacement' => null,
6752
				'version'     => 'jetpack-8.3.0',
6753
			),
6754
			'jetpack_mobile_header_before' => array(
6755
				'replacement' => null,
6756
				'version'     => 'jetpack-8.3.0',
6757
			),
6758
			'jetpack_mobile_header_after'  => array(
6759
				'replacement' => null,
6760
				'version'     => 'jetpack-8.3.0',
6761
			),
6762
		);
6763
6764
		foreach ( $action_deprecated_list as $tag => $args ) {
6765
			if ( has_action( $tag ) ) {
6766
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6767
			}
6768
		}
6769
	}
6770
6771
	/**
6772
	 * Converts any url in a stylesheet, to the correct absolute url.
6773
	 *
6774
	 * Considerations:
6775
	 *  - Normal, relative URLs     `feh.png`
6776
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6777
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6778
	 *  - Absolute URLs             `http://domain.com/feh.png`
6779
	 *  - Domain root relative URLs `/feh.png`
6780
	 *
6781
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6782
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6783
	 *
6784
	 * @return mixed|string
6785
	 */
6786
	public static function absolutize_css_urls( $css, $css_file_url ) {
6787
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6788
		$css_dir = dirname( $css_file_url );
6789
		$p       = wp_parse_url( $css_dir );
6790
		$domain  = sprintf(
6791
			'%1$s//%2$s%3$s%4$s',
6792
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6793
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6794
			$p['host'],
6795
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6796
		);
6797
6798
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6799
			$find = $replace = array();
6800
			foreach ( $matches as $match ) {
6801
				$url = trim( $match['path'], "'\" \t" );
6802
6803
				// If this is a data url, we don't want to mess with it.
6804
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6805
					continue;
6806
				}
6807
6808
				// If this is an absolute or protocol-agnostic url,
6809
				// we don't want to mess with it.
6810
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6811
					continue;
6812
				}
6813
6814
				switch ( substr( $url, 0, 1 ) ) {
6815
					case '/':
6816
						$absolute = $domain . $url;
6817
						break;
6818
					default:
6819
						$absolute = $css_dir . '/' . $url;
6820
				}
6821
6822
				$find[]    = $match[0];
6823
				$replace[] = sprintf( 'url("%s")', $absolute );
6824
			}
6825
			$css = str_replace( $find, $replace, $css );
6826
		}
6827
6828
		return $css;
6829
	}
6830
6831
	/**
6832
	 * This methods removes all of the registered css files on the front end
6833
	 * from Jetpack in favor of using a single file. In effect "imploding"
6834
	 * all the files into one file.
6835
	 *
6836
	 * Pros:
6837
	 * - Uses only ONE css asset connection instead of 15
6838
	 * - Saves a minimum of 56k
6839
	 * - Reduces server load
6840
	 * - Reduces time to first painted byte
6841
	 *
6842
	 * Cons:
6843
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6844
	 *      should not cause any issues with themes.
6845
	 * - Plugins/themes dequeuing styles no longer do anything. See
6846
	 *      jetpack_implode_frontend_css filter for a workaround
6847
	 *
6848
	 * For some situations developers may wish to disable css imploding and
6849
	 * instead operate in legacy mode where each file loads seperately and
6850
	 * can be edited individually or dequeued. This can be accomplished with
6851
	 * the following line:
6852
	 *
6853
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6854
	 *
6855
	 * @since 3.2
6856
	 **/
6857
	public function implode_frontend_css( $travis_test = false ) {
6858
		$do_implode = true;
6859
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6860
			$do_implode = false;
6861
		}
6862
6863
		// Do not implode CSS when the page loads via the AMP plugin.
6864
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6865
			$do_implode = false;
6866
		}
6867
6868
		/**
6869
		 * Allow CSS to be concatenated into a single jetpack.css file.
6870
		 *
6871
		 * @since 3.2.0
6872
		 *
6873
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6874
		 */
6875
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6876
6877
		// Do not use the imploded file when default behavior was altered through the filter
6878
		if ( ! $do_implode ) {
6879
			return;
6880
		}
6881
6882
		// We do not want to use the imploded file in dev mode, or if not connected
6883
		if ( ( new Status() )->is_offline_mode() || ! self::is_active() ) {
6884
			if ( ! $travis_test ) {
6885
				return;
6886
			}
6887
		}
6888
6889
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6890
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6891
			return;
6892
		}
6893
6894
		/*
6895
		 * Now we assume Jetpack is connected and able to serve the single
6896
		 * file.
6897
		 *
6898
		 * In the future there will be a check here to serve the file locally
6899
		 * or potentially from the Jetpack CDN
6900
		 *
6901
		 * For now:
6902
		 * - Enqueue a single imploded css file
6903
		 * - Zero out the style_loader_tag for the bundled ones
6904
		 * - Be happy, drink scotch
6905
		 */
6906
6907
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6908
6909
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6910
6911
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6912
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6913
	}
6914
6915
	function concat_remove_style_loader_tag( $tag, $handle ) {
6916
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6917
			$tag = '';
6918
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6919
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6920
			}
6921
		}
6922
6923
		return $tag;
6924
	}
6925
6926
	/**
6927
	 * @deprecated
6928
	 * @see Automattic\Jetpack\Assets\add_aync_script
6929
	 */
6930
	public function script_add_async( $tag, $handle, $src ) {
6931
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6932
	}
6933
6934
	/*
6935
	 * Check the heartbeat data
6936
	 *
6937
	 * Organizes the heartbeat data by severity.  For example, if the site
6938
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6939
	 *
6940
	 * Data will be added to "caution" array, if it either:
6941
	 *  - Out of date Jetpack version
6942
	 *  - Out of date WP version
6943
	 *  - Out of date PHP version
6944
	 *
6945
	 * $return array $filtered_data
6946
	 */
6947
	public static function jetpack_check_heartbeat_data() {
6948
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6949
6950
		$good    = array();
6951
		$caution = array();
6952
		$bad     = array();
6953
6954
		foreach ( $raw_data as $stat => $value ) {
6955
6956
			// Check jetpack version
6957
			if ( 'version' == $stat ) {
6958
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6959
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6960
					continue;
6961
				}
6962
			}
6963
6964
			// Check WP version
6965
			if ( 'wp-version' == $stat ) {
6966
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6967
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6968
					continue;
6969
				}
6970
			}
6971
6972
			// Check PHP version
6973
			if ( 'php-version' == $stat ) {
6974
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6975
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6976
					continue;
6977
				}
6978
			}
6979
6980
			// Check ID crisis
6981
			if ( 'identitycrisis' == $stat ) {
6982
				if ( 'yes' == $value ) {
6983
					$bad[ $stat ] = $value;
6984
					continue;
6985
				}
6986
			}
6987
6988
			// The rest are good :)
6989
			$good[ $stat ] = $value;
6990
		}
6991
6992
		$filtered_data = array(
6993
			'good'    => $good,
6994
			'caution' => $caution,
6995
			'bad'     => $bad,
6996
		);
6997
6998
		return $filtered_data;
6999
	}
7000
7001
	/*
7002
	 * This method is used to organize all options that can be reset
7003
	 * without disconnecting Jetpack.
7004
	 *
7005
	 * It is used in class.jetpack-cli.php to reset options
7006
	 *
7007
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
7008
	 *
7009
	 * @return array of options to delete.
7010
	 */
7011
	public static function get_jetpack_options_for_reset() {
7012
		return Jetpack_Options::get_options_for_reset();
7013
	}
7014
7015
	/*
7016
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
7017
	 * so we can bring them directly to their site in calypso.
7018
	 *
7019
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
7020
	 *
7021
	 * @param string | url
7022
	 * @return string | url without the guff
7023
	 */
7024
	public static function build_raw_urls( $url ) {
7025
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
7026
7027
		return ( new Status() )->get_site_suffix( $url );
7028
	}
7029
7030
	/**
7031
	 * Stores and prints out domains to prefetch for page speed optimization.
7032
	 *
7033
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
7034
	 *
7035
	 * @param string|array $urls URLs to hint.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $urls not be string|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...
7036
	 */
7037
	public static function dns_prefetch( $urls = null ) {
7038
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
7039
		if ( $urls ) {
7040
			Assets::add_resource_hint( $urls );
7041
		}
7042
	}
7043
7044
	public function wp_dashboard_setup() {
7045
		if ( self::is_active() ) {
7046
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
7047
		}
7048
7049
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
7050
			$jetpack_logo = new Jetpack_Logo();
7051
			$widget_title = sprintf(
7052
				/* translators: Placeholder is a Jetpack logo. */
7053
				__( 'Stats by %s', 'jetpack' ),
7054
				$jetpack_logo->get_jp_emblem( true )
7055
			);
7056
7057
			// Wrap title in span so Logo can be properly styled.
7058
			$widget_title = sprintf(
7059
				'<span>%s</span>',
7060
				$widget_title
7061
			);
7062
7063
			wp_add_dashboard_widget(
7064
				'jetpack_summary_widget',
7065
				$widget_title,
7066
				array( __CLASS__, 'dashboard_widget' )
7067
			);
7068
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
7069
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
7070
7071
			// If we're inactive and not in offline mode, sort our box to the top.
7072
			if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
7073
				global $wp_meta_boxes;
7074
7075
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7076
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7077
7078
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7079
			}
7080
		}
7081
	}
7082
7083
	/**
7084
	 * @param mixed $result Value for the user's option
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
7085
	 * @return mixed
7086
	 */
7087
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7088
		if ( ! is_array( $sorted ) ) {
7089
			return $sorted;
7090
		}
7091
7092
		foreach ( $sorted as $box_context => $ids ) {
7093
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7094
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7095
				continue;
7096
			}
7097
7098
			$ids_array = explode( ',', $ids );
7099
			$key       = array_search( 'dashboard_stats', $ids_array );
7100
7101
			if ( false !== $key ) {
7102
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7103
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7104
				$sorted[ $box_context ] = implode( ',', $ids_array );
7105
				// We've found it, stop searching, and just return.
7106
				break;
7107
			}
7108
		}
7109
7110
		return $sorted;
7111
	}
7112
7113
	public static function dashboard_widget() {
7114
		/**
7115
		 * Fires when the dashboard is loaded.
7116
		 *
7117
		 * @since 3.4.0
7118
		 */
7119
		do_action( 'jetpack_dashboard_widget' );
7120
	}
7121
7122
	public static function dashboard_widget_footer() {
7123
		?>
7124
		<footer>
7125
7126
		<div class="protect">
7127
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7128
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7129
				<p class="blocked-count">
7130
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7131
				</p>
7132
				<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>
7133
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7134
				<a href="
7135
				<?php
7136
				echo esc_url(
7137
					wp_nonce_url(
7138
						self::admin_url(
7139
							array(
7140
								'action' => 'activate',
7141
								'module' => 'protect',
7142
							)
7143
						),
7144
						'jetpack_activate-protect'
7145
					)
7146
				);
7147
				?>
7148
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7149
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7150
				</a>
7151
			<?php else : ?>
7152
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7153
			<?php endif; ?>
7154
		</div>
7155
7156
		<div class="akismet">
7157
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7158
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7159
				<p class="blocked-count">
7160
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7161
				</p>
7162
				<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>
7163
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7164
				<a href="
7165
				<?php
7166
				echo esc_url(
7167
					wp_nonce_url(
7168
						add_query_arg(
7169
							array(
7170
								'action' => 'activate',
7171
								'plugin' => 'akismet/akismet.php',
7172
							),
7173
							admin_url( 'plugins.php' )
7174
						),
7175
						'activate-plugin_akismet/akismet.php'
7176
					)
7177
				);
7178
				?>
7179
							" class="button button-jetpack">
7180
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7181
				</a>
7182
			<?php else : ?>
7183
				<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>
7184
			<?php endif; ?>
7185
		</div>
7186
7187
		</footer>
7188
		<?php
7189
	}
7190
7191
	/*
7192
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7193
	 */
7194
	function jetpack_icon_user_connected( $columns ) {
7195
		$columns['user_jetpack'] = '';
7196
		return $columns;
7197
	}
7198
7199
	/*
7200
	 * Show Jetpack icon if the user is linked.
7201
	 */
7202
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7203
		if ( 'user_jetpack' === $col && self::connection()->is_user_connected( $user_id ) ) {
7204
			$jetpack_logo = new Jetpack_Logo();
7205
			$emblem_html  = sprintf(
7206
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7207
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7208
				$jetpack_logo->get_jp_emblem()
7209
			);
7210
			return $emblem_html;
7211
		}
7212
7213
		return $val;
7214
	}
7215
7216
	/*
7217
	 * Style the Jetpack user column
7218
	 */
7219
	function jetpack_user_col_style() {
7220
		global $current_screen;
7221
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7222
			?>
7223
			<style>
7224
				.fixed .column-user_jetpack {
7225
					width: 21px;
7226
				}
7227
				.jp-emblem-user-admin svg {
7228
					width: 20px;
7229
					height: 20px;
7230
				}
7231
				.jp-emblem-user-admin path {
7232
					fill: #00BE28;
7233
				}
7234
			</style>
7235
			<?php
7236
		}
7237
	}
7238
7239
	/**
7240
	 * Checks if Akismet is active and working.
7241
	 *
7242
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7243
	 * that implied usage of methods present since more recent version.
7244
	 * See https://github.com/Automattic/jetpack/pull/9585
7245
	 *
7246
	 * @since  5.1.0
7247
	 *
7248
	 * @return bool True = Akismet available. False = Aksimet not available.
7249
	 */
7250
	public static function is_akismet_active() {
7251
		static $status = null;
7252
7253
		if ( ! is_null( $status ) ) {
7254
			return $status;
7255
		}
7256
7257
		// Check if a modern version of Akismet is active.
7258
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7259
			$status = false;
7260
			return $status;
7261
		}
7262
7263
		// Make sure there is a key known to Akismet at all before verifying key.
7264
		$akismet_key = Akismet::get_api_key();
7265
		if ( ! $akismet_key ) {
7266
			$status = false;
7267
			return $status;
7268
		}
7269
7270
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7271
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7272
7273
		// 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.
7274
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7275
		// We cache the result of the Akismet key verification for ten minutes.
7276
		if ( ! $akismet_key_state || $recheck ) {
7277
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7278
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7279
		}
7280
7281
		$status = 'valid' === $akismet_key_state;
7282
7283
		return $status;
7284
	}
7285
7286
	/**
7287
	 * @deprecated
7288
	 *
7289
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7290
	 */
7291
	public static function is_function_in_backtrace() {
7292
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7293
	}
7294
7295
	/**
7296
	 * Given a minified path, and a non-minified path, will return
7297
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7298
	 *
7299
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7300
	 * root Jetpack directory.
7301
	 *
7302
	 * @since 5.6.0
7303
	 *
7304
	 * @param string $min_path
7305
	 * @param string $non_min_path
7306
	 * @return string The URL to the file
7307
	 */
7308
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7309
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7310
	}
7311
7312
	/**
7313
	 * Checks for whether Jetpack Backup is enabled.
7314
	 * Will return true if the state of Backup is anything except "unavailable".
7315
	 *
7316
	 * @return bool|int|mixed
7317
	 */
7318
	public static function is_rewind_enabled() {
7319
		if ( ! self::is_active() ) {
7320
			return false;
7321
		}
7322
7323
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7324
		if ( false === $rewind_enabled ) {
7325
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7326
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7327
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7328
				&& ! empty( $rewind_data['state'] )
7329
				&& 'active' === $rewind_data['state'] )
7330
				? 1
7331
				: 0;
7332
7333
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7334
		}
7335
		return $rewind_enabled;
7336
	}
7337
7338
	/**
7339
	 * Return Calypso environment value; used for developing Jetpack and pairing
7340
	 * it with different Calypso enrionments, such as localhost.
7341
	 *
7342
	 * @since 7.4.0
7343
	 *
7344
	 * @return string Calypso environment
7345
	 */
7346
	public static function get_calypso_env() {
7347
		if ( isset( $_GET['calypso_env'] ) ) {
7348
			return sanitize_key( $_GET['calypso_env'] );
7349
		}
7350
7351
		if ( getenv( 'CALYPSO_ENV' ) ) {
7352
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7353
		}
7354
7355
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7356
			return sanitize_key( CALYPSO_ENV );
7357
		}
7358
7359
		return '';
7360
	}
7361
7362
	/**
7363
	 * Returns the hostname with protocol for Calypso.
7364
	 * Used for developing Jetpack with Calypso.
7365
	 *
7366
	 * @since 8.4.0
7367
	 *
7368
	 * @return string Calypso host.
7369
	 */
7370
	public static function get_calypso_host() {
7371
		$calypso_env = self::get_calypso_env();
7372
		switch ( $calypso_env ) {
7373
			case 'development':
7374
				return 'http://calypso.localhost:3000/';
7375
			case 'wpcalypso':
7376
				return 'https://wpcalypso.wordpress.com/';
7377
			case 'horizon':
7378
				return 'https://horizon.wordpress.com/';
7379
			default:
7380
				return 'https://wordpress.com/';
7381
		}
7382
	}
7383
7384
	/**
7385
	 * Handles activating default modules as well general cleanup for the new connection.
7386
	 *
7387
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7388
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7389
	 * @param boolean $send_state_messages          Whether to send state messages.
7390
	 * @return void
7391
	 */
7392
	public static function handle_post_authorization_actions(
7393
		$activate_sso = false,
7394
		$redirect_on_activation_error = false,
7395
		$send_state_messages = true
7396
	) {
7397
		$other_modules = $activate_sso
7398
			? array( 'sso' )
7399
			: array();
7400
7401
		if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
7402
			$active_modules = Jetpack_Options::get_option( 'active_modules' );
7403
			self::delete_active_modules();
7404
7405
			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...
7406
		} else {
7407
			// Default modules that don't require a user were already activated on site_register.
7408
			// This time let's activate only those that require a user, this assures we don't reactivate manually deactivated modules while the site was user-less.
7409
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
7410
			Jetpack_Options::update_option( 'active_modules_initialized', true );
7411
		}
7412
7413
		// Since this is a fresh connection, be sure to clear out IDC options
7414
		Identity_Crisis::clear_all_idc_options();
7415
7416
		if ( $send_state_messages ) {
7417
			self::state( 'message', 'authorized' );
7418
		}
7419
	}
7420
7421
	/**
7422
	 * Returns a boolean for whether backups UI should be displayed or not.
7423
	 *
7424
	 * @return bool Should backups UI be displayed?
7425
	 */
7426
	public static function show_backups_ui() {
7427
		/**
7428
		 * Whether UI for backups should be displayed.
7429
		 *
7430
		 * @since 6.5.0
7431
		 *
7432
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7433
		 */
7434
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7435
	}
7436
7437
	/*
7438
	 * Deprecated manage functions
7439
	 */
7440
	function prepare_manage_jetpack_notice() {
7441
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7442
	}
7443
	function manage_activate_screen() {
7444
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7445
	}
7446
	function admin_jetpack_manage_notice() {
7447
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7448
	}
7449
	function opt_out_jetpack_manage_url() {
7450
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7451
	}
7452
	function opt_in_jetpack_manage_url() {
7453
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7454
	}
7455
	function opt_in_jetpack_manage_notice() {
7456
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7457
	}
7458
	function can_display_jetpack_manage_notice() {
7459
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7460
	}
7461
7462
	/**
7463
	 * Clean leftoveruser meta.
7464
	 *
7465
	 * Delete Jetpack-related user meta when it is no longer needed.
7466
	 *
7467
	 * @since 7.3.0
7468
	 *
7469
	 * @param int $user_id User ID being updated.
7470
	 */
7471
	public static function user_meta_cleanup( $user_id ) {
7472
		$meta_keys = array(
7473
			// AtD removed from Jetpack 7.3
7474
			'AtD_options',
7475
			'AtD_check_when',
7476
			'AtD_guess_lang',
7477
			'AtD_ignored_phrases',
7478
		);
7479
7480
		foreach ( $meta_keys as $meta_key ) {
7481
			if ( get_user_meta( $user_id, $meta_key ) ) {
7482
				delete_user_meta( $user_id, $meta_key );
7483
			}
7484
		}
7485
	}
7486
7487
	/**
7488
	 * Checks if a Jetpack site is both active and not in offline mode.
7489
	 *
7490
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7491
	 *
7492
	 * @deprecated 8.8.0
7493
	 *
7494
	 * @return bool True if Jetpack is active and not in offline mode.
7495
	 */
7496
	public static function is_active_and_not_development_mode() {
7497
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7498
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7499
			return false;
7500
		}
7501
		return true;
7502
	}
7503
7504
	/**
7505
	 * Checks if a Jetpack site is both active and not in offline mode.
7506
	 *
7507
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7508
	 *
7509
	 * @since 8.8.0
7510
	 *
7511
	 * @return bool True if Jetpack is active and not in offline mode.
7512
	 */
7513
	public static function is_active_and_not_offline_mode() {
7514
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7515
			return false;
7516
		}
7517
		return true;
7518
	}
7519
7520
	/**
7521
	 * Returns the list of products that we have available for purchase.
7522
	 */
7523
	public static function get_products_for_purchase() {
7524
		$products = array();
7525
		if ( ! is_multisite() ) {
7526
			$products[] = array(
7527
				'key'               => 'backup',
7528
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7529
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7530
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7531
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7532
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7533
				'options'           => array(
7534
					array(
7535
						'type'        => 'daily',
7536
						'slug'        => 'jetpack-backup-daily',
7537
						'key'         => 'jetpack_backup_daily',
7538
						'name'        => __( 'Daily Backups', 'jetpack' ),
7539
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7540
					),
7541
					array(
7542
						'type'        => 'realtime',
7543
						'slug'        => 'jetpack-backup-realtime',
7544
						'key'         => 'jetpack_backup_realtime',
7545
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7546
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7547
					),
7548
				),
7549
				'default_option'    => 'realtime',
7550
				'show_promotion'    => true,
7551
				'discount_percent'  => 70,
7552
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7553
			);
7554
7555
			$products[] = array(
7556
				'key'               => 'scan',
7557
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7558
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7559
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7560
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7561
				'show_promotion'    => true,
7562
				'discount_percent'  => 30,
7563
				'options'           => array(
7564
					array(
7565
						'type' => 'scan',
7566
						'slug' => 'jetpack-scan',
7567
						'key'  => 'jetpack_scan',
7568
						'name' => __( 'Daily Scan', 'jetpack' ),
7569
					),
7570
				),
7571
				'default_option'    => 'scan',
7572
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7573
			);
7574
		}
7575
7576
		$products[] = array(
7577
			'key'               => 'search',
7578
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7579
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7580
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7581
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7582
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7583
			'options'           => array(
7584
				array(
7585
					'type' => 'search',
7586
					'slug' => 'jetpack-search',
7587
					'key'  => 'jetpack_search',
7588
					'name' => __( 'Search', 'jetpack' ),
7589
				),
7590
			),
7591
			'tears'             => array(),
7592
			'default_option'    => 'search',
7593
			'show_promotion'    => false,
7594
			'included_in_plans' => array( 'search-plan' ),
7595
		);
7596
7597
		$products[] = array(
7598
			'key'               => 'anti-spam',
7599
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7600
			'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' ),
7601
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7602
			'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' ),
7603
			'options'           => array(
7604
				array(
7605
					'type' => 'anti-spam',
7606
					'slug' => 'jetpack-anti-spam',
7607
					'key'  => 'jetpack_anti_spam',
7608
					'name' => __( 'Anti-Spam', 'jetpack' ),
7609
				),
7610
			),
7611
			'default_option'    => 'anti-spam',
7612
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7613
		);
7614
7615
		return $products;
7616
	}
7617
}
7618