Completed
Push — rm/deprecated-code ( 60e936...87d3e1 )
by Jeremy
38:33 queued 26:57
created

Jetpack::xmlrpc_async_call()   C

Complexity

Conditions 12
Paths 42

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
nc 42
nop 1
dl 0
loc 42
rs 6.9666
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A Jetpack::store_json_api_authorization_token() 0 6 1
A Jetpack::allow_wpcom_public_api_domain() 0 4 1
A Jetpack::is_redirect_encoded() 0 3 1
A Jetpack::allow_wpcom_environments() 0 7 1
A Jetpack::add_token_to_login_redirect_json_api_authorization() 0 12 1

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
use Automattic\Jetpack\Assets;
4
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Jetpack_Logo.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
new \Automattic\Jetpack\Terms_Of_Service() is of type object<Automattic\Jetpack\Terms_Of_Service>, but the function expects a object<Automattic\Jetpac...tpack\Terms_Of_Service>.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
new \Automattic\Jetpack\Status() is of type object<Automattic\Jetpack\Status>, but the function expects a object<Automattic\Jetpac...omattic\Jetpack\Status>.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
886
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
887
		} else {
888
			/**
889
			 * Initialize tracking right after the user agrees to the terms of service.
890
			 */
891
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
892
		}
893
	}
894
895
	/**
896
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
897
	 * initialization code.
898
	 *
899
	 * @action plugins_loaded
900
	 */
901
	public function late_initialization() {
902
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
903
904
		Partner::init();
905
906
		/**
907
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
908
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
909
		 *
910
		 * @since 8.1.0
911
		 *
912
		 * @param Jetpack $jetpack the main plugin class object.
913
		 */
914
		do_action( 'jetpack_loaded', $this );
915
916
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
917
	}
918
919
	/**
920
	 * This is ported over from the manage module, which has been deprecated and baked in here.
921
	 *
922
	 * @param $domains
923
	 */
924
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
925
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
926
	}
927
928
	/**
929
	 * Return $domains, with 'wordpress.com' appended.
930
	 * This is ported over from the manage module, which has been deprecated and baked in here.
931
	 *
932
	 * @param $domains
933
	 * @return array
934
	 */
935
	function allow_wpcom_domain( $domains ) {
936
		if ( empty( $domains ) ) {
937
			$domains = array();
938
		}
939
		$domains[] = 'wordpress.com';
940
		return array_unique( $domains );
941
	}
942
943
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
944
		$post = get_post( $post_id );
945
946
		if ( empty( $post ) ) {
947
			return $default_url;
948
		}
949
950
		$post_type = $post->post_type;
951
952
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
953
		// https://en.support.wordpress.com/custom-post-types/
954
		$allowed_post_types = array(
955
			'post',
956
			'page',
957
			'jetpack-portfolio',
958
			'jetpack-testimonial',
959
		);
960
961
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
962
			return $default_url;
963
		}
964
965
		return Redirect::get_url(
966
			'calypso-edit-' . $post_type,
967
			array(
968
				'path' => $post_id,
969
			)
970
		);
971
	}
972
973
	function point_edit_comment_links_to_calypso( $url ) {
974
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
975
		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...
976
977
		return Redirect::get_url(
978
			'calypso-edit-comment',
979
			array(
980
				'path' => $query_args['amp;c'],
981
			)
982
		);
983
984
	}
985
986
	/**
987
	 * Extend Sync callables with Jetpack Plugin functions.
988
	 *
989
	 * @param array $callables list of callables.
990
	 *
991
	 * @return array list of callables.
992
	 */
993
	public function filter_sync_callable_whitelist( $callables ) {
994
995
		// Jetpack Functions.
996
		$jetpack_callables = array(
997
			'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
998
			'updates'                  => array( 'Jetpack', 'get_updates' ),
999
			'active_modules'           => array( 'Jetpack', 'get_active_modules' ),
1000
			'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1001
		);
1002
		$callables         = array_merge( $callables, $jetpack_callables );
1003
1004
		// Jetpack_SSO_Helpers.
1005
		if ( include_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' ) {
1006
			$sso_helpers = array(
1007
				'sso_is_two_step_required'      => array( 'Jetpack_SSO_Helpers', 'is_two_step_required' ),
1008
				'sso_should_hide_login_form'    => array( 'Jetpack_SSO_Helpers', 'should_hide_login_form' ),
1009
				'sso_match_by_email'            => array( 'Jetpack_SSO_Helpers', 'match_by_email' ),
1010
				'sso_new_user_override'         => array( 'Jetpack_SSO_Helpers', 'new_user_override' ),
1011
				'sso_bypass_default_login_form' => array( 'Jetpack_SSO_Helpers', 'bypass_login_forward_wpcom' ),
1012
			);
1013
			$callables   = array_merge( $callables, $sso_helpers );
1014
		}
1015
1016
		return $callables;
1017
	}
1018
1019
	/**
1020
	 * Extend Sync multisite callables with Jetpack Plugin functions.
1021
	 *
1022
	 * @param array $callables list of callables.
1023
	 *
1024
	 * @return array list of callables.
1025
	 */
1026
	public function filter_sync_multisite_callable_whitelist( $callables ) {
1027
1028
		// Jetpack Funtions.
1029
		$jetpack_multisite_callables = array(
1030
			'network_name'                        => array( 'Jetpack', 'network_name' ),
1031
			'network_allow_new_registrations'     => array( 'Jetpack', 'network_allow_new_registrations' ),
1032
			'network_add_new_users'               => array( 'Jetpack', 'network_add_new_users' ),
1033
			'network_site_upload_space'           => array( 'Jetpack', 'network_site_upload_space' ),
1034
			'network_upload_file_types'           => array( 'Jetpack', 'network_upload_file_types' ),
1035
			'network_enable_administration_menus' => array( 'Jetpack', 'network_enable_administration_menus' ),
1036
		);
1037
		$callables                   = array_merge( $callables, $jetpack_multisite_callables );
1038
1039
		return $callables;
1040
	}
1041
1042
	/**
1043
	 * Deprecated
1044
	 * Please use Automattic\Jetpack\JITMS\JITM::jetpack_track_last_sync_callback instead.
1045
	 *
1046
	 * @param array $params The action parameters.
1047
	 *
1048
	 * @deprecated since 9.8.
1049
	 */
1050
	function jetpack_track_last_sync_callback( $params ) {
1051
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\Automattic\Jetpack\JITMS\JITM->jetpack_track_last_sync_callback' );
1052
		return Automattic\Jetpack\JITMS\JITM::get_instance()->jetpack_track_last_sync_callback( $params );
1053
	}
1054
1055
	function jetpack_connection_banner_callback() {
1056
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1057
1058
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1059
		if (
1060
			isset( $_REQUEST['dismissBanner'] ) &&
1061
			! Jetpack_Connection_Banner::force_display()
1062
		) {
1063
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1064
			wp_send_json_success();
1065
		}
1066
1067
		wp_die();
1068
	}
1069
1070
	/**
1071
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1072
	 */
1073
	function push_stats() {
1074
		if ( ! empty( $this->stats ) ) {
1075
			$this->do_stats( 'server_side' );
1076
		}
1077
	}
1078
1079
	/**
1080
	 * Sets the Jetpack custom capabilities.
1081
	 *
1082
	 * @param string[] $caps    Array of the user's capabilities.
1083
	 * @param string   $cap     Capability name.
1084
	 * @param int      $user_id The user ID.
1085
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1086
	 */
1087
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1088
		switch ( $cap ) {
1089
			case 'jetpack_manage_modules':
1090
			case 'jetpack_activate_modules':
1091
			case 'jetpack_deactivate_modules':
1092
				$caps = array( 'manage_options' );
1093
				break;
1094
			case 'jetpack_configure_modules':
1095
				$caps = array( 'manage_options' );
1096
				break;
1097
			case 'jetpack_manage_autoupdates':
1098
				$caps = array(
1099
					'manage_options',
1100
					'update_plugins',
1101
				);
1102
				break;
1103
			case 'jetpack_network_admin_page':
1104
			case 'jetpack_network_settings_page':
1105
				$caps = array( 'manage_network_plugins' );
1106
				break;
1107
			case 'jetpack_network_sites_page':
1108
				$caps = array( 'manage_sites' );
1109
				break;
1110 View Code Duplication
			case 'jetpack_admin_page':
1111
				$is_offline_mode = ( new Status() )->is_offline_mode();
1112
				if ( $is_offline_mode ) {
1113
					$caps = array( 'manage_options' );
1114
					break;
1115
				} else {
1116
					$caps = array( 'read' );
1117
				}
1118
				break;
1119
		}
1120
		return $caps;
1121
	}
1122
1123
	/**
1124
	 * Register assets for use in various modules and the Jetpack admin page.
1125
	 *
1126
	 * @uses wp_script_is, wp_register_script, plugins_url
1127
	 * @action wp_loaded
1128
	 * @return null
1129
	 */
1130
	public function register_assets() {
1131 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1132
			wp_register_script(
1133
				'jetpack-gallery-settings',
1134
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1135
				array( 'media-views' ),
1136
				'20121225'
1137
			);
1138
		}
1139
1140
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1141
			wp_register_script(
1142
				'jetpack-twitter-timeline',
1143
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1144
				array( 'jquery' ),
1145
				'4.0.0',
1146
				true
1147
			);
1148
		}
1149
1150
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1151
			wp_register_script(
1152
				'jetpack-facebook-embed',
1153
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1154
				array(),
1155
				null,
1156
				true
1157
			);
1158
1159
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1160
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1161
			if ( ! is_numeric( $fb_app_id ) ) {
1162
				$fb_app_id = '';
1163
			}
1164
			wp_localize_script(
1165
				'jetpack-facebook-embed',
1166
				'jpfbembed',
1167
				array(
1168
					'appid'  => $fb_app_id,
1169
					'locale' => $this->get_locale(),
1170
				)
1171
			);
1172
		}
1173
1174
		/**
1175
		 * As jetpack_register_genericons is by default fired off a hook,
1176
		 * the hook may have already fired by this point.
1177
		 * So, let's just trigger it manually.
1178
		 */
1179
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1180
		jetpack_register_genericons();
1181
1182
		/**
1183
		 * Register the social logos
1184
		 */
1185
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1186
		jetpack_register_social_logos();
1187
1188 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1189
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1190
		}
1191
	}
1192
1193
	/**
1194
	 * Guess locale from language code.
1195
	 *
1196
	 * @param string $lang Language code.
1197
	 * @return string|bool
1198
	 */
1199 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1200
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1201
			return 'en_US';
1202
		}
1203
1204
		if ( ! class_exists( 'GP_Locales' ) ) {
1205
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1206
				return false;
1207
			}
1208
1209
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1210
		}
1211
1212
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1213
			// WP.com: get_locale() returns 'it'
1214
			$locale = GP_Locales::by_slug( $lang );
1215
		} else {
1216
			// Jetpack: get_locale() returns 'it_IT';
1217
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1218
		}
1219
1220
		if ( ! $locale ) {
1221
			return false;
1222
		}
1223
1224
		if ( empty( $locale->facebook_locale ) ) {
1225
			if ( empty( $locale->wp_locale ) ) {
1226
				return false;
1227
			} else {
1228
				// Facebook SDK is smart enough to fall back to en_US if a
1229
				// locale isn't supported. Since supported Facebook locales
1230
				// can fall out of sync, we'll attempt to use the known
1231
				// wp_locale value and rely on said fallback.
1232
				return $locale->wp_locale;
1233
			}
1234
		}
1235
1236
		return $locale->facebook_locale;
1237
	}
1238
1239
	/**
1240
	 * Get the locale.
1241
	 *
1242
	 * @return string|bool
1243
	 */
1244
	function get_locale() {
1245
		$locale = $this->guess_locale_from_lang( get_locale() );
1246
1247
		if ( ! $locale ) {
1248
			$locale = 'en_US';
1249
		}
1250
1251
		return $locale;
1252
	}
1253
1254
	/**
1255
	 * Return the network_site_url so that .com knows what network this site is a part of.
1256
	 *
1257
	 * @param  bool $option
1258
	 * @return string
1259
	 */
1260
	public function jetpack_main_network_site_option( $option ) {
1261
		return network_site_url();
1262
	}
1263
	/**
1264
	 * Network Name.
1265
	 */
1266
	static function network_name( $option = null ) {
1267
		global $current_site;
1268
		return $current_site->site_name;
1269
	}
1270
	/**
1271
	 * Does the network allow new user and site registrations.
1272
	 *
1273
	 * @return string
1274
	 */
1275
	static function network_allow_new_registrations( $option = null ) {
1276
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1277
	}
1278
	/**
1279
	 * Does the network allow admins to add new users.
1280
	 *
1281
	 * @return boolian
1282
	 */
1283
	static function network_add_new_users( $option = null ) {
1284
		return (bool) get_site_option( 'add_new_users' );
1285
	}
1286
	/**
1287
	 * File upload psace left per site in MB.
1288
	 *  -1 means NO LIMIT.
1289
	 *
1290
	 * @return number
1291
	 */
1292
	static function network_site_upload_space( $option = null ) {
1293
		// value in MB
1294
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1295
	}
1296
1297
	/**
1298
	 * Network allowed file types.
1299
	 *
1300
	 * @return string
1301
	 */
1302
	static function network_upload_file_types( $option = null ) {
1303
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1304
	}
1305
1306
	/**
1307
	 * Maximum file upload size set by the network.
1308
	 *
1309
	 * @return number
1310
	 */
1311
	static function network_max_upload_file_size( $option = null ) {
1312
		// value in KB
1313
		return get_site_option( 'fileupload_maxk', 300 );
1314
	}
1315
1316
	/**
1317
	 * Lets us know if a site allows admins to manage the network.
1318
	 *
1319
	 * @return array
1320
	 */
1321
	static function network_enable_administration_menus( $option = null ) {
1322
		return get_site_option( 'menu_items' );
1323
	}
1324
1325
	/**
1326
	 * If a user has been promoted to or demoted from admin, we need to clear the
1327
	 * jetpack_other_linked_admins transient.
1328
	 *
1329
	 * @since 4.3.2
1330
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1331
	 *
1332
	 * @param int    $user_id   The user ID whose role changed.
1333
	 * @param string $role      The new role.
1334
	 * @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...
1335
	 */
1336
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1337
		if ( 'administrator' == $role
1338
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1339
			|| is_null( $old_roles )
1340
		) {
1341
			delete_transient( 'jetpack_other_linked_admins' );
1342
		}
1343
	}
1344
1345
	/**
1346
	 * Checks to see if there are any other users available to become primary
1347
	 * Users must both:
1348
	 * - Be linked to wpcom
1349
	 * - Be an admin
1350
	 *
1351
	 * @return mixed False if no other users are linked, Int if there are.
1352
	 */
1353
	static function get_other_linked_admins() {
1354
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1355
1356
		if ( false === $other_linked_users ) {
1357
			$admins = get_users( array( 'role' => 'administrator' ) );
1358
			if ( count( $admins ) > 1 ) {
1359
				$available = array();
1360
				foreach ( $admins as $admin ) {
1361
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1362
						$available[] = $admin->ID;
1363
					}
1364
				}
1365
1366
				$count_connected_admins = count( $available );
1367
				if ( count( $available ) > 1 ) {
1368
					$other_linked_users = $count_connected_admins;
1369
				} else {
1370
					$other_linked_users = 0;
1371
				}
1372
			} else {
1373
				$other_linked_users = 0;
1374
			}
1375
1376
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1377
		}
1378
1379
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1380
	}
1381
1382
	/**
1383
	 * Return whether we are dealing with a multi network setup or not.
1384
	 * The reason we are type casting this is because we want to avoid the situation where
1385
	 * the result is false since when is_main_network_option return false it cases
1386
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1387
	 * database which could be set to anything as opposed to what this function returns.
1388
	 *
1389
	 * @param  bool $option
1390
	 *
1391
	 * @return boolean
1392
	 */
1393
	public function is_main_network_option( $option ) {
1394
		// return '1' or ''
1395
		return (string) (bool) self::is_multi_network();
1396
	}
1397
1398
	/**
1399
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1400
	 *
1401
	 * @param  string $option
1402
	 * @return boolean
1403
	 */
1404
	public function is_multisite( $option ) {
1405
		return (string) (bool) is_multisite();
1406
	}
1407
1408
	/**
1409
	 * Implemented since there is no core is multi network function
1410
	 * Right now there is no way to tell if we which network is the dominant network on the system
1411
	 *
1412
	 * @since  3.3
1413
	 * @return boolean
1414
	 */
1415 View Code Duplication
	public static function is_multi_network() {
1416
		global  $wpdb;
1417
1418
		// if we don't have a multi site setup no need to do any more
1419
		if ( ! is_multisite() ) {
1420
			return false;
1421
		}
1422
1423
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1424
		if ( $num_sites > 1 ) {
1425
			return true;
1426
		} else {
1427
			return false;
1428
		}
1429
	}
1430
1431
	/**
1432
	 * Get back if the current site is single user site.
1433
	 *
1434
	 * @return bool
1435
	 */
1436 View Code Duplication
	public static function is_single_user_site() {
1437
		global $wpdb;
1438
1439
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1440
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1441
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1442
		}
1443
		return 1 === (int) $some_users;
1444
	}
1445
1446
	/**
1447
	 * Returns true if the site has file write access false otherwise.
1448
	 *
1449
	 * @return string ( '1' | '0' )
1450
	 **/
1451
	public static function file_system_write_access() {
1452
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1453
			require_once ABSPATH . 'wp-admin/includes/file.php';
1454
		}
1455
1456
		require_once ABSPATH . 'wp-admin/includes/template.php';
1457
1458
		$filesystem_method = get_filesystem_method();
1459
		if ( $filesystem_method === 'direct' ) {
1460
			return 1;
1461
		}
1462
1463
		ob_start();
1464
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1465
		ob_end_clean();
1466
		if ( $filesystem_credentials_are_stored ) {
1467
			return 1;
1468
		}
1469
		return 0;
1470
	}
1471
1472
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1473
	/**
1474
	 * jetpack_updates is saved in the following schema:
1475
	 *
1476
	 * array (
1477
	 *      'plugins'                       => (int) Number of plugin updates available.
1478
	 *      'themes'                        => (int) Number of theme updates available.
1479
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1480
	 *      'translations'                  => (int) Number of translation updates available.
1481
	 *      'total'                         => (int) Total of all available updates.
1482
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1483
	 * )
1484
	 *
1485
	 * @return array
1486
	 */
1487
	public static function get_updates() {
1488
		$update_data = wp_get_update_data();
1489
1490
		// Stores the individual update counts as well as the total count.
1491
		if ( isset( $update_data['counts'] ) ) {
1492
			$updates = $update_data['counts'];
1493
		}
1494
1495
		// If we need to update WordPress core, let's find the latest version number.
1496 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1497
			$cur = get_preferred_from_update_core();
1498
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1499
				$updates['wp_update_version'] = $cur->current;
1500
			}
1501
		}
1502
		return isset( $updates ) ? $updates : array();
1503
	}
1504
	// phpcs:enable
1505
1506
	public static function get_update_details() {
1507
		$update_details = array(
1508
			'update_core'    => get_site_transient( 'update_core' ),
1509
			'update_plugins' => get_site_transient( 'update_plugins' ),
1510
			'update_themes'  => get_site_transient( 'update_themes' ),
1511
		);
1512
		return $update_details;
1513
	}
1514
1515
	/**
1516
	 * Is Jetpack active?
1517
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1518
	 *
1519
	 * This method is deprecated since 9.6.0. Please use one of the methods provided by the Manager class in the Connection package,
1520
	 * or Jetpack::is_connection_ready if you want to know when the Jetpack plugin starts considering the connection ready to be used.
1521
	 *
1522
	 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
1523
	 *
1524
	 * @deprecated 9.6.0
1525
	 *
1526
	 * @return bool
1527
	 */
1528
	public static function is_active() {
1529
		return self::connection()->is_active();
0 ignored issues
show
Deprecated Code introduced by
The method Automattic\Jetpack\Connection\Manager::is_active() has been deprecated with message: 9.6.0

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

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

Loading history...
1530
	}
1531
1532
	/**
1533
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1534
	 *
1535
	 * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1536
	 * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1537
	 * users and this option will be available by default for everybody.
1538
	 *
1539
	 * @since 9.6.0
1540
	 * @since 9.7.0 returns is_connected in all cases and adds filter to the returned value
1541
	 *
1542
	 * @return bool is the site connection ready to be used?
1543
	 */
1544
	public static function is_connection_ready() {
1545
		/**
1546
		 * Allows filtering whether the connection is ready to be used. If true, this will enable the Jetpack UI and modules
1547
		 *
1548
		 * Modules will be enabled depending on the connection status and if the module requires a connection or user connection.
1549
		 *
1550
		 * @since 9.7.0
1551
		 *
1552
		 * @param bool                                  $is_connection_ready Is the connection ready?
1553
		 * @param Automattic\Jetpack\Connection\Manager $connection_manager Instance of the Manager class, can be used to check the connection status.
1554
		 */
1555
		return apply_filters( 'jetpack_is_connection_ready', self::connection()->is_connected(), self::connection() );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with self::connection().

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

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

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

Loading history...
1556
	}
1557
1558
	/**
1559
	 * Deprecated: Is Jetpack in development (offline) mode?
1560
	 *
1561
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1562
	 * and themes still use it, and we do not want to flood them with notices.
1563
	 *
1564
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1565
	 *
1566
	 * @deprecated since 8.0.
1567
	 */
1568
	public static function is_development_mode() {
1569
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1570
		return ( new Status() )->is_offline_mode();
1571
	}
1572
1573
	/**
1574
	 * Whether the site is currently onboarding or not.
1575
	 * A site is considered as being onboarded if it currently has an onboarding token.
1576
	 *
1577
	 * @since 5.8
1578
	 *
1579
	 * @access public
1580
	 * @static
1581
	 *
1582
	 * @return bool True if the site is currently onboarding, false otherwise
1583
	 */
1584
	public static function is_onboarding() {
1585
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1586
	}
1587
1588
	/**
1589
	 * Determines reason for Jetpack offline mode.
1590
	 */
1591
	public static function development_mode_trigger_text() {
1592
		$status = new Status();
1593
1594
		if ( ! $status->is_offline_mode() ) {
1595
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1596
		}
1597
1598
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1599
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1600
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1601
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1602
		} elseif ( $status->is_local_site() ) {
1603
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1604
			/** This filter is documented in packages/status/src/class-status.php */
1605
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1606
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1607
		} else {
1608
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1609
		}
1610
1611
		return $notice;
1612
1613
	}
1614
	/**
1615
	 * Get Jetpack offline mode notice text and notice class.
1616
	 *
1617
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1618
	 */
1619
	public static function show_development_mode_notice() {
1620 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1621
			$notice = sprintf(
1622
				/* translators: %s is a URL */
1623
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1624
				Redirect::get_url( 'jetpack-support-development-mode' )
1625
			);
1626
1627
			$notice .= ' ' . self::development_mode_trigger_text();
1628
1629
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1630
		}
1631
1632
		// Throw up a notice if using a development version and as for feedback.
1633
		if ( self::is_development_version() ) {
1634
			/* translators: %s is a URL */
1635
			$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' ) );
1636
1637
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1638
		}
1639
		// Throw up a notice if using staging mode
1640 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1641
			/* translators: %s is a URL */
1642
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1643
1644
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1645
		}
1646
	}
1647
1648
	/**
1649
	 * Whether Jetpack's version maps to a public release, or a development version.
1650
	 */
1651
	public static function is_development_version() {
1652
		/**
1653
		 * Allows filtering whether this is a development version of Jetpack.
1654
		 *
1655
		 * This filter is especially useful for tests.
1656
		 *
1657
		 * @since 4.3.0
1658
		 *
1659
		 * @param bool $development_version Is this a develoment version of Jetpack?
1660
		 */
1661
		return (bool) apply_filters(
1662
			'jetpack_development_version',
1663
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1664
		);
1665
	}
1666
1667
	/**
1668
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1669
	 */
1670
	public static function is_user_connected( $user_id = false ) {
1671
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1672
		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...
1673
	}
1674
1675
	/**
1676
	 * Get the wpcom user data of the current|specified connected user.
1677
	 */
1678
	public static function get_connected_user_data( $user_id = null ) {
1679
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1680
		return self::connection()->get_connected_user_data( $user_id );
1681
	}
1682
1683
	/**
1684
	 * Get the wpcom email of the current|specified connected user.
1685
	 */
1686
	public static function get_connected_user_email( $user_id = null ) {
1687
		if ( ! $user_id ) {
1688
			$user_id = get_current_user_id();
1689
		}
1690
1691
		$xml = new Jetpack_IXR_Client(
1692
			array(
1693
				'user_id' => $user_id,
1694
			)
1695
		);
1696
		$xml->query( 'wpcom.getUserEmail' );
1697
		if ( ! $xml->isError() ) {
1698
			return $xml->getResponse();
1699
		}
1700
		return false;
1701
	}
1702
1703
	/**
1704
	 * Get the wpcom email of the master user.
1705
	 */
1706
	public static function get_master_user_email() {
1707
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1708
		if ( $master_user_id ) {
1709
			return self::get_connected_user_email( $master_user_id );
1710
		}
1711
		return '';
1712
	}
1713
1714
	/**
1715
	 * Gets current user IP address.
1716
	 *
1717
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1718
	 *
1719
	 * @return string                  Current user IP address.
1720
	 */
1721
	public static function current_user_ip( $check_all_headers = false ) {
1722
		if ( $check_all_headers ) {
1723
			foreach ( array(
1724
				'HTTP_CF_CONNECTING_IP',
1725
				'HTTP_CLIENT_IP',
1726
				'HTTP_X_FORWARDED_FOR',
1727
				'HTTP_X_FORWARDED',
1728
				'HTTP_X_CLUSTER_CLIENT_IP',
1729
				'HTTP_FORWARDED_FOR',
1730
				'HTTP_FORWARDED',
1731
				'HTTP_VIA',
1732
			) as $key ) {
1733
				if ( ! empty( $_SERVER[ $key ] ) ) {
1734
					return $_SERVER[ $key ];
1735
				}
1736
			}
1737
		}
1738
1739
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1740
	}
1741
1742
	/**
1743
	 * Loads the currently active modules.
1744
	 */
1745
	public static function load_modules() {
1746
		$is_offline_mode = ( new Status() )->is_offline_mode();
1747
		if (
1748
			! self::is_connection_ready()
1749
			&& ! $is_offline_mode
1750
			&& ! self::is_onboarding()
1751
			&& (
1752
				! is_multisite()
1753
				|| ! get_site_option( 'jetpack_protect_active' )
1754
			)
1755
		) {
1756
			return;
1757
		}
1758
1759
		$version = Jetpack_Options::get_option( 'version' );
1760 View Code Duplication
		if ( ! $version ) {
1761
			$version = $old_version = JETPACK__VERSION . ':' . time();
1762
			/** This action is documented in class.jetpack.php */
1763
			do_action( 'updating_jetpack_version', $version, false );
1764
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1765
		}
1766
		list( $version ) = explode( ':', $version );
1767
1768
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1769
1770
		$modules_data = array();
1771
1772
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1773
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1774
			$updated_modules = array();
1775
			foreach ( $modules as $module ) {
1776
				$modules_data[ $module ] = self::get_module( $module );
1777
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1778
					continue;
1779
				}
1780
1781
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1782
					continue;
1783
				}
1784
1785
				$updated_modules[] = $module;
1786
			}
1787
1788
			$modules = array_diff( $modules, $updated_modules );
1789
		}
1790
1791
		$is_site_connection = self::connection()->is_site_connection();
1792
1793
		foreach ( $modules as $index => $module ) {
1794
			// If we're in offline/site-connection mode, disable modules requiring a connection/user connection.
1795
			if ( $is_offline_mode || $is_site_connection ) {
1796
				// Prime the pump if we need to
1797
				if ( empty( $modules_data[ $module ] ) ) {
1798
					$modules_data[ $module ] = self::get_module( $module );
1799
				}
1800
				// If the module requires a connection, but we're in local mode, don't include it.
1801
				if ( $is_offline_mode && $modules_data[ $module ]['requires_connection'] ) {
1802
					continue;
1803
				}
1804
1805
				if ( $is_site_connection && $modules_data[ $module ]['requires_user_connection'] ) {
1806
					continue;
1807
				}
1808
			}
1809
1810
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1811
				continue;
1812
			}
1813
1814
			if ( ! include_once self::get_module_path( $module ) ) {
1815
				unset( $modules[ $index ] );
1816
				self::update_active_modules( array_values( $modules ) );
1817
				continue;
1818
			}
1819
1820
			/**
1821
			 * Fires when a specific module is loaded.
1822
			 * The dynamic part of the hook, $module, is the module slug.
1823
			 *
1824
			 * @since 1.1.0
1825
			 */
1826
			do_action( 'jetpack_module_loaded_' . $module );
1827
		}
1828
1829
		/**
1830
		 * Fires when all the modules are loaded.
1831
		 *
1832
		 * @since 1.1.0
1833
		 */
1834
		do_action( 'jetpack_modules_loaded' );
1835
1836
		// 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.
1837
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1838
	}
1839
1840
	/**
1841
	 * Check if Jetpack's REST API compat file should be included
1842
	 *
1843
	 * @action plugins_loaded
1844
	 * @return null
1845
	 */
1846
	public function check_rest_api_compat() {
1847
		/**
1848
		 * Filters the list of REST API compat files to be included.
1849
		 *
1850
		 * @since 2.2.5
1851
		 *
1852
		 * @param array $args Array of REST API compat files to include.
1853
		 */
1854
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1855
1856
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1857
			require_once $_jetpack_rest_api_compat_include;
1858
		}
1859
	}
1860
1861
	/**
1862
	 * Gets all plugins currently active in values, regardless of whether they're
1863
	 * traditionally activated or network activated.
1864
	 *
1865
	 * @todo Store the result in core's object cache maybe?
1866
	 */
1867
	public static function get_active_plugins() {
1868
		$active_plugins = (array) get_option( 'active_plugins', array() );
1869
1870
		if ( is_multisite() ) {
1871
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1872
			// whereas active_plugins stores them in the values.
1873
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1874
			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...
1875
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1876
			}
1877
		}
1878
1879
		sort( $active_plugins );
1880
1881
		return array_unique( $active_plugins );
1882
	}
1883
1884
	/**
1885
	 * Gets and parses additional plugin data to send with the heartbeat data
1886
	 *
1887
	 * @since 3.8.1
1888
	 *
1889
	 * @return array Array of plugin data
1890
	 */
1891
	public static function get_parsed_plugin_data() {
1892
		if ( ! function_exists( 'get_plugins' ) ) {
1893
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
1894
		}
1895
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1896
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1897
		$active_plugins = self::get_active_plugins();
1898
1899
		$plugins = array();
1900
		foreach ( $all_plugins as $path => $plugin_data ) {
1901
			$plugins[ $path ] = array(
1902
				'is_active' => in_array( $path, $active_plugins ),
1903
				'file'      => $path,
1904
				'name'      => $plugin_data['Name'],
1905
				'version'   => $plugin_data['Version'],
1906
				'author'    => $plugin_data['Author'],
1907
			);
1908
		}
1909
1910
		return $plugins;
1911
	}
1912
1913
	/**
1914
	 * Gets and parses theme data to send with the heartbeat data
1915
	 *
1916
	 * @since 3.8.1
1917
	 *
1918
	 * @return array Array of theme data
1919
	 */
1920
	public static function get_parsed_theme_data() {
1921
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
1922
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1923
1924
		$themes = array();
1925
		foreach ( $all_themes as $slug => $theme_data ) {
1926
			$theme_headers = array();
1927
			foreach ( $header_keys as $header_key ) {
1928
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1929
			}
1930
1931
			$themes[ $slug ] = array(
1932
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
1933
				'slug'            => $slug,
1934
				'theme_root'      => $theme_data->get_theme_root_uri(),
1935
				'parent'          => $theme_data->parent(),
1936
				'headers'         => $theme_headers,
1937
			);
1938
		}
1939
1940
		return $themes;
1941
	}
1942
1943
	/**
1944
	 * Checks whether a specific plugin is active.
1945
	 *
1946
	 * We don't want to store these in a static variable, in case
1947
	 * there are switch_to_blog() calls involved.
1948
	 */
1949
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1950
		return in_array( $plugin, self::get_active_plugins() );
1951
	}
1952
1953
	/**
1954
	 * Check if Jetpack's Open Graph tags should be used.
1955
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1956
	 *
1957
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1958
	 * @action plugins_loaded
1959
	 * @return null
1960
	 */
1961
	public function check_open_graph() {
1962
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
1963
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1964
		}
1965
1966
		$active_plugins = self::get_active_plugins();
1967
1968
		if ( ! empty( $active_plugins ) ) {
1969
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1970
				if ( in_array( $plugin, $active_plugins ) ) {
1971
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1972
					break;
1973
				}
1974
			}
1975
		}
1976
1977
		/**
1978
		 * Allow the addition of Open Graph Meta Tags to all pages.
1979
		 *
1980
		 * @since 2.0.3
1981
		 *
1982
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1983
		 */
1984
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1985
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1986
		}
1987
	}
1988
1989
	/**
1990
	 * Check if Jetpack's Twitter tags should be used.
1991
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1992
	 *
1993
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1994
	 * @action plugins_loaded
1995
	 * @return null
1996
	 */
1997
	public function check_twitter_tags() {
1998
1999
		$active_plugins = self::get_active_plugins();
2000
2001
		if ( ! empty( $active_plugins ) ) {
2002
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2003
				if ( in_array( $plugin, $active_plugins ) ) {
2004
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2005
					break;
2006
				}
2007
			}
2008
		}
2009
2010
		/**
2011
		 * Allow Twitter Card Meta tags to be disabled.
2012
		 *
2013
		 * @since 2.6.0
2014
		 *
2015
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2016
		 */
2017
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2018
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2019
		}
2020
	}
2021
2022
	/* Jetpack Options API */
2023
2024
	public static function get_option_names( $type = 'compact' ) {
2025
		return Jetpack_Options::get_option_names( $type );
2026
	}
2027
2028
	/**
2029
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2030
	 *
2031
	 * @param string $name    Option name
2032
	 * @param mixed  $default (optional)
2033
	 */
2034
	public static function get_option( $name, $default = false ) {
2035
		return Jetpack_Options::get_option( $name, $default );
2036
	}
2037
2038
	/**
2039
	 * Returns an array of all PHP files in the specified absolute path.
2040
	 * Equivalent to glob( "$absolute_path/*.php" ).
2041
	 *
2042
	 * @param string $absolute_path The absolute path of the directory to search.
2043
	 * @return array Array of absolute paths to the PHP files.
2044
	 */
2045
	public static function glob_php( $absolute_path ) {
2046
		if ( function_exists( 'glob' ) ) {
2047
			return glob( "$absolute_path/*.php" );
2048
		}
2049
2050
		$absolute_path = untrailingslashit( $absolute_path );
2051
		$files         = array();
2052
		if ( ! $dir = @opendir( $absolute_path ) ) {
2053
			return $files;
2054
		}
2055
2056
		while ( false !== $file = readdir( $dir ) ) {
2057
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2058
				continue;
2059
			}
2060
2061
			$file = "$absolute_path/$file";
2062
2063
			if ( ! is_file( $file ) ) {
2064
				continue;
2065
			}
2066
2067
			$files[] = $file;
2068
		}
2069
2070
		closedir( $dir );
2071
2072
		return $files;
2073
	}
2074
2075
	public static function activate_new_modules( $redirect = false ) {
2076
		if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2077
			return;
2078
		}
2079
2080
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2081 View Code Duplication
		if ( ! $jetpack_old_version ) {
2082
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2083
			/** This action is documented in class.jetpack.php */
2084
			do_action( 'updating_jetpack_version', $version, false );
2085
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2086
		}
2087
2088
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2089
2090
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2091
			return;
2092
		}
2093
2094
		$active_modules     = self::get_active_modules();
2095
		$reactivate_modules = array();
2096
		foreach ( $active_modules as $active_module ) {
2097
			$module = self::get_module( $active_module );
2098
			if ( ! isset( $module['changed'] ) ) {
2099
				continue;
2100
			}
2101
2102
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2103
				continue;
2104
			}
2105
2106
			$reactivate_modules[] = $active_module;
2107
			self::deactivate_module( $active_module );
2108
		}
2109
2110
		$new_version = JETPACK__VERSION . ':' . time();
2111
		/** This action is documented in class.jetpack.php */
2112
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2113
		Jetpack_Options::update_options(
2114
			array(
2115
				'version'     => $new_version,
2116
				'old_version' => $jetpack_old_version,
2117
			)
2118
		);
2119
2120
		self::state( 'message', 'modules_activated' );
2121
2122
		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...
2123
2124
		if ( $redirect ) {
2125
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2126
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2127
				$page = $_GET['page'];
2128
			}
2129
2130
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2131
			exit;
2132
		}
2133
	}
2134
2135
	/**
2136
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2137
	 * Make sure to tuck away module "library" files in a sub-directory.
2138
	 *
2139
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2140
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2141
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2142
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2143
	 *
2144
	 * @return array $modules Array of module slugs
2145
	 */
2146
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2147
		static $modules = null;
2148
2149
		if ( ! isset( $modules ) ) {
2150
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2151
			// Use the cache if we're on the front-end and it's available...
2152
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2153
				$modules = $available_modules_option[ JETPACK__VERSION ];
2154
			} else {
2155
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2156
2157
				$modules = array();
2158
2159
				foreach ( $files as $file ) {
2160
					if ( ! $headers = self::get_module( $file ) ) {
2161
						continue;
2162
					}
2163
2164
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2165
				}
2166
2167
				Jetpack_Options::update_option(
2168
					'available_modules',
2169
					array(
2170
						JETPACK__VERSION => $modules,
2171
					)
2172
				);
2173
			}
2174
		}
2175
2176
		/**
2177
		 * Filters the array of modules available to be activated.
2178
		 *
2179
		 * @since 2.4.0
2180
		 *
2181
		 * @param array $modules Array of available modules.
2182
		 * @param string $min_version Minimum version number required to use modules.
2183
		 * @param string $max_version Maximum version number required to use modules.
2184
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2185
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2186
		 */
2187
		$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...
2188
2189
		if ( ! $min_version && ! $max_version && is_null( $requires_connection ) && is_null( $requires_user_connection ) ) {
2190
			return array_keys( $mods );
2191
		}
2192
2193
		$r = array();
2194
		foreach ( $mods as $slug => $introduced ) {
2195
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2196
				continue;
2197
			}
2198
2199
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2200
				continue;
2201
			}
2202
2203
			$mod_details = self::get_module( $slug );
2204
2205
			if ( null !== $requires_connection && (bool) $requires_connection !== $mod_details['requires_connection'] ) {
2206
				continue;
2207
			}
2208
2209
			if ( null !== $requires_user_connection && (bool) $requires_user_connection !== $mod_details['requires_user_connection'] ) {
2210
				continue;
2211
			}
2212
2213
			$r[] = $slug;
2214
		}
2215
2216
		return $r;
2217
	}
2218
2219
	/**
2220
	 * Get default modules loaded on activation.
2221
	 *
2222
	 * @param bool|string $min_version Onlu return modules introduced in this version or later. Default is false, do not filter.
2223
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2224
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2225
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2226
	 *
2227
	 * @return array $modules Array of module slugs
2228
	 */
2229
	public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2230
		$return = array();
2231
2232
		foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2233
			$module_data = self::get_module( $module );
2234
2235
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2236
				case 'yes':
2237
					$return[] = $module;
2238
					break;
2239
				case 'public':
2240
					if ( Jetpack_Options::get_option( 'public' ) ) {
2241
						$return[] = $module;
2242
					}
2243
					break;
2244
				case 'no':
2245
				default:
2246
					break;
2247
			}
2248
		}
2249
		/**
2250
		 * Filters the array of default modules.
2251
		 *
2252
		 * @since 2.5.0
2253
		 *
2254
		 * @param array $return Array of default modules.
2255
		 * @param string $min_version Minimum version number required to use modules.
2256
		 * @param string $max_version Maximum version number required to use modules.
2257
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2258
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2259
		 */
2260
		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...
2261
	}
2262
2263
	/**
2264
	 * Checks activated modules during auto-activation to determine
2265
	 * if any of those modules are being deprecated.  If so, close
2266
	 * them out, and add any replacement modules.
2267
	 *
2268
	 * Runs at priority 99 by default.
2269
	 *
2270
	 * This is run late, so that it can still activate a module if
2271
	 * the new module is a replacement for another that the user
2272
	 * currently has active, even if something at the normal priority
2273
	 * would kibosh everything.
2274
	 *
2275
	 * @since 2.6
2276
	 * @uses jetpack_get_default_modules filter
2277
	 * @param array $modules
2278
	 * @return array
2279
	 */
2280
	function handle_deprecated_modules( $modules ) {
2281
		$deprecated_modules = array(
2282
			'debug'            => null,  // Closed out and moved to the debugger library.
2283
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2284
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2285
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2286
		);
2287
2288
		// Don't activate SSO if they never completed activating WPCC.
2289
		if ( self::is_module_active( 'wpcc' ) ) {
2290
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2291
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2292
				$deprecated_modules['wpcc'] = null;
2293
			}
2294
		}
2295
2296
		foreach ( $deprecated_modules as $module => $replacement ) {
2297
			if ( self::is_module_active( $module ) ) {
2298
				self::deactivate_module( $module );
2299
				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...
2300
					$modules[] = $replacement;
2301
				}
2302
			}
2303
		}
2304
2305
		return array_unique( $modules );
2306
	}
2307
2308
	/**
2309
	 * Checks activated plugins during auto-activation to determine
2310
	 * if any of those plugins are in the list with a corresponding module
2311
	 * that is not compatible with the plugin. The module will not be allowed
2312
	 * to auto-activate.
2313
	 *
2314
	 * @since 2.6
2315
	 * @uses jetpack_get_default_modules filter
2316
	 * @param array $modules
2317
	 * @return array
2318
	 */
2319
	function filter_default_modules( $modules ) {
2320
2321
		$active_plugins = self::get_active_plugins();
2322
2323
		if ( ! empty( $active_plugins ) ) {
2324
2325
			// For each module we'd like to auto-activate...
2326
			foreach ( $modules as $key => $module ) {
2327
				// If there are potential conflicts for it...
2328
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2329
					// For each potential conflict...
2330
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2331
						// If that conflicting plugin is active...
2332
						if ( in_array( $plugin, $active_plugins ) ) {
2333
							// Remove that item from being auto-activated.
2334
							unset( $modules[ $key ] );
2335
						}
2336
					}
2337
				}
2338
			}
2339
		}
2340
2341
		return $modules;
2342
	}
2343
2344
	/**
2345
	 * Extract a module's slug from its full path.
2346
	 */
2347
	public static function get_module_slug( $file ) {
2348
		return str_replace( '.php', '', basename( $file ) );
2349
	}
2350
2351
	/**
2352
	 * Generate a module's path from its slug.
2353
	 */
2354
	public static function get_module_path( $slug ) {
2355
		/**
2356
		 * Filters the path of a modules.
2357
		 *
2358
		 * @since 7.4.0
2359
		 *
2360
		 * @param array $return The absolute path to a module's root php file
2361
		 * @param string $slug The module slug
2362
		 */
2363
		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...
2364
	}
2365
2366
	/**
2367
	 * Load module data from module file. Headers differ from WordPress
2368
	 * plugin headers to avoid them being identified as standalone
2369
	 * plugins on the WordPress plugins page.
2370
	 */
2371
	public static function get_module( $module ) {
2372
		$headers = array(
2373
			'name'                      => 'Module Name',
2374
			'description'               => 'Module Description',
2375
			'sort'                      => 'Sort Order',
2376
			'recommendation_order'      => 'Recommendation Order',
2377
			'introduced'                => 'First Introduced',
2378
			'changed'                   => 'Major Changes In',
2379
			'deactivate'                => 'Deactivate',
2380
			'free'                      => 'Free',
2381
			'requires_connection'       => 'Requires Connection',
2382
			'requires_user_connection'  => 'Requires User Connection',
2383
			'auto_activate'             => 'Auto Activate',
2384
			'module_tags'               => 'Module Tags',
2385
			'feature'                   => 'Feature',
2386
			'additional_search_queries' => 'Additional Search Queries',
2387
			'plan_classes'              => 'Plans',
2388
		);
2389
2390
		static $modules_details;
2391
		$file = self::get_module_path( self::get_module_slug( $module ) );
2392
2393
		if ( isset( $modules_details[ $module ] ) ) {
2394
			$mod = $modules_details[ $module ];
2395
		} else {
2396
2397
			$mod = self::get_file_data( $file, $headers );
2398
			if ( empty( $mod['name'] ) ) {
2399
				return false;
2400
			}
2401
2402
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2403
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2404
			$mod['deactivate']               = empty( $mod['deactivate'] );
2405
			$mod['free']                     = empty( $mod['free'] );
2406
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2407
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2408
2409
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2410
				$mod['auto_activate'] = 'No';
2411
			} else {
2412
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2413
			}
2414
2415
			if ( $mod['module_tags'] ) {
2416
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2417
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2418
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2419
			} else {
2420
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2421
			}
2422
2423 View Code Duplication
			if ( $mod['plan_classes'] ) {
2424
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2425
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2426
			} else {
2427
				$mod['plan_classes'] = array( 'free' );
2428
			}
2429
2430 View Code Duplication
			if ( $mod['feature'] ) {
2431
				$mod['feature'] = explode( ',', $mod['feature'] );
2432
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2433
			} else {
2434
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2435
			}
2436
2437
			$modules_details[ $module ] = $mod;
2438
2439
		}
2440
2441
		/**
2442
		 * Filters the feature array on a module.
2443
		 *
2444
		 * This filter allows you to control where each module is filtered: Recommended,
2445
		 * and the default "Other" listing.
2446
		 *
2447
		 * @since 3.5.0
2448
		 *
2449
		 * @param array   $mod['feature'] The areas to feature this module:
2450
		 *     'Recommended' shows on the main Jetpack admin screen.
2451
		 *     'Other' should be the default if no other value is in the array.
2452
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2453
		 * @param array   $mod All the currently assembled module data.
2454
		 */
2455
		$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...
2456
2457
		/**
2458
		 * Filter the returned data about a module.
2459
		 *
2460
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2461
		 * so please be careful.
2462
		 *
2463
		 * @since 3.6.0
2464
		 *
2465
		 * @param array   $mod    The details of the requested module.
2466
		 * @param string  $module The slug of the module, e.g. sharedaddy
2467
		 * @param string  $file   The path to the module source file.
2468
		 */
2469
		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...
2470
	}
2471
2472
	/**
2473
	 * Like core's get_file_data implementation, but caches the result.
2474
	 */
2475
	public static function get_file_data( $file, $headers ) {
2476
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2477
		$file_name = basename( $file );
2478
2479
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2480
2481
		$file_data_option = get_transient( $cache_key );
2482
2483
		if ( ! is_array( $file_data_option ) ) {
2484
			delete_transient( $cache_key );
2485
			$file_data_option = false;
2486
		}
2487
2488
		if ( false === $file_data_option ) {
2489
			$file_data_option = array();
2490
		}
2491
2492
		$key           = md5( $file_name . serialize( $headers ) );
2493
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2494
2495
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2496
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2497
			return $file_data_option[ $key ];
2498
		}
2499
2500
		$data = get_file_data( $file, $headers );
2501
2502
		$file_data_option[ $key ] = $data;
2503
2504
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2505
2506
		return $data;
2507
	}
2508
2509
	/**
2510
	 * Return translated module tag.
2511
	 *
2512
	 * @param string $tag Tag as it appears in each module heading.
2513
	 *
2514
	 * @return mixed
2515
	 */
2516
	public static function translate_module_tag( $tag ) {
2517
		return jetpack_get_module_i18n_tag( $tag );
2518
	}
2519
2520
	/**
2521
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2522
	 *
2523
	 * @since 3.9.2
2524
	 *
2525
	 * @param array $modules
2526
	 *
2527
	 * @return string|void
2528
	 */
2529
	public static function get_translated_modules( $modules ) {
2530
		foreach ( $modules as $index => $module ) {
2531
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2532
			if ( isset( $module['name'] ) ) {
2533
				$modules[ $index ]['name'] = $i18n_module['name'];
2534
			}
2535
			if ( isset( $module['description'] ) ) {
2536
				$modules[ $index ]['description']       = $i18n_module['description'];
2537
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2538
			}
2539
		}
2540
		return $modules;
2541
	}
2542
2543
	/**
2544
	 * Get a list of activated modules as an array of module slugs.
2545
	 */
2546
	public static function get_active_modules() {
2547
		$active = Jetpack_Options::get_option( 'active_modules' );
2548
2549
		if ( ! is_array( $active ) ) {
2550
			$active = array();
2551
		}
2552
2553
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2554
			$active[] = 'vaultpress';
2555
		} else {
2556
			$active = array_diff( $active, array( 'vaultpress' ) );
2557
		}
2558
2559
		// If protect is active on the main site of a multisite, it should be active on all sites.
2560
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2561
			$active[] = 'protect';
2562
		}
2563
2564
		/**
2565
		 * Allow filtering of the active modules.
2566
		 *
2567
		 * Gives theme and plugin developers the power to alter the modules that
2568
		 * are activated on the fly.
2569
		 *
2570
		 * @since 5.8.0
2571
		 *
2572
		 * @param array $active Array of active module slugs.
2573
		 */
2574
		$active = apply_filters( 'jetpack_active_modules', $active );
2575
2576
		return array_unique( $active );
2577
	}
2578
2579
	/**
2580
	 * Check whether or not a Jetpack module is active.
2581
	 *
2582
	 * @param string $module The slug of a Jetpack module.
2583
	 * @return bool
2584
	 *
2585
	 * @static
2586
	 */
2587
	public static function is_module_active( $module ) {
2588
		return in_array( $module, self::get_active_modules() );
2589
	}
2590
2591
	public static function is_module( $module ) {
2592
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2593
	}
2594
2595
	/**
2596
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2597
	 *
2598
	 * @param bool $catch True to start catching, False to stop.
2599
	 *
2600
	 * @static
2601
	 */
2602
	public static function catch_errors( $catch ) {
2603
		static $display_errors, $error_reporting;
2604
2605
		if ( $catch ) {
2606
			$display_errors  = @ini_set( 'display_errors', 1 );
2607
			$error_reporting = @error_reporting( E_ALL );
2608
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2609
		} else {
2610
			@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...
2611
			@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...
2612
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2613
		}
2614
	}
2615
2616
	/**
2617
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2618
	 */
2619
	public static function catch_errors_on_shutdown() {
2620
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2621
	}
2622
2623
	/**
2624
	 * Rewrite any string to make paths easier to read.
2625
	 *
2626
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2627
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2628
	 *
2629
	 * @param $string
2630
	 * @return mixed
2631
	 */
2632
	public static function alias_directories( $string ) {
2633
		// ABSPATH has a trailing slash.
2634
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2635
		// WP_CONTENT_DIR does not have a trailing slash.
2636
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2637
2638
		return $string;
2639
	}
2640
2641
	public static function activate_default_modules(
2642
		$min_version = false,
2643
		$max_version = false,
2644
		$other_modules = array(),
2645
		$redirect = null,
2646
		$send_state_messages = null,
2647
		$requires_connection = null,
2648
		$requires_user_connection = null
2649
	) {
2650
		$jetpack = self::init();
2651
2652
		if ( is_null( $redirect ) ) {
2653
			if (
2654
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2655
			||
2656
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2657
			||
2658
				( defined( 'WP_CLI' ) && WP_CLI )
2659
			||
2660
				( defined( 'DOING_CRON' ) && DOING_CRON )
2661
			||
2662
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2663
			) {
2664
				$redirect = false;
2665
			} elseif ( is_admin() ) {
2666
				$redirect = true;
2667
			} else {
2668
				$redirect = false;
2669
			}
2670
		}
2671
2672
		if ( is_null( $send_state_messages ) ) {
2673
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2674
		}
2675
2676
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2677
		$modules = array_merge( $other_modules, $modules );
2678
2679
		// Look for standalone plugins and disable if active.
2680
2681
		$to_deactivate = array();
2682
		foreach ( $modules as $module ) {
2683
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2684
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2685
			}
2686
		}
2687
2688
		$deactivated = array();
2689
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2690
			list( $probable_file, $probable_title ) = $deactivate_me;
2691
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2692
				$deactivated[] = $module;
2693
			}
2694
		}
2695
2696
		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...
2697
			if ( $send_state_messages ) {
2698
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2699
			}
2700
2701
			if ( $redirect ) {
2702
				$url = add_query_arg(
2703
					array(
2704
						'action'   => 'activate_default_modules',
2705
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2706
					),
2707
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2708
				);
2709
				wp_safe_redirect( $url );
2710
				exit;
2711
			}
2712
		}
2713
2714
		/**
2715
		 * Fires before default modules are activated.
2716
		 *
2717
		 * @since 1.9.0
2718
		 *
2719
		 * @param string    $min_version Minimum version number required to use modules.
2720
		 * @param string    $max_version Maximum version number required to use modules.
2721
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
2722
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2723
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2724
		 */
2725
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
2726
2727
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2728
		if ( $send_state_messages ) {
2729
			self::restate();
2730
			self::catch_errors( true );
2731
		}
2732
2733
		$active = self::get_active_modules();
2734
2735
		foreach ( $modules as $module ) {
2736
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2737
				$active[] = $module;
2738
				self::update_active_modules( $active );
2739
				continue;
2740
			}
2741
2742
			if ( $send_state_messages && in_array( $module, $active ) ) {
2743
				$module_info = self::get_module( $module );
2744 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2745
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2746
					if ( $active_state = self::state( $state ) ) {
2747
						$active_state = explode( ',', $active_state );
2748
					} else {
2749
						$active_state = array();
2750
					}
2751
					$active_state[] = $module;
2752
					self::state( $state, implode( ',', $active_state ) );
2753
				}
2754
				continue;
2755
			}
2756
2757
			$file = self::get_module_path( $module );
2758
			if ( ! file_exists( $file ) ) {
2759
				continue;
2760
			}
2761
2762
			// we'll override this later if the plugin can be included without fatal error
2763
			if ( $redirect ) {
2764
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2765
			}
2766
2767
			if ( $send_state_messages ) {
2768
				self::state( 'error', 'module_activation_failed' );
2769
				self::state( 'module', $module );
2770
			}
2771
2772
			ob_start();
2773
			require_once $file;
2774
2775
			$active[] = $module;
2776
2777 View Code Duplication
			if ( $send_state_messages ) {
2778
2779
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2780
				if ( $active_state = self::state( $state ) ) {
2781
					$active_state = explode( ',', $active_state );
2782
				} else {
2783
					$active_state = array();
2784
				}
2785
				$active_state[] = $module;
2786
				self::state( $state, implode( ',', $active_state ) );
2787
			}
2788
2789
			self::update_active_modules( $active );
2790
2791
			ob_end_clean();
2792
		}
2793
2794
		if ( $send_state_messages ) {
2795
			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...
2796
			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...
2797
		}
2798
2799
		self::catch_errors( false );
2800
		/**
2801
		 * Fires when default modules are activated.
2802
		 *
2803
		 * @since 1.9.0
2804
		 *
2805
		 * @param string    $min_version Minimum version number required to use modules.
2806
		 * @param string    $max_version Maximum version number required to use modules.
2807
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
2808
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2809
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2810
		 */
2811
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
2812
	}
2813
2814
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2815
		/**
2816
		 * Fires before a module is activated.
2817
		 *
2818
		 * @since 2.6.0
2819
		 *
2820
		 * @param string $module Module slug.
2821
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2822
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2823
		 */
2824
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2825
2826
		$jetpack = self::init();
2827
2828
		if ( ! strlen( $module ) ) {
2829
			return false;
2830
		}
2831
2832
		if ( ! self::is_module( $module ) ) {
2833
			return false;
2834
		}
2835
2836
		// If it's already active, then don't do it again
2837
		$active = self::get_active_modules();
2838
		foreach ( $active as $act ) {
2839
			if ( $act == $module ) {
2840
				return true;
2841
			}
2842
		}
2843
2844
		$module_data = self::get_module( $module );
2845
2846
		$is_offline_mode = ( new Status() )->is_offline_mode();
2847
		if ( ! self::is_connection_ready() ) {
2848
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
2849
				return false;
2850
			}
2851
2852
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
2853
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
2854
				return false;
2855
			}
2856
		}
2857
2858
		// Check and see if the old plugin is active
2859
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2860
			// Deactivate the old plugin
2861
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2862
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2863
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2864
				self::state( 'deactivated_plugins', $module );
2865
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2866
				exit;
2867
			}
2868
		}
2869
2870
		// Protect won't work with mis-configured IPs
2871
		if ( 'protect' === $module ) {
2872
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2873
			if ( ! jetpack_protect_get_ip() ) {
2874
				self::state( 'message', 'protect_misconfigured_ip' );
2875
				return false;
2876
			}
2877
		}
2878
2879
		if ( ! Jetpack_Plan::supports( $module ) ) {
2880
			return false;
2881
		}
2882
2883
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2884
		self::state( 'module', $module );
2885
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2886
2887
		self::catch_errors( true );
2888
		ob_start();
2889
		require self::get_module_path( $module );
2890
		/** This action is documented in class.jetpack.php */
2891
		do_action( 'jetpack_activate_module', $module );
2892
		$active[] = $module;
2893
		self::update_active_modules( $active );
2894
2895
		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...
2896
		ob_end_clean();
2897
		self::catch_errors( false );
2898
2899
		if ( $redirect ) {
2900
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2901
		}
2902
		if ( $exit ) {
2903
			exit;
2904
		}
2905
		return true;
2906
	}
2907
2908
	public static function deactivate_module( $module ) {
2909
		/**
2910
		 * Fires when a module is deactivated.
2911
		 *
2912
		 * @since 1.9.0
2913
		 *
2914
		 * @param string $module Module slug.
2915
		 */
2916
		do_action( 'jetpack_pre_deactivate_module', $module );
2917
2918
		$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...
2919
2920
		$active = self::get_active_modules();
2921
		$new    = array_filter( array_diff( $active, (array) $module ) );
2922
2923
		return self::update_active_modules( $new );
2924
	}
2925
2926
	public static function enable_module_configurable( $module ) {
2927
		$module = self::get_module_slug( $module );
2928
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2929
	}
2930
2931
	/**
2932
	 * Composes a module configure URL. It uses Jetpack settings search as default value
2933
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
2934
	 *
2935
	 * @param string $module Module slug
2936
	 * @return string $url module configuration URL
2937
	 */
2938
	public static function module_configuration_url( $module ) {
2939
		$module      = self::get_module_slug( $module );
2940
		$default_url = self::admin_url() . "#/settings?term=$module";
2941
		/**
2942
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
2943
		 *
2944
		 * @since 6.9.0
2945
		 *
2946
		 * @param string $default_url Default url, which redirects to jetpack settings page.
2947
		 */
2948
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
2949
2950
		return $url;
2951
	}
2952
2953
	/* Installation */
2954
	public static function bail_on_activation( $message, $deactivate = true ) {
2955
		?>
2956
<!doctype html>
2957
<html>
2958
<head>
2959
<meta charset="<?php bloginfo( 'charset' ); ?>">
2960
<style>
2961
* {
2962
	text-align: center;
2963
	margin: 0;
2964
	padding: 0;
2965
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2966
}
2967
p {
2968
	margin-top: 1em;
2969
	font-size: 18px;
2970
}
2971
</style>
2972
<body>
2973
<p><?php echo esc_html( $message ); ?></p>
2974
</body>
2975
</html>
2976
		<?php
2977
		if ( $deactivate ) {
2978
			$plugins = get_option( 'active_plugins' );
2979
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2980
			$update  = false;
2981
			foreach ( $plugins as $i => $plugin ) {
2982
				if ( $plugin === $jetpack ) {
2983
					$plugins[ $i ] = false;
2984
					$update        = true;
2985
				}
2986
			}
2987
2988
			if ( $update ) {
2989
				update_option( 'active_plugins', array_filter( $plugins ) );
2990
			}
2991
		}
2992
		exit;
2993
	}
2994
2995
	/**
2996
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2997
	 *
2998
	 * @static
2999
	 */
3000
	public static function plugin_activation( $network_wide ) {
3001
		Jetpack_Options::update_option( 'activated', 1 );
3002
3003
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3004
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3005
		}
3006
3007
		if ( $network_wide ) {
3008
			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...
3009
		}
3010
3011
		// For firing one-off events (notices) immediately after activation
3012
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3013
3014
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3015
3016
		Health::on_jetpack_activated();
3017
3018
		self::plugin_initialize();
3019
	}
3020
3021
	public static function get_activation_source( $referer_url ) {
3022
3023
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3024
			return array( 'wp-cli', null );
3025
		}
3026
3027
		$referer = wp_parse_url( $referer_url );
3028
3029
		$source_type  = 'unknown';
3030
		$source_query = null;
3031
3032
		if ( ! is_array( $referer ) ) {
3033
			return array( $source_type, $source_query );
3034
		}
3035
3036
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3037
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3038
3039
		if ( isset( $referer['query'] ) ) {
3040
			parse_str( $referer['query'], $query_parts );
3041
		} else {
3042
			$query_parts = array();
3043
		}
3044
3045
		if ( $plugins_path === $referer['path'] ) {
3046
			$source_type = 'list';
3047
		} elseif ( $plugins_install_path === $referer['path'] ) {
3048
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3049
			switch ( $tab ) {
3050
				case 'popular':
3051
					$source_type = 'popular';
3052
					break;
3053
				case 'recommended':
3054
					$source_type = 'recommended';
3055
					break;
3056
				case 'favorites':
3057
					$source_type = 'favorites';
3058
					break;
3059
				case 'search':
3060
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3061
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3062
					break;
3063
				default:
3064
					$source_type = 'featured';
3065
			}
3066
		}
3067
3068
		return array( $source_type, $source_query );
3069
	}
3070
3071
	/**
3072
	 * Runs before bumping version numbers up to a new version
3073
	 *
3074
	 * @param string $version    Version:timestamp.
3075
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3076
	 */
3077
	public static function do_version_bump( $version, $old_version ) {
3078
		if ( $old_version ) { // For existing Jetpack installations.
3079
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3080
3081
			// If a front end page is visited after the update, the 'wp' action will fire.
3082
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3083
3084
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3085
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3086
		}
3087
	}
3088
3089
	/**
3090
	 * Sets the display_update_modal state.
3091
	 */
3092
	public static function set_update_modal_display() {
3093
		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...
3094
3095
	}
3096
3097
	/**
3098
	 * Enqueues the block library styles.
3099
	 *
3100
	 * @param string $hook The current admin page.
3101
	 */
3102
	public static function enqueue_block_style( $hook ) {
3103
		if ( 'toplevel_page_jetpack' === $hook ) {
3104
			wp_enqueue_style( 'wp-block-library' );
3105
		}
3106
	}
3107
3108
	/**
3109
	 * Sets the internal version number and activation state.
3110
	 *
3111
	 * @static
3112
	 */
3113
	public static function plugin_initialize() {
3114
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3115
			Jetpack_Options::update_option( 'activated', 2 );
3116
		}
3117
3118 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3119
			$version = $old_version = JETPACK__VERSION . ':' . time();
3120
			/** This action is documented in class.jetpack.php */
3121
			do_action( 'updating_jetpack_version', $version, false );
3122
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3123
		}
3124
3125
		self::load_modules();
3126
3127
		Jetpack_Options::delete_option( 'do_activate' );
3128
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3129
	}
3130
3131
	/**
3132
	 * Removes all connection options
3133
	 *
3134
	 * @static
3135
	 */
3136
	public static function plugin_deactivation() {
3137
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3138
		$tracking = new Tracking();
3139
		$tracking->record_user_event( 'deactivate_plugin', array() );
3140
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3141
			Jetpack_Network::init()->deactivate();
3142
		} else {
3143
			self::disconnect( false );
3144
			// Jetpack_Heartbeat::init()->deactivate();
3145
		}
3146
	}
3147
3148
	/**
3149
	 * Disconnects from the Jetpack servers.
3150
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3151
	 *
3152
	 * @static
3153
	 */
3154
	public static function disconnect( $update_activated_state = true ) {
3155
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3156
3157
		$connection = self::connection();
3158
3159
		( new Nonce_Handler() )->clean_all();
3160
3161
		// If the site is in an IDC because sync is not allowed,
3162
		// let's make sure to not disconnect the production site.
3163
		if ( ! Identity_Crisis::validate_sync_error_idc_option() ) {
3164
			$tracking = new Tracking();
3165
			$tracking->record_user_event( 'disconnect_site', array() );
3166
3167
			$connection->disconnect_site_wpcom( true );
3168
		}
3169
3170
		$connection->delete_all_connection_tokens( true );
3171
		Identity_Crisis::clear_all_idc_options();
3172
3173
		if ( $update_activated_state ) {
3174
			Jetpack_Options::update_option( 'activated', 4 );
3175
		}
3176
3177
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3178
			// Check then record unique disconnection if site has never been disconnected previously
3179
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3180
				$jetpack_unique_connection['disconnected'] = 1;
3181
			} else {
3182
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3183
					// track unique disconnect
3184
					$jetpack = self::init();
3185
3186
					$jetpack->stat( 'connections', 'unique-disconnect' );
3187
					$jetpack->do_stats( 'server_side' );
3188
				}
3189
				// increment number of times disconnected
3190
				$jetpack_unique_connection['disconnected'] += 1;
3191
			}
3192
3193
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3194
		}
3195
3196
		// Delete all the sync related data. Since it could be taking up space.
3197
		Sender::get_instance()->uninstall();
3198
3199
	}
3200
3201
	/**
3202
	 * Disconnects the user
3203
	 *
3204
	 * @param int $user_id The user ID to disconnect.
3205
	 */
3206
	public function disconnect_user( $user_id ) {
3207
		$this->connection_manager->disconnect_user( $user_id );
3208
	}
3209
3210
	/**
3211
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3212
	 *
3213
	 * @deprecated since Jetpack 9.7.0
3214
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
3215
	 *
3216
	 * @return bool|WP_Error
3217
	 */
3218
	public static function try_registration() {
3219
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
3220
		return static::connection()->try_registration();
3221
	}
3222
3223
	/**
3224
	 * Checking the domain names in beta versions.
3225
	 * If this is a development version, before attempting to connect, let's make sure that the domains are viable.
3226
	 *
3227
	 * @param null|\WP_Error $error The domain validation error, or `null` if everything's fine.
3228
	 *
3229
	 * @return null|\WP_Error The domain validation error, or `null` if everything's fine.
3230
	 */
3231
	public static function registration_check_domains( $error ) {
3232
		if ( static::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3233
			$domains_to_check = array_unique(
3234
				array(
3235
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3236
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3237
				)
3238
			);
3239
			foreach ( $domains_to_check as $domain ) {
3240
				$result = static::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3239 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...
3241
				if ( is_wp_error( $result ) ) {
3242
					return $result;
3243
				}
3244
			}
3245
		}
3246
3247
		return $error;
3248
	}
3249
3250
	/**
3251
	 * Tracking an internal event log. Try not to put too much chaff in here.
3252
	 *
3253
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3254
	 */
3255
	public static function log( $code, $data = null ) {
3256
		// only grab the latest 200 entries
3257
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3258
3259
		// Append our event to the log
3260
		$log_entry = array(
3261
			'time'    => time(),
3262
			'user_id' => get_current_user_id(),
3263
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3264
			'code'    => $code,
3265
		);
3266
		// Don't bother storing it unless we've got some.
3267
		if ( ! is_null( $data ) ) {
3268
			$log_entry['data'] = $data;
3269
		}
3270
		$log[] = $log_entry;
3271
3272
		// Try add_option first, to make sure it's not autoloaded.
3273
		// @todo: Add an add_option method to Jetpack_Options
3274
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3275
			Jetpack_Options::update_option( 'log', $log );
3276
		}
3277
3278
		/**
3279
		 * Fires when Jetpack logs an internal event.
3280
		 *
3281
		 * @since 3.0.0
3282
		 *
3283
		 * @param array $log_entry {
3284
		 *  Array of details about the log entry.
3285
		 *
3286
		 *  @param string time Time of the event.
3287
		 *  @param int user_id ID of the user who trigerred the event.
3288
		 *  @param int blog_id Jetpack Blog ID.
3289
		 *  @param string code Unique name for the event.
3290
		 *  @param string data Data about the event.
3291
		 * }
3292
		 */
3293
		do_action( 'jetpack_log_entry', $log_entry );
3294
	}
3295
3296
	/**
3297
	 * Get the internal event log.
3298
	 *
3299
	 * @param $event (string) - only return the specific log events
3300
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3301
	 *
3302
	 * @return array of log events || WP_Error for invalid params
3303
	 */
3304
	public static function get_log( $event = false, $num = false ) {
3305
		if ( $event && ! is_string( $event ) ) {
3306
			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...
3307
		}
3308
3309
		if ( $num && ! is_numeric( $num ) ) {
3310
			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...
3311
		}
3312
3313
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3314
3315
		// If nothing set - act as it did before, otherwise let's start customizing the output
3316
		if ( ! $num && ! $event ) {
3317
			return $entire_log;
3318
		} else {
3319
			$entire_log = array_reverse( $entire_log );
3320
		}
3321
3322
		$custom_log_output = array();
3323
3324
		if ( $event ) {
3325
			foreach ( $entire_log as $log_event ) {
3326
				if ( $event == $log_event['code'] ) {
3327
					$custom_log_output[] = $log_event;
3328
				}
3329
			}
3330
		} else {
3331
			$custom_log_output = $entire_log;
3332
		}
3333
3334
		if ( $num ) {
3335
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3336
		}
3337
3338
		return $custom_log_output;
3339
	}
3340
3341
	/**
3342
	 * Log modification of important settings.
3343
	 */
3344
	public static function log_settings_change( $option, $old_value, $value ) {
3345
		switch ( $option ) {
3346
			case 'jetpack_sync_non_public_post_stati':
3347
				self::log( $option, $value );
3348
				break;
3349
		}
3350
	}
3351
3352
	/**
3353
	 * Return stat data for WPCOM sync
3354
	 */
3355
	public static function get_stat_data( $encode = true, $extended = true ) {
3356
		$data = Jetpack_Heartbeat::generate_stats_array();
3357
3358
		if ( $extended ) {
3359
			$additional_data = self::get_additional_stat_data();
3360
			$data            = array_merge( $data, $additional_data );
3361
		}
3362
3363
		if ( $encode ) {
3364
			return json_encode( $data );
3365
		}
3366
3367
		return $data;
3368
	}
3369
3370
	/**
3371
	 * Get additional stat data to sync to WPCOM
3372
	 */
3373
	public static function get_additional_stat_data( $prefix = '' ) {
3374
		$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...
3375
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3376
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3377
		$return[ "{$prefix}site-count" ]    = 0;
3378
3379
		if ( function_exists( 'get_blog_count' ) ) {
3380
			$return[ "{$prefix}site-count" ] = get_blog_count();
3381
		}
3382
		return $return;
3383
	}
3384
3385
	private static function get_site_user_count() {
3386
		global $wpdb;
3387
3388
		if ( function_exists( 'wp_is_large_network' ) ) {
3389
			if ( wp_is_large_network( 'users' ) ) {
3390
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3391
			}
3392
		}
3393
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3394
			// It wasn't there, so regenerate the data and save the transient
3395
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3396
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3397
		}
3398
		return $user_count;
3399
	}
3400
3401
	/* Admin Pages */
3402
3403
	function admin_init() {
3404
		// If the plugin is not connected, display a connect message.
3405
		if (
3406
			// the plugin was auto-activated and needs its candy
3407
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3408
		||
3409
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3410
			! Jetpack_Options::get_option( 'activated' )
3411
		) {
3412
			self::plugin_initialize();
3413
		}
3414
3415
		$is_offline_mode              = ( new Status() )->is_offline_mode();
3416
		$fallback_no_verify_ssl_certs = Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
3417
		/** Already documented in automattic/jetpack-connection::src/class-client.php */
3418
		$client_verify_ssl_certs = apply_filters( 'jetpack_client_verify_ssl_certs', false );
3419
3420
		if ( ! $is_offline_mode ) {
3421
			Jetpack_Connection_Banner::init();
3422
		}
3423
3424
		if ( ( self::is_connection_ready() || $is_offline_mode ) && false === $fallback_no_verify_ssl_certs && ! $client_verify_ssl_certs ) {
3425
			// Upgrade: 1.1 -> 1.1.1
3426
			// Check and see if host can verify the Jetpack servers' SSL certificate
3427
			$args = array();
3428
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3429
		}
3430
3431
		Jetpack_Recommendations_Banner::init();
3432
3433
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3434
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3435
		}
3436
3437
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3438
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3439
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3440
3441
		if ( isset( $_COOKIE['jetpackState']['display_update_modal'] ) ) {
3442
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3443
		}
3444
3445
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3446
3447
		if ( self::is_connection_ready() || $is_offline_mode ) {
3448
			// Artificially throw errors in certain specific cases during plugin activation.
3449
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3450
		}
3451
3452
		// Add custom column in wp-admin/users.php to show whether user is linked.
3453
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3454
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3455
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3456
	}
3457
3458
	function admin_body_class( $admin_body_class = '' ) {
3459
		$classes = explode( ' ', trim( $admin_body_class ) );
3460
3461
		$classes[] = self::is_connection_ready() ? 'jetpack-connected' : 'jetpack-disconnected';
3462
3463
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3464
		return " $admin_body_class ";
3465
	}
3466
3467
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3468
		return $admin_body_class . ' jetpack-pagestyles ';
3469
	}
3470
3471
	/**
3472
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3473
	 * This function artificially throws errors for such cases (per a specific list).
3474
	 *
3475
	 * @param string $plugin The activated plugin.
3476
	 */
3477
	function throw_error_on_activate_plugin( $plugin ) {
3478
		$active_modules = self::get_active_modules();
3479
3480
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3481
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3482
			$throw = false;
3483
3484
			// Try and make sure it really was the stats plugin
3485
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3486
				if ( 'stats.php' == basename( $plugin ) ) {
3487
					$throw = true;
3488
				}
3489
			} else {
3490
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3491
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3492
					$throw = true;
3493
				}
3494
			}
3495
3496
			if ( $throw ) {
3497
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3498
			}
3499
		}
3500
	}
3501
3502
	function intercept_plugin_error_scrape_init() {
3503
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3504
	}
3505
3506
	function intercept_plugin_error_scrape( $action, $result ) {
3507
		if ( ! $result ) {
3508
			return;
3509
		}
3510
3511
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3512
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3513
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3514
			}
3515
		}
3516
	}
3517
3518
	/**
3519
	 * Register the remote file upload request handlers, if needed.
3520
	 *
3521
	 * @access public
3522
	 */
3523
	public function add_remote_request_handlers() {
3524
		// Remote file uploads are allowed only via AJAX requests.
3525
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3526
			return;
3527
		}
3528
3529
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3530
		$remote_request_actions = array(
3531
			'jetpack_upload_file',
3532
			'jetpack_update_file',
3533
		);
3534
3535
		// phpcs:ignore WordPress.Security.NonceVerification
3536
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3537
			return;
3538
		}
3539
3540
		// Require Jetpack authentication for the remote file upload AJAX requests.
3541
		if ( ! $this->connection_manager ) {
3542
			$this->connection_manager = new Connection_Manager();
3543
		}
3544
3545
		$this->connection_manager->require_jetpack_authentication();
3546
3547
		// Register the remote file upload AJAX handlers.
3548
		foreach ( $remote_request_actions as $action ) {
3549
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3550
		}
3551
	}
3552
3553
	/**
3554
	 * Handler for Jetpack remote file uploads.
3555
	 *
3556
	 * @access public
3557
	 */
3558
	public function remote_request_handlers() {
3559
		$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...
3560
3561
		switch ( current_filter() ) {
3562
			case 'wp_ajax_nopriv_jetpack_upload_file':
3563
				$response = $this->upload_handler();
3564
				break;
3565
3566
			case 'wp_ajax_nopriv_jetpack_update_file':
3567
				$response = $this->upload_handler( true );
3568
				break;
3569
			default:
3570
				$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...
3571
				break;
3572
		}
3573
3574
		if ( ! $response ) {
3575
			$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...
3576
		}
3577
3578
		if ( is_wp_error( $response ) ) {
3579
			$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...
3580
			$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...
3581
			$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...
3582
3583
			if ( ! is_int( $status_code ) ) {
3584
				$status_code = 400;
3585
			}
3586
3587
			status_header( $status_code );
3588
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3589
		}
3590
3591
		status_header( 200 );
3592
		if ( true === $response ) {
3593
			exit;
3594
		}
3595
3596
		die( json_encode( (object) $response ) );
3597
	}
3598
3599
	/**
3600
	 * Uploads a file gotten from the global $_FILES.
3601
	 * If `$update_media_item` is true and `post_id` is defined
3602
	 * the attachment file of the media item (gotten through of the post_id)
3603
	 * will be updated instead of add a new one.
3604
	 *
3605
	 * @param  boolean $update_media_item - update media attachment
3606
	 * @return array - An array describing the uploadind files process
3607
	 */
3608
	function upload_handler( $update_media_item = false ) {
3609
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3610
			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...
3611
		}
3612
3613
		$user = wp_authenticate( '', '' );
3614
		if ( ! $user || is_wp_error( $user ) ) {
3615
			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...
3616
		}
3617
3618
		wp_set_current_user( $user->ID );
3619
3620
		if ( ! current_user_can( 'upload_files' ) ) {
3621
			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...
3622
		}
3623
3624
		if ( empty( $_FILES ) ) {
3625
			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...
3626
		}
3627
3628
		foreach ( array_keys( $_FILES ) as $files_key ) {
3629
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3630
				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...
3631
			}
3632
		}
3633
3634
		$media_keys = array_keys( $_FILES['media'] );
3635
3636
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3637
		if ( ! $token || is_wp_error( $token ) ) {
3638
			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...
3639
		}
3640
3641
		$uploaded_files = array();
3642
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3643
		unset( $GLOBALS['post'] );
3644
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3645
			$file = array();
3646
			foreach ( $media_keys as $media_key ) {
3647
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3648
			}
3649
3650
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3651
3652
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3653
			if ( $hmac_provided !== $hmac_file ) {
3654
				$uploaded_files[ $index ] = (object) array(
3655
					'error'             => 'invalid_hmac',
3656
					'error_description' => 'The corresponding HMAC for this file does not match',
3657
				);
3658
				continue;
3659
			}
3660
3661
			$_FILES['.jetpack.upload.'] = $file;
3662
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3663
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3664
				$post_id = 0;
3665
			}
3666
3667
			if ( $update_media_item ) {
3668
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3669
					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...
3670
				}
3671
3672
				$media_array = $_FILES['media'];
3673
3674
				$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...
3675
				$file_array['type']     = $media_array['type'][0];
3676
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3677
				$file_array['error']    = $media_array['error'][0];
3678
				$file_array['size']     = $media_array['size'][0];
3679
3680
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3681
3682
				if ( is_wp_error( $edited_media_item ) ) {
3683
					return $edited_media_item;
3684
				}
3685
3686
				$response = (object) array(
3687
					'id'   => (string) $post_id,
3688
					'file' => (string) $edited_media_item->post_title,
3689
					'url'  => (string) wp_get_attachment_url( $post_id ),
3690
					'type' => (string) $edited_media_item->post_mime_type,
3691
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3692
				);
3693
3694
				return (array) array( $response );
3695
			}
3696
3697
			$attachment_id = media_handle_upload(
3698
				'.jetpack.upload.',
3699
				$post_id,
3700
				array(),
3701
				array(
3702
					'action' => 'jetpack_upload_file',
3703
				)
3704
			);
3705
3706
			if ( ! $attachment_id ) {
3707
				$uploaded_files[ $index ] = (object) array(
3708
					'error'             => 'unknown',
3709
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3710
				);
3711
			} elseif ( is_wp_error( $attachment_id ) ) {
3712
				$uploaded_files[ $index ] = (object) array(
3713
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3714
					'error_description' => $attachment_id->get_error_message(),
3715
				);
3716
			} else {
3717
				$attachment               = get_post( $attachment_id );
3718
				$uploaded_files[ $index ] = (object) array(
3719
					'id'   => (string) $attachment_id,
3720
					'file' => $attachment->post_title,
3721
					'url'  => wp_get_attachment_url( $attachment_id ),
3722
					'type' => $attachment->post_mime_type,
3723
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3724
				);
3725
				// Zip files uploads are not supported unless they are done for installation purposed
3726
				// lets delete them in case something goes wrong in this whole process
3727
				if ( 'application/zip' === $attachment->post_mime_type ) {
3728
					// Schedule a cleanup for 2 hours from now in case of failed install.
3729
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3730
				}
3731
			}
3732
		}
3733
		if ( ! is_null( $global_post ) ) {
3734
			$GLOBALS['post'] = $global_post;
3735
		}
3736
3737
		return $uploaded_files;
3738
	}
3739
3740
	/**
3741
	 * Add help to the Jetpack page
3742
	 *
3743
	 * @since Jetpack (1.2.3)
3744
	 * @return false if not the Jetpack page
3745
	 */
3746
	function admin_help() {
3747
		$current_screen = get_current_screen();
3748
3749
		// Overview
3750
		$current_screen->add_help_tab(
3751
			array(
3752
				'id'      => 'home',
3753
				'title'   => __( 'Home', 'jetpack' ),
3754
				'content' =>
3755
					'<p><strong>' . __( 'Jetpack', 'jetpack' ) . '</strong></p>' .
3756
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3757
					'<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>',
3758
			)
3759
		);
3760
3761
		// Screen Content
3762
		if ( current_user_can( 'manage_options' ) ) {
3763
			$current_screen->add_help_tab(
3764
				array(
3765
					'id'      => 'settings',
3766
					'title'   => __( 'Settings', 'jetpack' ),
3767
					'content' =>
3768
						'<p><strong>' . __( 'Jetpack', 'jetpack' ) . '</strong></p>' .
3769
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3770
						'<ol>' .
3771
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3772
							'<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>' .
3773
						'</ol>' .
3774
						'<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>',
3775
				)
3776
			);
3777
		}
3778
3779
		// Help Sidebar
3780
		$support_url = Redirect::get_url( 'jetpack-support' );
3781
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3782
		$current_screen->set_help_sidebar(
3783
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3784
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3785
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3786
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3787
		);
3788
	}
3789
3790
	function admin_menu_css() {
3791
		wp_enqueue_style( 'jetpack-icons' );
3792
	}
3793
3794
	function admin_menu_order() {
3795
		return true;
3796
	}
3797
3798
	function jetpack_menu_order( $menu_order ) {
3799
		$jp_menu_order = array();
3800
3801
		foreach ( $menu_order as $index => $item ) {
3802
			if ( $item != 'jetpack' ) {
3803
				$jp_menu_order[] = $item;
3804
			}
3805
3806
			if ( $index == 0 ) {
3807
				$jp_menu_order[] = 'jetpack';
3808
			}
3809
		}
3810
3811
		return $jp_menu_order;
3812
	}
3813
3814
	function admin_banner_styles() {
3815
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3816
3817 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3818
			wp_register_style(
3819
				'jetpack-dops-style',
3820
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3821
				array(),
3822
				JETPACK__VERSION
3823
			);
3824
		}
3825
3826
		wp_enqueue_style(
3827
			'jetpack',
3828
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3829
			array( 'jetpack-dops-style' ),
3830
			JETPACK__VERSION . '-20121016'
3831
		);
3832
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3833
		wp_style_add_data( 'jetpack', 'suffix', $min );
3834
	}
3835
3836
	function plugin_action_links( $actions ) {
3837
3838
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), __( 'My Jetpack', 'jetpack' ) ) );
3839
3840
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
3841
			return array_merge(
3842
				$jetpack_home,
3843
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3844
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3845
				$actions
3846
			);
3847
		}
3848
3849
		return array_merge( $jetpack_home, $actions );
3850
	}
3851
3852
	/**
3853
	 * Adds the deactivation warning modal if there are other active plugins using the connection
3854
	 *
3855
	 * @param string $hook The current admin page.
3856
	 *
3857
	 * @return void
3858
	 */
3859
	public function deactivate_dialog( $hook ) {
3860
		if (
3861
			'plugins.php' === $hook
3862
			&& self::is_connection_ready()
3863
		) {
3864
3865
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
3866
3867
			if ( count( $active_plugins_using_connection ) > 1 ) {
3868
3869
				add_thickbox();
3870
3871
				// Register jp-tracks-functions dependency.
3872
				Tracking::register_tracks_functions_scripts();
3873
3874
				wp_enqueue_script(
3875
					'jetpack-deactivate-dialog-js',
3876
					Assets::get_file_url_for_environment(
3877
						'_inc/build/jetpack-deactivate-dialog.min.js',
3878
						'_inc/jetpack-deactivate-dialog.js'
3879
					),
3880
					array( 'jquery', 'jp-tracks-functions' ),
3881
					JETPACK__VERSION,
3882
					true
3883
				);
3884
3885
				wp_localize_script(
3886
					'jetpack-deactivate-dialog-js',
3887
					'deactivate_dialog',
3888
					array(
3889
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
3890
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
3891
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
3892
					)
3893
				);
3894
3895
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
3896
3897
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
3898
			}
3899
		}
3900
	}
3901
3902
	/**
3903
	 * Outputs the content of the deactivation modal
3904
	 *
3905
	 * @return void
3906
	 */
3907
	public function deactivate_dialog_content() {
3908
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
3909
		unset( $active_plugins_using_connection['jetpack'] );
3910
		$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 3908 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...
3911
	}
3912
3913
	/**
3914
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
3915
	 *
3916
	 * @param string $login_url The wp-login URL.
3917
	 * @param string $redirect  URL to redirect users after logging in.
3918
	 * @since Jetpack 8.4
3919
	 * @return string
3920
	 */
3921
	public function login_url( $login_url, $redirect ) {
3922
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
3923
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
3924
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
3925
		}
3926
		return $login_url;
3927
	}
3928
3929
	/**
3930
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
3931
	 *
3932
	 * @since Jetpack 8.4
3933
	 */
3934
	public function login_init() {
3935
		// phpcs:ignore WordPress.Security.NonceVerification
3936
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
3937
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3938
			wp_safe_redirect(
3939
				add_query_arg(
3940
					array(
3941
						'forceInstall' => 1,
3942
						'url'          => rawurlencode( get_site_url() ),
3943
					),
3944
					// @todo provide way to go to specific calypso env.
3945
					self::get_calypso_host() . 'jetpack/connect'
3946
				)
3947
			);
3948
			exit;
3949
		}
3950
	}
3951
3952
	/*
3953
	 * Registration flow:
3954
	 * 1 - ::admin_page_load() action=register
3955
	 * 2 - ::try_registration()
3956
	 * 3 - ::register()
3957
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3958
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3959
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3960
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3961
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3962
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3963
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3964
	 *       jetpack_id, jetpack_secret, jetpack_public
3965
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3966
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3967
	 * 5 - user logs in with WP.com account
3968
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3969
	 *		- Manager::authorize()
3970
	 *		- Manager::get_token()
3971
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3972
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3973
	 *			- which responds with access_token, token_type, scope
3974
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
3975
	 *		- Jetpack::activate_default_modules()
3976
	 *     		- Deactivates deprecated plugins
3977
	 *     		- Activates all default modules
3978
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3979
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3980
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3981
	 *     Done!
3982
	 */
3983
3984
	/**
3985
	 * Handles the page load events for the Jetpack admin page
3986
	 */
3987
	function admin_page_load() {
3988
		$error = false;
3989
3990
		// Make sure we have the right body class to hook stylings for subpages off of.
3991
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
3992
3993
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3994
			// Should only be used in intermediate redirects to preserve state across redirects
3995
			self::restate();
3996
		}
3997
3998
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3999
			// @todo: Add validation against a known allowed list.
4000
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4001
			// User clicked in the iframe to link their accounts
4002
			if ( ! self::connection()->is_user_connected() ) {
4003
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4004
4005
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4006
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4007
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4008
4009
				if ( isset( $_GET['notes_iframe'] ) ) {
4010
					$connect_url .= '&notes_iframe';
4011
				}
4012
				wp_redirect( $connect_url );
4013
				exit;
4014
			} else {
4015
				if ( ! isset( $_GET['calypso_env'] ) ) {
4016
					self::state( 'message', 'already_authorized' );
4017
					wp_safe_redirect( self::admin_url() );
4018
					exit;
4019
				} else {
4020
					$connect_url  = $this->build_connect_url( true, false, $from );
4021
					$connect_url .= '&already_authorized=true';
4022
					wp_redirect( $connect_url );
4023
					exit;
4024
				}
4025
			}
4026
		}
4027
4028
		if ( isset( $_GET['action'] ) ) {
4029
			switch ( $_GET['action'] ) {
4030
				case 'authorize_redirect':
4031
					self::log( 'authorize_redirect' );
4032
4033
					add_filter(
4034
						'allowed_redirect_hosts',
4035
						function ( $domains ) {
4036
							$domains[] = 'jetpack.com';
4037
							$domains[] = 'jetpack.wordpress.com';
4038
							$domains[] = 'wordpress.com';
4039
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4040
							return array_unique( $domains );
4041
						}
4042
					);
4043
4044
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4045
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4046
4047
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4048
						// The destination URL is missing or invalid, nothing to do here.
4049
						exit;
4050
					}
4051
4052
					if ( static::connection()->is_connected() && static::connection()->is_user_connected() ) {
4053
						// The user is either already connected, or finished the connection process.
4054
						wp_safe_redirect( $dest_url );
4055
						exit;
4056
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4057
						// The user decided not to proceed with setting up the connection.
4058
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4059
						exit;
4060
					}
4061
4062
					$redirect_args = array(
4063
						'page'     => 'jetpack',
4064
						'action'   => 'authorize_redirect',
4065
						'dest_url' => rawurlencode( $dest_url ),
4066
						'done'     => '1',
4067
					);
4068
4069
					if ( ! empty( $_GET['from'] ) && 'jetpack_site_only_checkout' === $_GET['from'] ) {
4070
						$redirect_args['from'] = 'jetpack_site_only_checkout';
4071
					}
4072
4073
					wp_safe_redirect( static::build_authorize_url( self::admin_url( $redirect_args ) ) );
0 ignored issues
show
Documentation introduced by
self::admin_url($redirect_args) 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...
4074
					exit;
4075
				case 'authorize':
4076
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4077
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4078
					exit;
4079
				case 'register':
4080
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4081
						$error = 'cheatin';
4082
						break;
4083
					}
4084
					check_admin_referer( 'jetpack-register' );
4085
					self::log( 'register' );
4086
					self::maybe_set_version_option();
4087
					$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4088
					if ( $from ) {
4089
						static::connection()->add_register_request_param( 'from', (string) $from );
4090
					}
4091
					$registered = static::connection()->try_registration();
4092
					if ( is_wp_error( $registered ) ) {
4093
						$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...
4094
						self::state( 'error', $error );
4095
						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...
4096
4097
						/**
4098
						 * Jetpack registration Error.
4099
						 *
4100
						 * @since 7.5.0
4101
						 *
4102
						 * @param string|int $error The error code.
4103
						 * @param \WP_Error $registered The error object.
4104
						 */
4105
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4106
						break;
4107
					}
4108
4109
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4110
4111
					/**
4112
					 * Jetpack registration Success.
4113
					 *
4114
					 * @since 7.5.0
4115
					 *
4116
					 * @param string $from 'from' GET parameter;
4117
					 */
4118
					do_action( 'jetpack_connection_register_success', $from );
4119
4120
					$url = $this->build_connect_url( true, $redirect, $from );
4121
4122
					if ( ! empty( $_GET['onboarding'] ) ) {
4123
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4124
					}
4125
4126
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4127
						$url = add_query_arg( 'auth_approved', 'true', $url );
4128
					}
4129
4130
					wp_redirect( $url );
4131
					exit;
4132
				case 'activate':
4133
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4134
						$error = 'cheatin';
4135
						break;
4136
					}
4137
4138
					$module = stripslashes( $_GET['module'] );
4139
					check_admin_referer( "jetpack_activate-$module" );
4140
					self::log( 'activate', $module );
4141
					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...
4142
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4143
					}
4144
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4145
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4146
					exit;
4147
				case 'activate_default_modules':
4148
					check_admin_referer( 'activate_default_modules' );
4149
					self::log( 'activate_default_modules' );
4150
					self::restate();
4151
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4152
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4153
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4154
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4155
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4156
					exit;
4157 View Code Duplication
				case 'disconnect':
4158
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4159
						$error = 'cheatin';
4160
						break;
4161
					}
4162
4163
					check_admin_referer( 'jetpack-disconnect' );
4164
					self::log( 'disconnect' );
4165
					self::disconnect();
4166
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4167
					exit;
4168 View Code Duplication
				case 'reconnect':
4169
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4170
						$error = 'cheatin';
4171
						break;
4172
					}
4173
4174
					check_admin_referer( 'jetpack-reconnect' );
4175
					self::log( 'reconnect' );
4176
					self::disconnect();
4177
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4178
					exit;
4179 View Code Duplication
				case 'deactivate':
4180
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4181
						$error = 'cheatin';
4182
						break;
4183
					}
4184
4185
					$modules = stripslashes( $_GET['module'] );
4186
					check_admin_referer( "jetpack_deactivate-$modules" );
4187
					foreach ( explode( ',', $modules ) as $module ) {
4188
						self::log( 'deactivate', $module );
4189
						self::deactivate_module( $module );
4190
						self::state( 'message', 'module_deactivated' );
4191
					}
4192
					self::state( 'module', $modules );
4193
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4194
					exit;
4195
				case 'unlink':
4196
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4197
					check_admin_referer( 'jetpack-unlink' );
4198
					self::log( 'unlink' );
4199
					$this->connection_manager->disconnect_user();
4200
					self::state( 'message', 'unlinked' );
4201
					if ( 'sub-unlink' == $redirect ) {
4202
						wp_safe_redirect( admin_url() );
4203
					} else {
4204
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4205
					}
4206
					exit;
4207
				case 'onboard':
4208
					if ( ! current_user_can( 'manage_options' ) ) {
4209
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4210
					} else {
4211
						self::create_onboarding_token();
4212
						$url = $this->build_connect_url( true );
4213
4214
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4215
							$url = add_query_arg( 'onboarding', $token, $url );
4216
						}
4217
4218
						$calypso_env = $this->get_calypso_env();
4219
						if ( ! empty( $calypso_env ) ) {
4220
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4221
						}
4222
4223
						wp_redirect( $url );
4224
						exit;
4225
					}
4226
					exit;
4227
				default:
4228
					/**
4229
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4230
					 *
4231
					 * @since 2.6.0
4232
					 *
4233
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4234
					 */
4235
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4236
			}
4237
		}
4238
4239
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4240
			self::activate_new_modules( true );
4241
		}
4242
4243
		$message_code = self::state( 'message' );
4244
		if ( self::state( 'optin-manage' ) ) {
4245
			$activated_manage = $message_code;
4246
			$message_code     = 'jetpack-manage';
4247
		}
4248
4249
		switch ( $message_code ) {
4250
			case 'jetpack-manage':
4251
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4252
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4253
				$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>';
4254
				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...
4255
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4256
				}
4257
				break;
4258
4259
		}
4260
4261
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4262
4263
		if ( ! empty( $deactivated_plugins ) ) {
4264
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4265
			$deactivated_titles  = array();
4266
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4267
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4268
					continue;
4269
				}
4270
4271
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4272
			}
4273
4274
			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...
4275
				if ( $this->message ) {
4276
					$this->message .= "<br /><br />\n";
4277
				}
4278
4279
				$this->message .= wp_sprintf(
4280
					_n(
4281
						'Jetpack contains the most recent version of the old %l plugin.',
4282
						'Jetpack contains the most recent versions of the old %l plugins.',
4283
						count( $deactivated_titles ),
4284
						'jetpack'
4285
					),
4286
					$deactivated_titles
4287
				);
4288
4289
				$this->message .= "<br />\n";
4290
4291
				$this->message .= _n(
4292
					'The old version has been deactivated and can be removed from your site.',
4293
					'The old versions have been deactivated and can be removed from your site.',
4294
					count( $deactivated_titles ),
4295
					'jetpack'
4296
				);
4297
			}
4298
		}
4299
4300
		$this->privacy_checks = self::state( 'privacy_checks' );
4301
4302
		if ( $this->message || $this->error || $this->privacy_checks ) {
4303
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4304
		}
4305
4306
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4307
	}
4308
4309
	function admin_notices() {
4310
4311
		if ( $this->error ) {
4312
			?>
4313
<div id="message" class="jetpack-message jetpack-err">
4314
	<div class="squeezer">
4315
		<h2>
4316
			<?php
4317
			echo wp_kses(
4318
				$this->error,
4319
				array(
4320
					'a'      => array( 'href' => array() ),
4321
					'small'  => true,
4322
					'code'   => true,
4323
					'strong' => true,
4324
					'br'     => true,
4325
					'b'      => true,
4326
				)
4327
			);
4328
			?>
4329
			</h2>
4330
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4331
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4332
<?php	endif; ?>
4333
	</div>
4334
</div>
4335
			<?php
4336
		}
4337
4338
		if ( $this->message ) {
4339
			?>
4340
<div id="message" class="jetpack-message">
4341
	<div class="squeezer">
4342
		<h2>
4343
			<?php
4344
			echo wp_kses(
4345
				$this->message,
4346
				array(
4347
					'strong' => array(),
4348
					'a'      => array( 'href' => true ),
4349
					'br'     => true,
4350
				)
4351
			);
4352
			?>
4353
			</h2>
4354
	</div>
4355
</div>
4356
			<?php
4357
		}
4358
4359
		if ( $this->privacy_checks ) :
4360
			$module_names = $module_slugs = array();
4361
4362
			$privacy_checks = explode( ',', $this->privacy_checks );
4363
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4364
			foreach ( $privacy_checks as $module_slug ) {
4365
				$module = self::get_module( $module_slug );
4366
				if ( ! $module ) {
4367
					continue;
4368
				}
4369
4370
				$module_slugs[] = $module_slug;
4371
				$module_names[] = "<strong>{$module['name']}</strong>";
4372
			}
4373
4374
			$module_slugs = join( ',', $module_slugs );
4375
			?>
4376
<div id="message" class="jetpack-message jetpack-err">
4377
	<div class="squeezer">
4378
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4379
		<p>
4380
			<?php
4381
			echo wp_kses(
4382
				wptexturize(
4383
					wp_sprintf(
4384
						_nx(
4385
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4386
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4387
							count( $privacy_checks ),
4388
							'%l = list of Jetpack module/feature names',
4389
							'jetpack'
4390
						),
4391
						$module_names
4392
					)
4393
				),
4394
				array( 'strong' => true )
4395
			);
4396
4397
			echo "\n<br />\n";
4398
4399
			echo wp_kses(
4400
				sprintf(
4401
					_nx(
4402
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4403
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4404
						count( $privacy_checks ),
4405
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4406
						'jetpack'
4407
					),
4408
					wp_nonce_url(
4409
						self::admin_url(
4410
							array(
4411
								'page'   => 'jetpack',
4412
								'action' => 'deactivate',
4413
								'module' => urlencode( $module_slugs ),
4414
							)
4415
						),
4416
						"jetpack_deactivate-$module_slugs"
4417
					),
4418
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4419
				),
4420
				array(
4421
					'a' => array(
4422
						'href'  => true,
4423
						'title' => true,
4424
					),
4425
				)
4426
			);
4427
			?>
4428
		</p>
4429
	</div>
4430
</div>
4431
			<?php
4432
endif;
4433
	}
4434
4435
	/**
4436
	 * We can't always respond to a signed XML-RPC request with a
4437
	 * helpful error message. In some circumstances, doing so could
4438
	 * leak information.
4439
	 *
4440
	 * Instead, track that the error occurred via a Jetpack_Option,
4441
	 * and send that data back in the heartbeat.
4442
	 * All this does is increment a number, but it's enough to find
4443
	 * trends.
4444
	 *
4445
	 * @param WP_Error $xmlrpc_error The error produced during
4446
	 *                               signature validation.
4447
	 */
4448
	function track_xmlrpc_error( $xmlrpc_error ) {
4449
		$code = is_wp_error( $xmlrpc_error )
4450
			? $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...
4451
			: 'should-not-happen';
4452
4453
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4454
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4455
			// No need to update the option if we already have
4456
			// this code stored.
4457
			return;
4458
		}
4459
		$xmlrpc_errors[ $code ] = true;
4460
4461
		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...
4462
	}
4463
4464
	/**
4465
	 * Initialize the jetpack stats instance only when needed
4466
	 *
4467
	 * @return void
4468
	 */
4469
	private function initialize_stats() {
4470
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4471
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4472
		}
4473
	}
4474
4475
	/**
4476
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4477
	 */
4478
	function stat( $group, $detail ) {
4479
		$this->initialize_stats();
4480
		$this->a8c_mc_stats_instance->add( $group, $detail );
4481
4482
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4483
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4484
	}
4485
4486
	/**
4487
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4488
	 */
4489
	function do_stats( $method = '' ) {
4490
		$this->initialize_stats();
4491
		if ( 'server_side' === $method ) {
4492
			$this->a8c_mc_stats_instance->do_server_side_stats();
4493
		} else {
4494
			$this->a8c_mc_stats_instance->do_stats();
4495
		}
4496
4497
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4498
		$this->stats = array();
4499
	}
4500
4501
	/**
4502
	 * Runs stats code for a one-off, server-side.
4503
	 *
4504
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4505
	 *
4506
	 * @return bool If it worked.
4507
	 */
4508
	static function do_server_side_stat( $args ) {
4509
		$url                   = self::build_stats_url( $args );
4510
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4511
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4512
	}
4513
4514
	/**
4515
	 * Builds the stats url.
4516
	 *
4517
	 * @param $args array|string The arguments to append to the URL.
4518
	 *
4519
	 * @return string The URL to be pinged.
4520
	 */
4521
	static function build_stats_url( $args ) {
4522
4523
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4524
		return $a8c_mc_stats_instance->build_stats_url( $args );
4525
4526
	}
4527
4528
	/**
4529
	 * Builds a URL to the Jetpack connection auth page
4530
	 *
4531
	 * @since 3.9.5
4532
	 *
4533
	 * @param bool        $raw If true, URL will not be escaped.
4534
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4535
	 *                              If string, will be a custom redirect.
4536
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4537
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4538
	 *
4539
	 * @return string Connect URL
4540
	 */
4541
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4542
		$site_id    = Jetpack_Options::get_option( 'id' );
4543
		$blog_token = ( new Tokens() )->get_access_token();
4544
4545
		if ( $register || ! $blog_token || ! $site_id ) {
4546
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4547
4548
			if ( ! empty( $redirect ) ) {
4549
				$url = add_query_arg(
4550
					'redirect',
4551
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4552
					$url
4553
				);
4554
			}
4555
4556
			if ( is_network_admin() ) {
4557
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4558
			}
4559
4560
			$calypso_env = self::get_calypso_env();
4561
4562
			if ( ! empty( $calypso_env ) ) {
4563
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4564
			}
4565
		} else {
4566
4567
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4568
			// because otherwise this logic can get us in to a loop.
4569
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4570
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4571
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4572
4573
				$response = Client::wpcom_json_api_request_as_blog(
4574
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4575
					'1.1'
4576
				);
4577
4578
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4579
4580
					// Generating a register URL instead to refresh the existing token
4581
					return $this->build_connect_url( $raw, $redirect, $from, true );
4582
				}
4583
			}
4584
4585
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4541 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...
4586
		}
4587
4588
		if ( $from ) {
4589
			$url = add_query_arg( 'from', $from, $url );
4590
		}
4591
4592
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4593
		/**
4594
		 * Filter the URL used when connecting a user to a WordPress.com account.
4595
		 *
4596
		 * @since 8.1.0
4597
		 *
4598
		 * @param string $url Connection URL.
4599
		 * @param bool   $raw If true, URL will not be escaped.
4600
		 */
4601
		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...
4602
	}
4603
4604
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4605
4606
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4607
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4608
4609
		if ( $iframe ) {
4610
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4611
		}
4612
4613
		$c8n = self::connection();
4614
		$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...
4615
4616
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4617
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4618
4619
		if ( $iframe ) {
4620
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4621
		}
4622
4623
		/**
4624
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4625
		 *
4626
		 * @since 8.9.0
4627
		 *
4628
		 * @param string $url Connection URL.
4629
		 */
4630
		return apply_filters( 'jetpack_build_authorize_url', $url );
4631
	}
4632
4633
	/**
4634
	 * Filters the connection URL parameter array.
4635
	 *
4636
	 * @param array $args default URL parameters used by the package.
4637
	 * @return array the modified URL arguments array.
4638
	 */
4639
	public static function filter_connect_request_body( $args ) {
4640
		if (
4641
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4642
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4643
		) {
4644
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4645
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4646
				? $gp_locale->slug
4647
				: '';
4648
		}
4649
4650
		$tracking        = new Tracking();
4651
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4652
4653
		$args = array_merge(
4654
			$args,
4655
			array(
4656
				'_ui' => $tracks_identity['_ui'],
4657
				'_ut' => $tracks_identity['_ut'],
4658
			)
4659
		);
4660
4661
		$calypso_env = self::get_calypso_env();
4662
4663
		if ( ! empty( $calypso_env ) ) {
4664
			$args['calypso_env'] = $calypso_env;
4665
		}
4666
4667
		return $args;
4668
	}
4669
4670
	/**
4671
	 * Filters the URL that will process the connection data. It can be different from the URL
4672
	 * that we send the user to after everything is done.
4673
	 *
4674
	 * @param String $processing_url the default redirect URL used by the package.
4675
	 * @return String the modified URL.
4676
	 *
4677
	 * @deprecated since Jetpack 9.5.0
4678
	 */
4679
	public static function filter_connect_processing_url( $processing_url ) {
4680
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4681
4682
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4683
		return $processing_url;
4684
	}
4685
4686
	/**
4687
	 * Filters the redirection URL that is used for connect requests. The redirect
4688
	 * URL should return the user back to the Jetpack console.
4689
	 *
4690
	 * @param String $redirect the default redirect URL used by the package.
4691
	 * @return String the modified URL.
4692
	 */
4693
	public static function filter_connect_redirect_url( $redirect ) {
4694
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4695
		$redirect           = $redirect
4696
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4697
			: $jetpack_admin_page;
4698
4699
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4700
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4701
		}
4702
4703
		return $redirect;
4704
	}
4705
4706
	/**
4707
	 * This action fires at the beginning of the Manager::authorize method.
4708
	 */
4709
	public static function authorize_starting() {
4710
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4711
		// Checking if site has been active/connected previously before recording unique connection.
4712
		if ( ! $jetpack_unique_connection ) {
4713
			// jetpack_unique_connection option has never been set.
4714
			$jetpack_unique_connection = array(
4715
				'connected'    => 0,
4716
				'disconnected' => 0,
4717
				'version'      => '3.6.1',
4718
			);
4719
4720
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4721
4722
			// Track unique connection.
4723
			$jetpack = self::init();
4724
4725
			$jetpack->stat( 'connections', 'unique-connection' );
4726
			$jetpack->do_stats( 'server_side' );
4727
		}
4728
4729
		// Increment number of times connected.
4730
		$jetpack_unique_connection['connected'] += 1;
4731
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4732
	}
4733
4734
	/**
4735
	 * This action fires when the site is registered (connected at a site level).
4736
	 */
4737
	public function handle_unique_registrations_stats() {
4738
		$jetpack_unique_registrations = Jetpack_Options::get_option( 'unique_registrations' );
4739
		// Checking if site has been registered previously before recording unique connection.
4740
		if ( ! $jetpack_unique_registrations ) {
4741
4742
			$jetpack_unique_registrations = 0;
4743
4744
			$this->stat( 'connections', 'unique-registrations' );
4745
			$this->do_stats( 'server_side' );
4746
		}
4747
4748
		// Increment number of times connected.
4749
		$jetpack_unique_registrations ++;
4750
		Jetpack_Options::update_option( 'unique_registrations', $jetpack_unique_registrations );
4751
	}
4752
4753
	/**
4754
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4755
	 * linked.
4756
	 */
4757
	public static function authorize_ending_linked() {
4758
		// Don't activate anything since we are just connecting a user.
4759
		self::state( 'message', 'linked' );
4760
	}
4761
4762
	/**
4763
	 * This action fires at the end of the Manager::authorize method when the master user is
4764
	 * authorized.
4765
	 *
4766
	 * @param array $data The request data.
4767
	 */
4768
	public static function authorize_ending_authorized( $data ) {
4769
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4770
		self::invalidate_onboarding_token();
4771
4772
		// If redirect_uri is SSO, ensure SSO module is enabled.
4773
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4774
4775
		/** This filter is documented in class.jetpack-cli.php */
4776
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4777
4778
		$activate_sso = (
4779
			isset( $redirect_options['action'] ) &&
4780
			'jetpack-sso' === $redirect_options['action'] &&
4781
			$jetpack_start_enable_sso
4782
		);
4783
4784
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4785
4786
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4787
	}
4788
4789
	/**
4790
	 * Fires on the jetpack_site_registered hook and acitvates default modules
4791
	 */
4792
	public static function activate_default_modules_on_site_register() {
4793
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
4794
		if ( $active_modules ) {
4795
			self::delete_active_modules();
4796
4797
			// 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.
4798
			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...
4799
		} else {
4800
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
4801
			self::activate_default_modules( false, false, array(), false, null, null, false );
4802
		}
4803
4804
		// Since this is a fresh connection, be sure to clear out IDC options.
4805
		Identity_Crisis::clear_all_idc_options();
4806
	}
4807
4808
	/**
4809
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
4810
	 * reconnect process is completed.
4811
	 * Note that this currently only happens when we don't need the user to re-authorize
4812
	 * their WP.com account, eg in cases where we are restoring a connection with
4813
	 * unhealthy blog token.
4814
	 */
4815
	public static function reconnection_completed() {
4816
		self::state( 'message', 'reconnection_completed' );
4817
	}
4818
4819 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4820
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4821
4822
		if ( $activation_source_name ) {
4823
			$args['_as'] = urlencode( $activation_source_name );
4824
		}
4825
4826
		if ( $activation_source_keyword ) {
4827
			$args['_ak'] = urlencode( $activation_source_keyword );
4828
		}
4829
	}
4830
4831
	function build_reconnect_url( $raw = false ) {
4832
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4833
		return $raw ? $url : esc_url( $url );
4834
	}
4835
4836
	public static function admin_url( $args = null ) {
4837
		$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...
4838
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4839
		return $url;
4840
	}
4841
4842
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4843
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4844
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4845
	}
4846
4847
	function dismiss_jetpack_notice() {
4848
4849
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4850
			return;
4851
		}
4852
4853
		switch ( $_GET['jetpack-notice'] ) {
4854
			case 'dismiss':
4855
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4856
4857
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4858
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4859
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4860
				}
4861
				break;
4862
		}
4863
	}
4864
4865
	public static function sort_modules( $a, $b ) {
4866
		if ( $a['sort'] == $b['sort'] ) {
4867
			return 0;
4868
		}
4869
4870
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4871
	}
4872
4873
	function ajax_recheck_ssl() {
4874
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4875
		$result = self::permit_ssl( true );
4876
		wp_send_json(
4877
			array(
4878
				'enabled' => $result,
4879
				'message' => get_transient( 'jetpack_https_test_message' ),
4880
			)
4881
		);
4882
	}
4883
4884
	/* Client API */
4885
4886
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4887
		// Default to a blog token.
4888
		$token_type = 'blog';
4889
4890
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4891
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4892
			if ( ! empty( $_GET['onboarding'] ) ) {
4893
				$jpo = $_GET;
4894
			} else {
4895
				$jpo = json_decode( $request_data, true );
4896
			}
4897
4898
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4899
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4900
4901
			if (
4902
				isset( $jpo_user )
4903
				&& isset( $jpo_token )
4904
				&& is_email( $jpo_user )
4905
				&& ctype_alnum( $jpo_token )
4906
				&& isset( $_GET['rest_route'] )
4907
				&& self::validate_onboarding_token_action(
4908
					$jpo_token,
4909
					$_GET['rest_route']
4910
				)
4911
			) {
4912
				$jp_user = get_user_by( 'email', $jpo_user );
4913
				if ( is_a( $jp_user, 'WP_User' ) ) {
4914
					wp_set_current_user( $jp_user->ID );
4915
					$user_can = is_multisite()
4916
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4917
						: current_user_can( 'manage_options' );
4918
					if ( $user_can ) {
4919
						$token_type              = 'user';
4920
						$token->external_user_id = $jp_user->ID;
4921
					}
4922
				}
4923
			}
4924
4925
			$token_data['type']    = $token_type;
4926
			$token_data['user_id'] = $token->external_user_id;
4927
		}
4928
4929
		return $token_data;
4930
	}
4931
4932
	/**
4933
	 * Create a random secret for validating onboarding payload
4934
	 *
4935
	 * @return string Secret token
4936
	 */
4937
	public static function create_onboarding_token() {
4938
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4939
			$token = wp_generate_password( 32, false );
4940
			Jetpack_Options::update_option( 'onboarding', $token );
4941
		}
4942
4943
		return $token;
4944
	}
4945
4946
	/**
4947
	 * Remove the onboarding token
4948
	 *
4949
	 * @return bool True on success, false on failure
4950
	 */
4951
	public static function invalidate_onboarding_token() {
4952
		return Jetpack_Options::delete_option( 'onboarding' );
4953
	}
4954
4955
	/**
4956
	 * Validate an onboarding token for a specific action
4957
	 *
4958
	 * @return boolean True if token/action pair is accepted, false if not
4959
	 */
4960
	public static function validate_onboarding_token_action( $token, $action ) {
4961
		// Compare tokens, bail if tokens do not match
4962
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4963
			return false;
4964
		}
4965
4966
		// List of valid actions we can take
4967
		$valid_actions = array(
4968
			'/jetpack/v4/settings',
4969
		);
4970
4971
		// Only allow valid actions.
4972
		if ( ! in_array( $action, $valid_actions ) ) {
4973
			return false;
4974
		}
4975
4976
		return true;
4977
	}
4978
4979
	/**
4980
	 * Checks to see if the URL is using SSL to connect with Jetpack
4981
	 *
4982
	 * @since 2.3.3
4983
	 * @return boolean
4984
	 */
4985
	public static function permit_ssl( $force_recheck = false ) {
4986
		// Do some fancy tests to see if ssl is being supported
4987
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4988
			$message = '';
4989
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4990
				$ssl = 0;
4991
			} else {
4992
				$ssl = 1;
4993
4994
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4995
					$ssl     = 0;
4996
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
4997
				} else {
4998
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4999
					if ( is_wp_error( $response ) ) {
5000
						$ssl     = 0;
5001
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5002
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5003
						$ssl     = 0;
5004
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5005
					}
5006
				}
5007
			}
5008
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5009
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5010
		}
5011
5012
		return (bool) $ssl;
5013
	}
5014
5015
	/*
5016
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5017
	 */
5018
	public function alert_auto_ssl_fail() {
5019
		if ( ! current_user_can( 'manage_options' ) ) {
5020
			return;
5021
		}
5022
5023
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5024
		?>
5025
5026
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5027
			<div class="jp-banner__content">
5028
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5029
				<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>
5030
				<p>
5031
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5032
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5033
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5034
				</p>
5035
				<p>
5036
					<?php
5037
					printf(
5038
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5039
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5040
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5041
					);
5042
					?>
5043
				</p>
5044
			</div>
5045
		</div>
5046
		<style>
5047
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5048
		</style>
5049
		<script type="text/javascript">
5050
			jQuery( document ).ready( function( $ ) {
5051
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5052
					var $this = $( this );
5053
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5054
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5055
					e.preventDefault();
5056
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5057
					$.post( ajaxurl, data )
5058
					  .done( function( response ) {
5059
						  if ( response.enabled ) {
5060
							  $( '#jetpack-ssl-warning' ).hide();
5061
						  } else {
5062
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5063
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5064
						  }
5065
					  }.bind( $this ) );
5066
				} );
5067
			} );
5068
		</script>
5069
5070
		<?php
5071
	}
5072
5073
	/**
5074
	 * Returns the connection manager object.
5075
	 *
5076
	 * @return Automattic\Jetpack\Connection\Manager
5077
	 */
5078
	public static function connection() {
5079
		$jetpack = static::init();
5080
5081
		// If the connection manager hasn't been instantiated, do that now.
5082
		if ( ! $jetpack->connection_manager ) {
5083
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5084
		}
5085
5086
		return $jetpack->connection_manager;
5087
	}
5088
5089
	/**
5090
	 * Creates two secret tokens and the end of life timestamp for them.
5091
	 *
5092
	 * Note these tokens are unique per call, NOT static per site for connecting.
5093
	 *
5094
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5095
	 *
5096
	 * @since 2.6
5097
	 * @param String  $action  The action name.
5098
	 * @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...
5099
	 * @param Integer $exp     Expiration time in seconds.
5100
	 * @return array
5101
	 */
5102
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5103
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5104
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5105
	}
5106
5107
	public static function get_secrets( $action, $user_id ) {
5108
		$secrets = ( new Secrets() )->get( $action, $user_id );
5109
5110
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5111
			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...
5112
		}
5113
5114
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5115
			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...
5116
		}
5117
5118
		return $secrets;
5119
	}
5120
5121
	/**
5122
	 * Builds the timeout limit for queries talking with the wpcom servers.
5123
	 *
5124
	 * Based on local php max_execution_time in php.ini
5125
	 *
5126
	 * @since 5.4
5127
	 * @return int
5128
	 **/
5129
	public static function get_max_execution_time() {
5130
		$timeout = (int) ini_get( 'max_execution_time' );
5131
5132
		// Ensure exec time set in php.ini
5133
		if ( ! $timeout ) {
5134
			$timeout = 30;
5135
		}
5136
		return $timeout;
5137
	}
5138
5139
	/**
5140
	 * Sets a minimum request timeout, and returns the current timeout
5141
	 *
5142
	 * @since 5.4
5143
	 **/
5144 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5145
		$timeout = self::get_max_execution_time();
5146
		if ( $timeout < $min_timeout ) {
5147
			$timeout = $min_timeout;
5148
			set_time_limit( $timeout );
5149
		}
5150
		return $timeout;
5151
	}
5152
5153
	/**
5154
	 * @deprecated since Jetpack 9.7.0
5155
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
5156
	 *
5157
	 * @return bool|WP_Error
5158
	 */
5159
	public static function register() {
5160
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
5161
		return static::connection()->try_registration( false );
5162
	}
5163
5164
	/**
5165
	 * Filters the registration request body to include tracking properties.
5166
	 *
5167
	 * @deprecated since Jetpack 9.7.0
5168
	 * @see Automattic\Jetpack\Connection\Utils::filter_register_request_body()
5169
	 *
5170
	 * @param array $properties
5171
	 * @return array amended properties.
5172
	 */
5173
	public static function filter_register_request_body( $properties ) {
5174
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Utils::filter_register_request_body' );
5175
		return Connection_Utils::filter_register_request_body( $properties );
5176
	}
5177
5178
	/**
5179
	 * Filters the token request body to include tracking properties.
5180
	 *
5181
	 * @param array $properties
5182
	 * @return array amended properties.
5183
	 */
5184 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5185
		$tracking        = new Tracking();
5186
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5187
5188
		return array_merge(
5189
			$properties,
5190
			array(
5191
				'_ui' => $tracks_identity['_ui'],
5192
				'_ut' => $tracks_identity['_ut'],
5193
			)
5194
		);
5195
	}
5196
5197
	/**
5198
	 * If the db version is showing something other that what we've got now, bump it to current.
5199
	 *
5200
	 * @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...
5201
	 */
5202
	public static function maybe_set_version_option() {
5203
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5204
		if ( JETPACK__VERSION != $version ) {
5205
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5206
5207
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5208
				/** This action is documented in class.jetpack.php */
5209
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5210
			}
5211
5212
			return true;
5213
		}
5214
		return false;
5215
	}
5216
5217
	/* Client Server API */
5218
5219
	/**
5220
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5221
	 * SET: state( $key, $value );
5222
	 * GET: $value = state( $key );
5223
	 *
5224
	 * @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...
5225
	 * @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...
5226
	 * @param bool   $restate private
5227
	 */
5228
	public static function state( $key = null, $value = null, $restate = false ) {
5229
		static $state = array();
5230
		static $path, $domain;
5231
		if ( ! isset( $path ) ) {
5232
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5233
			$admin_url = self::admin_url();
5234
			$bits      = wp_parse_url( $admin_url );
5235
5236
			if ( is_array( $bits ) ) {
5237
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5238
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5239
			} else {
5240
				$path = $domain = null;
5241
			}
5242
		}
5243
5244
		// Extract state from cookies and delete cookies
5245
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5246
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5247
			unset( $_COOKIE['jetpackState'] );
5248
			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...
5249
				if ( strlen( $v ) ) {
5250
					$state[ $k ] = $v;
5251
				}
5252
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5253
			}
5254
		}
5255
5256
		if ( $restate ) {
5257
			foreach ( $state as $k => $v ) {
5258
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5259
			}
5260
			return;
5261
		}
5262
5263
		// Get a state variable.
5264
		if ( isset( $key ) && ! isset( $value ) ) {
5265
			if ( array_key_exists( $key, $state ) ) {
5266
				return $state[ $key ];
5267
			}
5268
			return null;
5269
		}
5270
5271
		// Set a state variable.
5272
		if ( isset( $key ) && isset( $value ) ) {
5273
			if ( is_array( $value ) && isset( $value[0] ) ) {
5274
				$value = $value[0];
5275
			}
5276
			$state[ $key ] = $value;
5277
			if ( ! headers_sent() ) {
5278
				if ( self::should_set_cookie( $key ) ) {
5279
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5280
				}
5281
			}
5282
		}
5283
	}
5284
5285
	public static function restate() {
5286
		self::state( null, null, true );
5287
	}
5288
5289
	/**
5290
	 * Determines whether the jetpackState[$key] value should be added to the
5291
	 * cookie.
5292
	 *
5293
	 * @param string $key The state key.
5294
	 *
5295
	 * @return boolean Whether the value should be added to the cookie.
5296
	 */
5297
	public static function should_set_cookie( $key ) {
5298
		global $current_screen;
5299
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5300
5301
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5302
			return false;
5303
		}
5304
5305
		return true;
5306
	}
5307
5308
	public static function check_privacy( $file ) {
5309
		static $is_site_publicly_accessible = null;
5310
5311
		if ( is_null( $is_site_publicly_accessible ) ) {
5312
			$is_site_publicly_accessible = false;
5313
5314
			$rpc = new Jetpack_IXR_Client();
5315
5316
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5317
			if ( $success ) {
5318
				$response = $rpc->getResponse();
5319
				if ( $response ) {
5320
					$is_site_publicly_accessible = true;
5321
				}
5322
			}
5323
5324
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5325
		}
5326
5327
		if ( $is_site_publicly_accessible ) {
5328
			return;
5329
		}
5330
5331
		$module_slug = self::get_module_slug( $file );
5332
5333
		$privacy_checks = self::state( 'privacy_checks' );
5334
		if ( ! $privacy_checks ) {
5335
			$privacy_checks = $module_slug;
5336
		} else {
5337
			$privacy_checks .= ",$module_slug";
5338
		}
5339
5340
		self::state( 'privacy_checks', $privacy_checks );
5341
	}
5342
5343
	/**
5344
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5345
	 *
5346
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5347
	 *
5348
	 * @param string $url WordPress.com static resource URL.
5349
	 */
5350
	public static function staticize_subdomain( $url ) {
5351
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5352
		return Assets::staticize_subdomain( $url );
5353
	}
5354
5355
	/* JSON API Authorization */
5356
5357
	/**
5358
	 * Handles the login action for Authorizing the JSON API
5359
	 */
5360
	function login_form_json_api_authorization() {
5361
		$this->verify_json_api_authorization_request();
5362
5363
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5364
5365
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5366
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5367
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5368
	}
5369
5370
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5371
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5372
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5373
			return $url;
5374
		}
5375
5376
		$parsed_url = wp_parse_url( $url );
5377
		$url        = strtok( $url, '?' );
5378
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5379
		if ( ! empty( $parsed_url['query'] ) ) {
5380
			$url .= "&{$parsed_url['query']}";
5381
		}
5382
5383
		return $url;
5384
	}
5385
5386
	// Make sure the POSTed request is handled by the same action
5387
	function preserve_action_in_login_form_for_json_api_authorization() {
5388
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5389
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5390
	}
5391
5392
	// If someone logs in to approve API access, store the Access Code in usermeta
5393
	function store_json_api_authorization_token( $user_login, $user ) {
5394
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5395
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5396
		$token = wp_generate_password( 32, false );
5397
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5398
	}
5399
5400
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5401
	function allow_wpcom_public_api_domain( $domains ) {
5402
		$domains[] = 'public-api.wordpress.com';
5403
		return $domains;
5404
	}
5405
5406
	static function is_redirect_encoded( $redirect_url ) {
5407
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5408
	}
5409
5410
	// Add all wordpress.com environments to the safe redirect allowed list.
5411
	function allow_wpcom_environments( $domains ) {
5412
		$domains[] = 'wordpress.com';
5413
		$domains[] = 'wpcalypso.wordpress.com';
5414
		$domains[] = 'horizon.wordpress.com';
5415
		$domains[] = 'calypso.localhost';
5416
		return $domains;
5417
	}
5418
5419
	// Add the Access Code details to the public-api.wordpress.com redirect
5420
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5421
		return add_query_arg(
5422
			urlencode_deep(
5423
				array(
5424
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5425
					'jetpack-user-id' => (int) $user->ID,
5426
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5427
				)
5428
			),
5429
			$redirect_to
5430
		);
5431
	}
5432
5433
	/**
5434
	 * Verifies the request by checking the signature
5435
	 *
5436
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5437
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5438
	 *
5439
	 * @param null|array $environment
5440
	 */
5441
	function verify_json_api_authorization_request( $environment = null ) {
5442
		$environment = is_null( $environment )
5443
			? $_REQUEST
5444
			: $environment;
5445
5446
		list( $env_token,, $env_user_id ) = explode( ':', $environment['token'] );
5447
		$token                            = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
5448
		if ( ! $token || empty( $token->secret ) ) {
5449
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5450
		}
5451
5452
		$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' );
5453
5454
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5455
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5456
			/**
5457
			 * Jetpack authorisation request Error.
5458
			 *
5459
			 * @since 7.5.0
5460
			 */
5461
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5462
			$die_error = sprintf(
5463
				/* translators: %s is a URL */
5464
				__( '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' ),
5465
				Redirect::get_url( 'jetpack-support-double-encoding' )
5466
			);
5467
		}
5468
5469
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5470
5471
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5472
			$signature = $jetpack_signature->sign_request(
5473
				$environment['token'],
5474
				$environment['timestamp'],
5475
				$environment['nonce'],
5476
				'',
5477
				'GET',
5478
				$environment['jetpack_json_api_original_query'],
5479
				null,
5480
				true
5481
			);
5482
		} else {
5483
			$signature = $jetpack_signature->sign_current_request(
5484
				array(
5485
					'body'   => null,
5486
					'method' => 'GET',
5487
				)
5488
			);
5489
		}
5490
5491
		if ( ! $signature ) {
5492
			wp_die( $die_error );
5493
		} elseif ( is_wp_error( $signature ) ) {
5494
			wp_die( $die_error );
5495
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5496
			if ( is_ssl() ) {
5497
				// 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
5498
				$signature = $jetpack_signature->sign_current_request(
5499
					array(
5500
						'scheme' => 'http',
5501
						'body'   => null,
5502
						'method' => 'GET',
5503
					)
5504
				);
5505
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5506
					wp_die( $die_error );
5507
				}
5508
			} else {
5509
				wp_die( $die_error );
5510
			}
5511
		}
5512
5513
		$timestamp = (int) $environment['timestamp'];
5514
		$nonce     = stripslashes( (string) $environment['nonce'] );
5515
5516
		if ( ! $this->connection_manager ) {
5517
			$this->connection_manager = new Connection_Manager();
5518
		}
5519
5520
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
5521
			// De-nonce the nonce, at least for 5 minutes.
5522
			// 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)
5523
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5524
			if ( $old_nonce_time < time() - 300 ) {
5525
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5526
			}
5527
		}
5528
5529
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5530
		$data_filters = array(
5531
			'state'        => 'opaque',
5532
			'client_id'    => 'int',
5533
			'client_title' => 'string',
5534
			'client_image' => 'url',
5535
		);
5536
5537
		foreach ( $data_filters as $key => $sanitation ) {
5538
			if ( ! isset( $data->$key ) ) {
5539
				wp_die( $die_error );
5540
			}
5541
5542
			switch ( $sanitation ) {
5543
				case 'int':
5544
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
5545
					break;
5546
				case 'opaque':
5547
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
5548
					break;
5549
				case 'string':
5550
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
5551
					break;
5552
				case 'url':
5553
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
5554
					break;
5555
			}
5556
		}
5557
5558
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5559
			wp_die( $die_error );
5560
		}
5561
	}
5562
5563
	function login_message_json_api_authorization( $message ) {
5564
		return '<p class="message">' . sprintf(
5565
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
5566
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5567
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5568
	}
5569
5570
	/**
5571
	 * Get $content_width, but with a <s>twist</s> filter.
5572
	 */
5573
	public static function get_content_width() {
5574
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5575
			? $GLOBALS['content_width']
5576
			: false;
5577
		/**
5578
		 * Filter the Content Width value.
5579
		 *
5580
		 * @since 2.2.3
5581
		 *
5582
		 * @param string $content_width Content Width value.
5583
		 */
5584
		return apply_filters( 'jetpack_content_width', $content_width );
5585
	}
5586
5587
	/**
5588
	 * Pings the WordPress.com Mirror Site for the specified options.
5589
	 *
5590
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5591
	 *
5592
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5593
	 */
5594
	public function get_cloud_site_options( $option_names ) {
5595
		$option_names = array_filter( (array) $option_names, 'is_string' );
5596
5597
		$xml = new Jetpack_IXR_Client();
5598
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5599
		if ( $xml->isError() ) {
5600
			return array(
5601
				'error_code' => $xml->getErrorCode(),
5602
				'error_msg'  => $xml->getErrorMessage(),
5603
			);
5604
		}
5605
		$cloud_site_options = $xml->getResponse();
5606
5607
		return $cloud_site_options;
5608
	}
5609
5610
	/**
5611
	 * Checks if the site is currently in an identity crisis.
5612
	 *
5613
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5614
	 */
5615
	public static function check_identity_crisis() {
5616
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() || ! Identity_Crisis::validate_sync_error_idc_option() ) {
5617
			return false;
5618
		}
5619
5620
		return Jetpack_Options::get_option( 'sync_error_idc' );
5621
	}
5622
5623
	/**
5624
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5625
	 *
5626
	 * @since 4.4.0
5627
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5628
	 *
5629
	 * @return bool
5630
	 */
5631
	public static function validate_sync_error_idc_option() {
5632
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::validate_sync_error_idc_option' );
5633
		return Identity_Crisis::validate_sync_error_idc_option();
5634
	}
5635
5636
	/**
5637
	 * Normalizes a url by doing three things:
5638
	 *  - Strips protocol
5639
	 *  - Strips www
5640
	 *  - Adds a trailing slash
5641
	 *
5642
	 * @since 4.4.0
5643
	 * @param string $url
5644
	 * @return WP_Error|string
5645
	 */
5646 View Code Duplication
	public static function normalize_url_protocol_agnostic( $url ) {
5647
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5648
		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...
5649
			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...
5650
		}
5651
5652
		// Strip www and protocols
5653
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5654
		return $url;
5655
	}
5656
5657
	/**
5658
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5659
	 *
5660
	 * @since 4.4.0
5661
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5662
	 *
5663
	 * @param array $response
5664
	 * @return array Array of the local urls, wpcom urls, and error code
5665
	 */
5666
	public static function get_sync_error_idc_option( $response = array() ) {
5667
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::get_sync_error_idc_option' );
5668
		return Identity_Crisis::get_sync_error_idc_option( $response );
5669
	}
5670
5671
	/**
5672
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5673
	 * If set to true, the site will be put into staging mode.
5674
	 *
5675
	 * @since 4.3.2
5676
	 * @return bool
5677
	 */
5678
	public static function sync_idc_optin() {
5679
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::sync_idc_optin' );
5680
		return Identity_Crisis::sync_idc_optin();
5681
	}
5682
5683
	/**
5684
	 * Maybe Use a .min.css stylesheet, maybe not.
5685
	 *
5686
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5687
	 */
5688
	public static function maybe_min_asset( $url, $path, $plugin ) {
5689
		// Short out on things trying to find actual paths.
5690
		if ( ! $path || empty( $plugin ) ) {
5691
			return $url;
5692
		}
5693
5694
		$path = ltrim( $path, '/' );
5695
5696
		// Strip out the abspath.
5697
		$base = dirname( plugin_basename( $plugin ) );
5698
5699
		// Short out on non-Jetpack assets.
5700
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5701
			return $url;
5702
		}
5703
5704
		// File name parsing.
5705
		$file              = "{$base}/{$path}";
5706
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5707
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5708
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5709
		$extension         = array_shift( $file_name_parts_r );
5710
5711
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5712
			// Already pointing at the minified version.
5713
			if ( 'min' === $file_name_parts_r[0] ) {
5714
				return $url;
5715
			}
5716
5717
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5718
			if ( file_exists( $min_full_path ) ) {
5719
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5720
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
5721
				if ( 'css' === $extension ) {
5722
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
5723
					self::$min_assets[ $key ] = $path;
5724
				}
5725
			}
5726
		}
5727
5728
		return $url;
5729
	}
5730
5731
	/**
5732
	 * If the asset is minified, let's flag .min as the suffix.
5733
	 *
5734
	 * Attached to `style_loader_src` filter.
5735
	 *
5736
	 * @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...
5737
	 * @param string $handle The registered handle of the script in question.
5738
	 * @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...
5739
	 */
5740
	public static function set_suffix_on_min( $src, $handle ) {
5741
		if ( false === strpos( $src, '.min.css' ) ) {
5742
			return $src;
5743
		}
5744
5745
		if ( ! empty( self::$min_assets ) ) {
5746
			foreach ( self::$min_assets as $file => $path ) {
5747
				if ( false !== strpos( $src, $file ) ) {
5748
					wp_style_add_data( $handle, 'suffix', '.min' );
5749
					return $src;
5750
				}
5751
			}
5752
		}
5753
5754
		return $src;
5755
	}
5756
5757
	/**
5758
	 * Maybe inlines a stylesheet.
5759
	 *
5760
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5761
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5762
	 *
5763
	 * Attached to `style_loader_tag` filter.
5764
	 *
5765
	 * @param string $tag The tag that would link to the external asset.
5766
	 * @param string $handle The registered handle of the script in question.
5767
	 *
5768
	 * @return string
5769
	 */
5770
	public static function maybe_inline_style( $tag, $handle ) {
5771
		global $wp_styles;
5772
		$item = $wp_styles->registered[ $handle ];
5773
5774
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5775
			return $tag;
5776
		}
5777
5778
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5779
			$href = $matches[1];
5780
			// Strip off query string
5781
			if ( $pos = strpos( $href, '?' ) ) {
5782
				$href = substr( $href, 0, $pos );
5783
			}
5784
			// Strip off fragment
5785
			if ( $pos = strpos( $href, '#' ) ) {
5786
				$href = substr( $href, 0, $pos );
5787
			}
5788
		} else {
5789
			return $tag;
5790
		}
5791
5792
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5793
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5794
			return $tag;
5795
		}
5796
5797
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5798
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5799
			// And this isn't the pass that actually deals with the RTL version...
5800
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5801
				// Short out, as the RTL version will deal with it in a moment.
5802
				return $tag;
5803
			}
5804
		}
5805
5806
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5807
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
5808
		if ( $css ) {
5809
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5810
			if ( empty( $item->extra['after'] ) ) {
5811
				wp_add_inline_style( $handle, $css );
5812
			} else {
5813
				array_unshift( $item->extra['after'], $css );
5814
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5815
			}
5816
		}
5817
5818
		return $tag;
5819
	}
5820
5821
	/**
5822
	 * Loads a view file from the views
5823
	 *
5824
	 * Data passed in with the $data parameter will be available in the
5825
	 * template file as $data['value']
5826
	 *
5827
	 * @param string $template - Template file to load
5828
	 * @param array  $data - Any data to pass along to the template
5829
	 * @return boolean - If template file was found
5830
	 **/
5831
	public function load_view( $template, $data = array() ) {
5832
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
5833
5834
		if ( file_exists( $views_dir . $template ) ) {
5835
			require_once $views_dir . $template;
5836
			return true;
5837
		}
5838
5839
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
5840
		return false;
5841
	}
5842
5843
	/**
5844
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
5845
	 */
5846
	public function deprecated_hooks() {
5847
		$filter_deprecated_list = array(
5848
			'jetpack_bail_on_shortcode'                    => array(
5849
				'replacement' => 'jetpack_shortcodes_to_include',
5850
				'version'     => 'jetpack-3.1.0',
5851
			),
5852
			'wpl_sharing_2014_1'                           => array(
5853
				'replacement' => null,
5854
				'version'     => 'jetpack-3.6.0',
5855
			),
5856
			'jetpack-tools-to-include'                     => array(
5857
				'replacement' => 'jetpack_tools_to_include',
5858
				'version'     => 'jetpack-3.9.0',
5859
			),
5860
			'jetpack_identity_crisis_options_to_check'     => array(
5861
				'replacement' => null,
5862
				'version'     => 'jetpack-4.0.0',
5863
			),
5864
			'update_option_jetpack_single_user_site'       => array(
5865
				'replacement' => null,
5866
				'version'     => 'jetpack-4.3.0',
5867
			),
5868
			'audio_player_default_colors'                  => array(
5869
				'replacement' => null,
5870
				'version'     => 'jetpack-4.3.0',
5871
			),
5872
			'add_option_jetpack_featured_images_enabled'   => array(
5873
				'replacement' => null,
5874
				'version'     => 'jetpack-4.3.0',
5875
			),
5876
			'add_option_jetpack_update_details'            => array(
5877
				'replacement' => null,
5878
				'version'     => 'jetpack-4.3.0',
5879
			),
5880
			'add_option_jetpack_updates'                   => array(
5881
				'replacement' => null,
5882
				'version'     => 'jetpack-4.3.0',
5883
			),
5884
			'add_option_jetpack_network_name'              => array(
5885
				'replacement' => null,
5886
				'version'     => 'jetpack-4.3.0',
5887
			),
5888
			'add_option_jetpack_network_allow_new_registrations' => array(
5889
				'replacement' => null,
5890
				'version'     => 'jetpack-4.3.0',
5891
			),
5892
			'add_option_jetpack_network_add_new_users'     => array(
5893
				'replacement' => null,
5894
				'version'     => 'jetpack-4.3.0',
5895
			),
5896
			'add_option_jetpack_network_site_upload_space' => array(
5897
				'replacement' => null,
5898
				'version'     => 'jetpack-4.3.0',
5899
			),
5900
			'add_option_jetpack_network_upload_file_types' => array(
5901
				'replacement' => null,
5902
				'version'     => 'jetpack-4.3.0',
5903
			),
5904
			'add_option_jetpack_network_enable_administration_menus' => array(
5905
				'replacement' => null,
5906
				'version'     => 'jetpack-4.3.0',
5907
			),
5908
			'add_option_jetpack_is_multi_site'             => array(
5909
				'replacement' => null,
5910
				'version'     => 'jetpack-4.3.0',
5911
			),
5912
			'add_option_jetpack_is_main_network'           => array(
5913
				'replacement' => null,
5914
				'version'     => 'jetpack-4.3.0',
5915
			),
5916
			'add_option_jetpack_main_network_site'         => array(
5917
				'replacement' => null,
5918
				'version'     => 'jetpack-4.3.0',
5919
			),
5920
			'jetpack_sync_all_registered_options'          => array(
5921
				'replacement' => null,
5922
				'version'     => 'jetpack-4.3.0',
5923
			),
5924
			'jetpack_has_identity_crisis'                  => array(
5925
				'replacement' => 'jetpack_sync_error_idc_validation',
5926
				'version'     => 'jetpack-4.4.0',
5927
			),
5928
			'jetpack_is_post_mailable'                     => array(
5929
				'replacement' => null,
5930
				'version'     => 'jetpack-4.4.0',
5931
			),
5932
			'jetpack_seo_site_host'                        => array(
5933
				'replacement' => null,
5934
				'version'     => 'jetpack-5.1.0',
5935
			),
5936
			'jetpack_installed_plugin'                     => array(
5937
				'replacement' => 'jetpack_plugin_installed',
5938
				'version'     => 'jetpack-6.0.0',
5939
			),
5940
			'jetpack_holiday_snow_option_name'             => array(
5941
				'replacement' => null,
5942
				'version'     => 'jetpack-6.0.0',
5943
			),
5944
			'jetpack_holiday_chance_of_snow'               => array(
5945
				'replacement' => null,
5946
				'version'     => 'jetpack-6.0.0',
5947
			),
5948
			'jetpack_holiday_snow_js_url'                  => array(
5949
				'replacement' => null,
5950
				'version'     => 'jetpack-6.0.0',
5951
			),
5952
			'jetpack_is_holiday_snow_season'               => array(
5953
				'replacement' => null,
5954
				'version'     => 'jetpack-6.0.0',
5955
			),
5956
			'jetpack_holiday_snow_option_updated'          => array(
5957
				'replacement' => null,
5958
				'version'     => 'jetpack-6.0.0',
5959
			),
5960
			'jetpack_holiday_snowing'                      => array(
5961
				'replacement' => null,
5962
				'version'     => 'jetpack-6.0.0',
5963
			),
5964
			'jetpack_sso_auth_cookie_expirtation'          => array(
5965
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
5966
				'version'     => 'jetpack-6.1.0',
5967
			),
5968
			'jetpack_cache_plans'                          => array(
5969
				'replacement' => null,
5970
				'version'     => 'jetpack-6.1.0',
5971
			),
5972
5973
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
5974
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
5975
				'version'     => 'jetpack-6.5.0',
5976
			),
5977
			'jetpack_enable_site_verification'             => array(
5978
				'replacement' => null,
5979
				'version'     => 'jetpack-6.5.0',
5980
			),
5981
			'can_display_jetpack_manage_notice'            => array(
5982
				'replacement' => null,
5983
				'version'     => 'jetpack-7.3.0',
5984
			),
5985
			'atd_http_post_timeout'                        => array(
5986
				'replacement' => null,
5987
				'version'     => 'jetpack-7.3.0',
5988
			),
5989
			'atd_service_domain'                           => array(
5990
				'replacement' => null,
5991
				'version'     => 'jetpack-7.3.0',
5992
			),
5993
			'atd_load_scripts'                             => array(
5994
				'replacement' => null,
5995
				'version'     => 'jetpack-7.3.0',
5996
			),
5997
			'jetpack_widget_authors_exclude'               => array(
5998
				'replacement' => 'jetpack_widget_authors_params',
5999
				'version'     => 'jetpack-7.7.0',
6000
			),
6001
			// Removed in Jetpack 7.9.0
6002
			'jetpack_pwa_manifest'                         => array(
6003
				'replacement' => null,
6004
				'version'     => 'jetpack-7.9.0',
6005
			),
6006
			'jetpack_pwa_background_color'                 => array(
6007
				'replacement' => null,
6008
				'version'     => 'jetpack-7.9.0',
6009
			),
6010
			'jetpack_check_mobile'                         => array(
6011
				'replacement' => null,
6012
				'version'     => 'jetpack-8.3.0',
6013
			),
6014
			'jetpack_mobile_stylesheet'                    => array(
6015
				'replacement' => null,
6016
				'version'     => 'jetpack-8.3.0',
6017
			),
6018
			'jetpack_mobile_template'                      => array(
6019
				'replacement' => null,
6020
				'version'     => 'jetpack-8.3.0',
6021
			),
6022
			'jetpack_mobile_theme_menu'                    => array(
6023
				'replacement' => null,
6024
				'version'     => 'jetpack-8.3.0',
6025
			),
6026
			'minileven_show_featured_images'               => array(
6027
				'replacement' => null,
6028
				'version'     => 'jetpack-8.3.0',
6029
			),
6030
			'minileven_attachment_size'                    => array(
6031
				'replacement' => null,
6032
				'version'     => 'jetpack-8.3.0',
6033
			),
6034
			'instagram_cache_oembed_api_response_body'     => array(
6035
				'replacement' => null,
6036
				'version'     => 'jetpack-9.1.0',
6037
			),
6038
			'jetpack_can_make_outbound_https'              => array(
6039
				'replacement' => null,
6040
				'version'     => 'jetpack-9.1.0',
6041
			),
6042
		);
6043
6044
		foreach ( $filter_deprecated_list as $tag => $args ) {
6045
			if ( has_filter( $tag ) ) {
6046
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6047
			}
6048
		}
6049
6050
		$action_deprecated_list = array(
6051
			'jetpack_updated_theme'        => array(
6052
				'replacement' => 'jetpack_updated_themes',
6053
				'version'     => 'jetpack-6.2.0',
6054
			),
6055
			'atd_http_post_error'          => array(
6056
				'replacement' => null,
6057
				'version'     => 'jetpack-7.3.0',
6058
			),
6059
			'mobile_reject_mobile'         => array(
6060
				'replacement' => null,
6061
				'version'     => 'jetpack-8.3.0',
6062
			),
6063
			'mobile_force_mobile'          => array(
6064
				'replacement' => null,
6065
				'version'     => 'jetpack-8.3.0',
6066
			),
6067
			'mobile_app_promo_download'    => array(
6068
				'replacement' => null,
6069
				'version'     => 'jetpack-8.3.0',
6070
			),
6071
			'mobile_setup'                 => array(
6072
				'replacement' => null,
6073
				'version'     => 'jetpack-8.3.0',
6074
			),
6075
			'jetpack_mobile_footer_before' => array(
6076
				'replacement' => null,
6077
				'version'     => 'jetpack-8.3.0',
6078
			),
6079
			'wp_mobile_theme_footer'       => array(
6080
				'replacement' => null,
6081
				'version'     => 'jetpack-8.3.0',
6082
			),
6083
			'minileven_credits'            => array(
6084
				'replacement' => null,
6085
				'version'     => 'jetpack-8.3.0',
6086
			),
6087
			'jetpack_mobile_header_before' => array(
6088
				'replacement' => null,
6089
				'version'     => 'jetpack-8.3.0',
6090
			),
6091
			'jetpack_mobile_header_after'  => array(
6092
				'replacement' => null,
6093
				'version'     => 'jetpack-8.3.0',
6094
			),
6095
		);
6096
6097
		foreach ( $action_deprecated_list as $tag => $args ) {
6098
			if ( has_action( $tag ) ) {
6099
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6100
			}
6101
		}
6102
	}
6103
6104
	/**
6105
	 * Converts any url in a stylesheet, to the correct absolute url.
6106
	 *
6107
	 * Considerations:
6108
	 *  - Normal, relative URLs     `feh.png`
6109
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6110
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6111
	 *  - Absolute URLs             `http://domain.com/feh.png`
6112
	 *  - Domain root relative URLs `/feh.png`
6113
	 *
6114
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6115
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6116
	 *
6117
	 * @return mixed|string
6118
	 */
6119
	public static function absolutize_css_urls( $css, $css_file_url ) {
6120
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6121
		$css_dir = dirname( $css_file_url );
6122
		$p       = wp_parse_url( $css_dir );
6123
		$domain  = sprintf(
6124
			'%1$s//%2$s%3$s%4$s',
6125
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6126
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6127
			$p['host'],
6128
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6129
		);
6130
6131
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6132
			$find = $replace = array();
6133
			foreach ( $matches as $match ) {
6134
				$url = trim( $match['path'], "'\" \t" );
6135
6136
				// If this is a data url, we don't want to mess with it.
6137
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6138
					continue;
6139
				}
6140
6141
				// If this is an absolute or protocol-agnostic url,
6142
				// we don't want to mess with it.
6143
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6144
					continue;
6145
				}
6146
6147
				switch ( substr( $url, 0, 1 ) ) {
6148
					case '/':
6149
						$absolute = $domain . $url;
6150
						break;
6151
					default:
6152
						$absolute = $css_dir . '/' . $url;
6153
				}
6154
6155
				$find[]    = $match[0];
6156
				$replace[] = sprintf( 'url("%s")', $absolute );
6157
			}
6158
			$css = str_replace( $find, $replace, $css );
6159
		}
6160
6161
		return $css;
6162
	}
6163
6164
	/**
6165
	 * This methods removes all of the registered css files on the front end
6166
	 * from Jetpack in favor of using a single file. In effect "imploding"
6167
	 * all the files into one file.
6168
	 *
6169
	 * Pros:
6170
	 * - Uses only ONE css asset connection instead of 15
6171
	 * - Saves a minimum of 56k
6172
	 * - Reduces server load
6173
	 * - Reduces time to first painted byte
6174
	 *
6175
	 * Cons:
6176
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6177
	 *      should not cause any issues with themes.
6178
	 * - Plugins/themes dequeuing styles no longer do anything. See
6179
	 *      jetpack_implode_frontend_css filter for a workaround
6180
	 *
6181
	 * For some situations developers may wish to disable css imploding and
6182
	 * instead operate in legacy mode where each file loads seperately and
6183
	 * can be edited individually or dequeued. This can be accomplished with
6184
	 * the following line:
6185
	 *
6186
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6187
	 *
6188
	 * @since 3.2
6189
	 **/
6190
	public function implode_frontend_css( $travis_test = false ) {
6191
		$do_implode = true;
6192
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6193
			$do_implode = false;
6194
		}
6195
6196
		// Do not implode CSS when the page loads via the AMP plugin.
6197
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6198
			$do_implode = false;
6199
		}
6200
6201
		/**
6202
		 * Allow CSS to be concatenated into a single jetpack.css file.
6203
		 *
6204
		 * @since 3.2.0
6205
		 *
6206
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6207
		 */
6208
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6209
6210
		// Do not use the imploded file when default behavior was altered through the filter
6211
		if ( ! $do_implode ) {
6212
			return;
6213
		}
6214
6215
		// We do not want to use the imploded file in dev mode, or if not connected
6216
		if ( ( new Status() )->is_offline_mode() || ! self::is_connection_ready() ) {
6217
			if ( ! $travis_test ) {
6218
				return;
6219
			}
6220
		}
6221
6222
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6223
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6224
			return;
6225
		}
6226
6227
		/*
6228
		 * Now we assume Jetpack is connected and able to serve the single
6229
		 * file.
6230
		 *
6231
		 * In the future there will be a check here to serve the file locally
6232
		 * or potentially from the Jetpack CDN
6233
		 *
6234
		 * For now:
6235
		 * - Enqueue a single imploded css file
6236
		 * - Zero out the style_loader_tag for the bundled ones
6237
		 * - Be happy, drink scotch
6238
		 */
6239
6240
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6241
6242
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6243
6244
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6245
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6246
	}
6247
6248
	function concat_remove_style_loader_tag( $tag, $handle ) {
6249
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6250
			$tag = '';
6251
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6252
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6253
			}
6254
		}
6255
6256
		return $tag;
6257
	}
6258
6259
	/*
6260
	 * Check the heartbeat data
6261
	 *
6262
	 * Organizes the heartbeat data by severity.  For example, if the site
6263
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6264
	 *
6265
	 * Data will be added to "caution" array, if it either:
6266
	 *  - Out of date Jetpack version
6267
	 *  - Out of date WP version
6268
	 *  - Out of date PHP version
6269
	 *
6270
	 * $return array $filtered_data
6271
	 */
6272
	public static function jetpack_check_heartbeat_data() {
6273
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6274
6275
		$good    = array();
6276
		$caution = array();
6277
		$bad     = array();
6278
6279
		foreach ( $raw_data as $stat => $value ) {
6280
6281
			// Check jetpack version
6282
			if ( 'version' == $stat ) {
6283
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6284
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6285
					continue;
6286
				}
6287
			}
6288
6289
			// Check WP version
6290
			if ( 'wp-version' == $stat ) {
6291
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6292
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6293
					continue;
6294
				}
6295
			}
6296
6297
			// Check PHP version
6298
			if ( 'php-version' == $stat ) {
6299
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6300
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6301
					continue;
6302
				}
6303
			}
6304
6305
			// Check ID crisis
6306
			if ( 'identitycrisis' == $stat ) {
6307
				if ( 'yes' == $value ) {
6308
					$bad[ $stat ] = $value;
6309
					continue;
6310
				}
6311
			}
6312
6313
			// The rest are good :)
6314
			$good[ $stat ] = $value;
6315
		}
6316
6317
		$filtered_data = array(
6318
			'good'    => $good,
6319
			'caution' => $caution,
6320
			'bad'     => $bad,
6321
		);
6322
6323
		return $filtered_data;
6324
	}
6325
6326
	/*
6327
	 * This method is used to organize all options that can be reset
6328
	 * without disconnecting Jetpack.
6329
	 *
6330
	 * It is used in class.jetpack-cli.php to reset options
6331
	 *
6332
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6333
	 *
6334
	 * @return array of options to delete.
6335
	 */
6336
	public static function get_jetpack_options_for_reset() {
6337
		return Jetpack_Options::get_options_for_reset();
6338
	}
6339
6340
	/*
6341
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6342
	 * so we can bring them directly to their site in calypso.
6343
	 *
6344
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
6345
	 *
6346
	 * @param string | url
6347
	 * @return string | url without the guff
6348
	 */
6349
	public static function build_raw_urls( $url ) {
6350
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
6351
6352
		return ( new Status() )->get_site_suffix( $url );
6353
	}
6354
6355
	public function wp_dashboard_setup() {
6356
		if ( self::is_connection_ready() ) {
6357
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6358
		}
6359
6360
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6361
			$jetpack_logo = new Jetpack_Logo();
6362
			$widget_title = sprintf(
6363
				/* translators: Placeholder is a Jetpack logo. */
6364
				__( 'Stats by %s', 'jetpack' ),
6365
				$jetpack_logo->get_jp_emblem( true )
6366
			);
6367
6368
			// Wrap title in span so Logo can be properly styled.
6369
			$widget_title = sprintf(
6370
				'<span>%s</span>',
6371
				$widget_title
6372
			);
6373
6374
			wp_add_dashboard_widget(
6375
				'jetpack_summary_widget',
6376
				$widget_title,
6377
				array( __CLASS__, 'dashboard_widget' )
6378
			);
6379
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6380
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6381
6382
			// If we're inactive and not in offline mode, sort our box to the top.
6383
			if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
6384
				global $wp_meta_boxes;
6385
6386
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6387
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6388
6389
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6390
			}
6391
		}
6392
	}
6393
6394
	/**
6395
	 * @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...
6396
	 * @return mixed
6397
	 */
6398
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6399
		if ( ! is_array( $sorted ) ) {
6400
			return $sorted;
6401
		}
6402
6403
		foreach ( $sorted as $box_context => $ids ) {
6404
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6405
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6406
				continue;
6407
			}
6408
6409
			$ids_array = explode( ',', $ids );
6410
			$key       = array_search( 'dashboard_stats', $ids_array );
6411
6412
			if ( false !== $key ) {
6413
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6414
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6415
				$sorted[ $box_context ] = implode( ',', $ids_array );
6416
				// We've found it, stop searching, and just return.
6417
				break;
6418
			}
6419
		}
6420
6421
		return $sorted;
6422
	}
6423
6424
	public static function dashboard_widget() {
6425
		/**
6426
		 * Fires when the dashboard is loaded.
6427
		 *
6428
		 * @since 3.4.0
6429
		 */
6430
		do_action( 'jetpack_dashboard_widget' );
6431
	}
6432
6433
	public static function dashboard_widget_footer() {
6434
		?>
6435
		<footer>
6436
6437
		<div class="protect">
6438
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6439
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6440
				<p class="blocked-count">
6441
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6442
				</p>
6443
				<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>
6444
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
6445
				<a href="
6446
				<?php
6447
				echo esc_url(
6448
					wp_nonce_url(
6449
						self::admin_url(
6450
							array(
6451
								'action' => 'activate',
6452
								'module' => 'protect',
6453
							)
6454
						),
6455
						'jetpack_activate-protect'
6456
					)
6457
				);
6458
				?>
6459
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6460
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6461
				</a>
6462
			<?php else : ?>
6463
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6464
			<?php endif; ?>
6465
		</div>
6466
6467
		<div class="akismet">
6468
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6469
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6470
				<p class="blocked-count">
6471
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6472
				</p>
6473
				<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>
6474
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6475
				<a href="
6476
				<?php
6477
				echo esc_url(
6478
					wp_nonce_url(
6479
						add_query_arg(
6480
							array(
6481
								'action' => 'activate',
6482
								'plugin' => 'akismet/akismet.php',
6483
							),
6484
							admin_url( 'plugins.php' )
6485
						),
6486
						'activate-plugin_akismet/akismet.php'
6487
					)
6488
				);
6489
				?>
6490
							" class="button button-jetpack">
6491
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
6492
				</a>
6493
			<?php else : ?>
6494
				<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>
6495
			<?php endif; ?>
6496
		</div>
6497
6498
		</footer>
6499
		<?php
6500
	}
6501
6502
	/*
6503
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6504
	 */
6505
	function jetpack_icon_user_connected( $columns ) {
6506
		$columns['user_jetpack'] = '';
6507
		return $columns;
6508
	}
6509
6510
	/*
6511
	 * Show Jetpack icon if the user is linked.
6512
	 */
6513
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6514
		if ( 'user_jetpack' === $col && self::connection()->is_user_connected( $user_id ) ) {
6515
			$jetpack_logo = new Jetpack_Logo();
6516
			$emblem_html  = sprintf(
6517
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6518
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6519
				$jetpack_logo->get_jp_emblem()
6520
			);
6521
			return $emblem_html;
6522
		}
6523
6524
		return $val;
6525
	}
6526
6527
	/*
6528
	 * Style the Jetpack user column
6529
	 */
6530
	function jetpack_user_col_style() {
6531
		global $current_screen;
6532
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6533
			?>
6534
			<style>
6535
				.fixed .column-user_jetpack {
6536
					width: 21px;
6537
				}
6538
				.jp-emblem-user-admin svg {
6539
					width: 20px;
6540
					height: 20px;
6541
				}
6542
				.jp-emblem-user-admin path {
6543
					fill: #00BE28;
6544
				}
6545
			</style>
6546
			<?php
6547
		}
6548
	}
6549
6550
	/**
6551
	 * Checks if Akismet is active and working.
6552
	 *
6553
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6554
	 * that implied usage of methods present since more recent version.
6555
	 * See https://github.com/Automattic/jetpack/pull/9585
6556
	 *
6557
	 * @since  5.1.0
6558
	 *
6559
	 * @return bool True = Akismet available. False = Aksimet not available.
6560
	 */
6561
	public static function is_akismet_active() {
6562
		static $status = null;
6563
6564
		if ( ! is_null( $status ) ) {
6565
			return $status;
6566
		}
6567
6568
		// Check if a modern version of Akismet is active.
6569
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6570
			$status = false;
6571
			return $status;
6572
		}
6573
6574
		// Make sure there is a key known to Akismet at all before verifying key.
6575
		$akismet_key = Akismet::get_api_key();
6576
		if ( ! $akismet_key ) {
6577
			$status = false;
6578
			return $status;
6579
		}
6580
6581
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6582
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6583
6584
		// 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.
6585
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6586
		// We cache the result of the Akismet key verification for ten minutes.
6587
		if ( ! $akismet_key_state || $recheck ) {
6588
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6589
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6590
		}
6591
6592
		$status = 'valid' === $akismet_key_state;
6593
6594
		return $status;
6595
	}
6596
6597
	/**
6598
	 * Given a minified path, and a non-minified path, will return
6599
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6600
	 *
6601
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6602
	 * root Jetpack directory.
6603
	 *
6604
	 * @since 5.6.0
6605
	 *
6606
	 * @param string $min_path
6607
	 * @param string $non_min_path
6608
	 * @return string The URL to the file
6609
	 */
6610
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6611
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6612
	}
6613
6614
	/**
6615
	 * Checks for whether Jetpack Backup is enabled.
6616
	 * Will return true if the state of Backup is anything except "unavailable".
6617
	 *
6618
	 * @return bool|int|mixed
6619
	 */
6620
	public static function is_rewind_enabled() {
6621
		// Rewind is a paid feature, therefore requires a user-level connection.
6622
		if ( ! static::connection()->has_connected_owner() ) {
6623
			return false;
6624
		}
6625
6626
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6627
		if ( false === $rewind_enabled ) {
6628
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6629
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6630
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6631
				&& ! empty( $rewind_data['state'] )
6632
				&& 'active' === $rewind_data['state'] )
6633
				? 1
6634
				: 0;
6635
6636
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6637
		}
6638
		return $rewind_enabled;
6639
	}
6640
6641
	/**
6642
	 * Return Calypso environment value; used for developing Jetpack and pairing
6643
	 * it with different Calypso enrionments, such as localhost.
6644
	 *
6645
	 * @since 7.4.0
6646
	 *
6647
	 * @return string Calypso environment
6648
	 */
6649
	public static function get_calypso_env() {
6650
		if ( isset( $_GET['calypso_env'] ) ) {
6651
			return sanitize_key( $_GET['calypso_env'] );
6652
		}
6653
6654
		if ( getenv( 'CALYPSO_ENV' ) ) {
6655
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6656
		}
6657
6658
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6659
			return sanitize_key( CALYPSO_ENV );
6660
		}
6661
6662
		return '';
6663
	}
6664
6665
	/**
6666
	 * Returns the hostname with protocol for Calypso.
6667
	 * Used for developing Jetpack with Calypso.
6668
	 *
6669
	 * @since 8.4.0
6670
	 *
6671
	 * @return string Calypso host.
6672
	 */
6673
	public static function get_calypso_host() {
6674
		$calypso_env = self::get_calypso_env();
6675
		switch ( $calypso_env ) {
6676
			case 'development':
6677
				return 'http://calypso.localhost:3000/';
6678
			case 'wpcalypso':
6679
				return 'https://wpcalypso.wordpress.com/';
6680
			case 'horizon':
6681
				return 'https://horizon.wordpress.com/';
6682
			default:
6683
				return 'https://wordpress.com/';
6684
		}
6685
	}
6686
6687
	/**
6688
	 * Handles activating default modules as well general cleanup for the new connection.
6689
	 *
6690
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6691
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6692
	 * @param boolean $send_state_messages          Whether to send state messages.
6693
	 * @return void
6694
	 */
6695
	public static function handle_post_authorization_actions(
6696
		$activate_sso = false,
6697
		$redirect_on_activation_error = false,
6698
		$send_state_messages = true
6699
	) {
6700
		$other_modules = $activate_sso
6701
			? array( 'sso' )
6702
			: array();
6703
6704
		if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
6705
			$active_modules = Jetpack_Options::get_option( 'active_modules' );
6706
			self::delete_active_modules();
6707
6708
			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...
6709
		} else {
6710
			// Default modules that don't require a user were already activated on site_register.
6711
			// This time let's activate only those that require a user, this assures we don't reactivate manually deactivated modules while the site was connected only at a site level.
6712
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
6713
			Jetpack_Options::update_option( 'active_modules_initialized', true );
6714
		}
6715
6716
		// Since this is a fresh connection, be sure to clear out IDC options
6717
		Identity_Crisis::clear_all_idc_options();
6718
6719
		if ( $send_state_messages ) {
6720
			self::state( 'message', 'authorized' );
6721
		}
6722
	}
6723
6724
	/**
6725
	 * Returns a boolean for whether backups UI should be displayed or not.
6726
	 *
6727
	 * @return bool Should backups UI be displayed?
6728
	 */
6729
	public static function show_backups_ui() {
6730
		/**
6731
		 * Whether UI for backups should be displayed.
6732
		 *
6733
		 * @since 6.5.0
6734
		 *
6735
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6736
		 */
6737
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6738
	}
6739
6740
	/**
6741
	 * Clean leftoveruser meta.
6742
	 *
6743
	 * Delete Jetpack-related user meta when it is no longer needed.
6744
	 *
6745
	 * @since 7.3.0
6746
	 *
6747
	 * @param int $user_id User ID being updated.
6748
	 */
6749
	public static function user_meta_cleanup( $user_id ) {
6750
		$meta_keys = array(
6751
			// AtD removed from Jetpack 7.3
6752
			'AtD_options',
6753
			'AtD_check_when',
6754
			'AtD_guess_lang',
6755
			'AtD_ignored_phrases',
6756
		);
6757
6758
		foreach ( $meta_keys as $meta_key ) {
6759
			if ( get_user_meta( $user_id, $meta_key ) ) {
6760
				delete_user_meta( $user_id, $meta_key );
6761
			}
6762
		}
6763
	}
6764
6765
	/**
6766
	 * Checks if a Jetpack site is both active and not in offline mode.
6767
	 *
6768
	 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
6769
	 *
6770
	 * @since 8.8.0
6771
	 *
6772
	 * @return bool True if Jetpack is active and not in offline mode.
6773
	 */
6774
	public static function is_active_and_not_offline_mode() {
6775
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
6776
			return false;
6777
		}
6778
		return true;
6779
	}
6780
6781
	/**
6782
	 * Returns the list of products that we have available for purchase.
6783
	 */
6784
	public static function get_products_for_purchase() {
6785
		$products = array();
6786
		if ( ! is_multisite() ) {
6787
			$products[] = array(
6788
				'key'               => 'backup',
6789
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
6790
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
6791
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
6792
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
6793
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
6794
				'options'           => array(
6795
					array(
6796
						'type'        => 'daily',
6797
						'slug'        => 'jetpack-backup-daily',
6798
						'key'         => 'jetpack_backup_daily',
6799
						'name'        => __( 'Daily Backups', 'jetpack' ),
6800
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
6801
					),
6802
					array(
6803
						'type'        => 'realtime',
6804
						'slug'        => 'jetpack-backup-realtime',
6805
						'key'         => 'jetpack_backup_realtime',
6806
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
6807
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
6808
					),
6809
				),
6810
				'default_option'    => 'realtime',
6811
				'show_promotion'    => true,
6812
				'discount_percent'  => 70,
6813
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
6814
			);
6815
6816
			$products[] = array(
6817
				'key'               => 'scan',
6818
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
6819
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
6820
				'learn_more'        => __( 'Learn More', 'jetpack' ),
6821
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
6822
				'show_promotion'    => true,
6823
				'discount_percent'  => 30,
6824
				'options'           => array(
6825
					array(
6826
						'type' => 'scan',
6827
						'slug' => 'jetpack-scan',
6828
						'key'  => 'jetpack_scan',
6829
						'name' => __( 'Daily Scan', 'jetpack' ),
6830
					),
6831
				),
6832
				'default_option'    => 'scan',
6833
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
6834
			);
6835
		}
6836
6837
		$products[] = array(
6838
			'key'               => 'search',
6839
			'title'             => __( 'Jetpack Search', 'jetpack' ),
6840
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
6841
			'learn_more'        => __( 'Learn More', 'jetpack' ),
6842
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
6843
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
6844
			'options'           => array(
6845
				array(
6846
					'type' => 'search',
6847
					'slug' => 'jetpack-search',
6848
					'key'  => 'jetpack_search',
6849
					'name' => __( 'Search', 'jetpack' ),
6850
				),
6851
			),
6852
			'tears'             => array(),
6853
			'default_option'    => 'search',
6854
			'show_promotion'    => false,
6855
			'included_in_plans' => array( 'search-plan' ),
6856
		);
6857
6858
		$products[] = array(
6859
			'key'               => 'anti-spam',
6860
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
6861
			'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' ),
6862
			'learn_more'        => __( 'Learn More', 'jetpack' ),
6863
			'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' ),
6864
			'options'           => array(
6865
				array(
6866
					'type' => 'anti-spam',
6867
					'slug' => 'jetpack-anti-spam',
6868
					'key'  => 'jetpack_anti_spam',
6869
					'name' => __( 'Anti-Spam', 'jetpack' ),
6870
				),
6871
			),
6872
			'default_option'    => 'anti-spam',
6873
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
6874
		);
6875
6876
		return $products;
6877
	}
6878
6879
	/**
6880
	 * Determine if the current user is allowed to make Jetpack purchases without
6881
	 * a WordPress.com account
6882
	 *
6883
	 * @return boolean True if the user can make purchases, false if not
6884
	 */
6885
	public static function current_user_can_purchase() {
6886
6887
		// The site must be site-connected to Jetpack (no users connected).
6888
		if ( ! self::connection()->is_site_connection() ) {
6889
			return false;
6890
		}
6891
6892
		// Make sure only administrators can make purchases.
6893
		if ( ! current_user_can( 'manage_options' ) ) {
6894
			return false;
6895
		}
6896
6897
		return true;
6898
	}
6899
6900
}
6901