Completed
Push — renovate/react-monorepo ( 545e89...65a81e )
by
unknown
268:48 queued 253:47
created

Jetpack::verify_json_api_authorization_request()   F

Complexity

Conditions 23
Paths 12672

Size

Total Lines 121

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
nc 12672
nop 1
dl 0
loc 121
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

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

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

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

Loading history...
928
	 */
929 View Code Duplication
	public function setup_xmlrpc_handlers(
930
		$request_params,
931
		$is_active,
932
		$is_signed,
933
		Jetpack_XMLRPC_Server $xmlrpc_server = null
934
	) {
935
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
936
937
		if ( ! $this->connection_manager ) {
938
			$this->connection_manager = new Connection_Manager();
939
		}
940
941
		return $this->connection_manager->setup_xmlrpc_handlers(
942
			$request_params,
943
			$is_active,
944
			$is_signed,
945
			$xmlrpc_server
946
		);
947
	}
948
949
	/**
950
	 * Initialize REST API registration connector.
951
	 *
952
	 * @deprecated since 7.7.0
953
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
954
	 */
955 View Code Duplication
	public function initialize_rest_api_registration_connector() {
956
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
957
958
		if ( ! $this->connection_manager ) {
959
			$this->connection_manager = new Connection_Manager();
960
		}
961
962
		$this->connection_manager->initialize_rest_api_registration_connector();
963
	}
964
965
	/**
966
	 * This is ported over from the manage module, which has been deprecated and baked in here.
967
	 *
968
	 * @param $domains
969
	 */
970
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
971
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
972
	}
973
974
	/**
975
	 * Return $domains, with 'wordpress.com' appended.
976
	 * This is ported over from the manage module, which has been deprecated and baked in here.
977
	 *
978
	 * @param $domains
979
	 * @return array
980
	 */
981
	function allow_wpcom_domain( $domains ) {
982
		if ( empty( $domains ) ) {
983
			$domains = array();
984
		}
985
		$domains[] = 'wordpress.com';
986
		return array_unique( $domains );
987
	}
988
989
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
990
		$post = get_post( $post_id );
991
992
		if ( empty( $post ) ) {
993
			return $default_url;
994
		}
995
996
		$post_type = $post->post_type;
997
998
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
999
		// https://en.support.wordpress.com/custom-post-types/
1000
		$allowed_post_types = array(
1001
			'post',
1002
			'page',
1003
			'jetpack-portfolio',
1004
			'jetpack-testimonial',
1005
		);
1006
1007
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1008
			return $default_url;
1009
		}
1010
1011
		return Redirect::get_url(
1012
			'calypso-edit-' . $post_type,
1013
			array(
1014
				'path' => $post_id,
1015
			)
1016
		);
1017
	}
1018
1019
	function point_edit_comment_links_to_calypso( $url ) {
1020
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1021
		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...
1022
1023
		return Redirect::get_url(
1024
			'calypso-edit-comment',
1025
			array(
1026
				'path' => $query_args['amp;c'],
1027
			)
1028
		);
1029
1030
	}
1031
1032
	/**
1033
	 * Extend callables with Jetpack Plugin functions.
1034
	 *
1035
	 * @param array $callables list of callables.
1036
	 *
1037
	 * @return array list of callables.
1038
	 */
1039
	public function filter_sync_callable_whitelist( $callables ) {
1040
1041
		// Jetpack Functions.
1042
		$jetpack_callables = array(
1043
			'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
1044
			'updates'                  => array( 'Jetpack', 'get_updates' ),
1045
			'active_modules'           => array( 'Jetpack', 'get_active_modules' ),
1046
			'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1047
		);
1048
		$callables         = array_merge( $callables, $jetpack_callables );
1049
1050
		// Jetpack_SSO_Helpers.
1051
		if ( include_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' ) {
1052
			$sso_helpers = array(
1053
				'sso_is_two_step_required'      => array( 'Jetpack_SSO_Helpers', 'is_two_step_required' ),
1054
				'sso_should_hide_login_form'    => array( 'Jetpack_SSO_Helpers', 'should_hide_login_form' ),
1055
				'sso_match_by_email'            => array( 'Jetpack_SSO_Helpers', 'match_by_email' ),
1056
				'sso_new_user_override'         => array( 'Jetpack_SSO_Helpers', 'new_user_override' ),
1057
				'sso_bypass_default_login_form' => array( 'Jetpack_SSO_Helpers', 'bypass_login_forward_wpcom' ),
1058
			);
1059
			$callables   = array_merge( $callables, $sso_helpers );
1060
		}
1061
1062
		return $callables;
1063
	}
1064
1065
	function jetpack_track_last_sync_callback( $params ) {
1066
		/**
1067
		 * Filter to turn off jitm caching
1068
		 *
1069
		 * @since 5.4.0
1070
		 *
1071
		 * @param bool false Whether to cache just in time messages
1072
		 */
1073
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1074
			return $params;
1075
		}
1076
1077
		if ( is_array( $params ) && isset( $params[0] ) ) {
1078
			$option = $params[0];
1079
			if ( 'active_plugins' === $option ) {
1080
				// use the cache if we can, but not terribly important if it gets evicted
1081
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1082
			}
1083
		}
1084
1085
		return $params;
1086
	}
1087
1088
	function jetpack_connection_banner_callback() {
1089
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1090
1091
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1092
		if (
1093
			isset( $_REQUEST['dismissBanner'] ) &&
1094
			! Jetpack_Connection_Banner::force_display()
1095
		) {
1096
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1097
			wp_send_json_success();
1098
		}
1099
1100
		wp_die();
1101
	}
1102
1103
	/**
1104
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1105
	 * Only used in our alternate XML-RPC endpoint, where we want to
1106
	 * ensure that Core and other plugins' methods are not exposed.
1107
	 *
1108
	 * @deprecated since 7.7.0
1109
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1110
	 *
1111
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1112
	 * @return array Filtered $methods
1113
	 */
1114 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1115
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1116
1117
		if ( ! $this->connection_manager ) {
1118
			$this->connection_manager = new Connection_Manager();
1119
		}
1120
1121
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1122
	}
1123
1124
	/**
1125
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1126
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1127
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1128
	 * which is accessible via a different URI. Most of the below is copied directly
1129
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1130
	 *
1131
	 * @deprecated since 7.7.0
1132
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1133
	 */
1134 View Code Duplication
	public function alternate_xmlrpc() {
1135
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1136
1137
		if ( ! $this->connection_manager ) {
1138
			$this->connection_manager = new Connection_Manager();
1139
		}
1140
1141
		$this->connection_manager->alternate_xmlrpc();
1142
	}
1143
1144
	/**
1145
	 * The callback for the JITM ajax requests.
1146
	 *
1147
	 * @deprecated since 7.9.0
1148
	 */
1149
	function jetpack_jitm_ajax_callback() {
1150
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1151
	}
1152
1153
	/**
1154
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1155
	 */
1156
	function push_stats() {
1157
		if ( ! empty( $this->stats ) ) {
1158
			$this->do_stats( 'server_side' );
1159
		}
1160
	}
1161
1162
	/**
1163
	 * Sets the Jetpack custom capabilities.
1164
	 *
1165
	 * @param string[] $caps    Array of the user's capabilities.
1166
	 * @param string   $cap     Capability name.
1167
	 * @param int      $user_id The user ID.
1168
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1169
	 */
1170
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1171
		$is_offline_mode = ( new Status() )->is_offline_mode();
1172
		switch ( $cap ) {
1173
			case 'jetpack_manage_modules':
1174
			case 'jetpack_activate_modules':
1175
			case 'jetpack_deactivate_modules':
1176
				$caps = array( 'manage_options' );
1177
				break;
1178
			case 'jetpack_configure_modules':
1179
				$caps = array( 'manage_options' );
1180
				break;
1181
			case 'jetpack_manage_autoupdates':
1182
				$caps = array(
1183
					'manage_options',
1184
					'update_plugins',
1185
				);
1186
				break;
1187
			case 'jetpack_network_admin_page':
1188
			case 'jetpack_network_settings_page':
1189
				$caps = array( 'manage_network_plugins' );
1190
				break;
1191
			case 'jetpack_network_sites_page':
1192
				$caps = array( 'manage_sites' );
1193
				break;
1194
			case 'jetpack_admin_page':
1195
				if ( $is_offline_mode ) {
1196
					$caps = array( 'manage_options' );
1197
					break;
1198
				} else {
1199
					$caps = array( 'read' );
1200
				}
1201
				break;
1202
		}
1203
		return $caps;
1204
	}
1205
1206
	/**
1207
	 * Require a Jetpack authentication.
1208
	 *
1209
	 * @deprecated since 7.7.0
1210
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1211
	 */
1212 View Code Duplication
	public function require_jetpack_authentication() {
1213
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1214
1215
		if ( ! $this->connection_manager ) {
1216
			$this->connection_manager = new Connection_Manager();
1217
		}
1218
1219
		$this->connection_manager->require_jetpack_authentication();
1220
	}
1221
1222
	/**
1223
	 * Register assets for use in various modules and the Jetpack admin page.
1224
	 *
1225
	 * @uses wp_script_is, wp_register_script, plugins_url
1226
	 * @action wp_loaded
1227
	 * @return null
1228
	 */
1229
	public function register_assets() {
1230 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1231
			wp_register_script(
1232
				'jetpack-gallery-settings',
1233
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1234
				array( 'media-views' ),
1235
				'20121225'
1236
			);
1237
		}
1238
1239
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1240
			wp_register_script(
1241
				'jetpack-twitter-timeline',
1242
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1243
				array( 'jquery' ),
1244
				'4.0.0',
1245
				true
1246
			);
1247
		}
1248
1249
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1250
			wp_register_script(
1251
				'jetpack-facebook-embed',
1252
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1253
				array(),
1254
				null,
1255
				true
1256
			);
1257
1258
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1259
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1260
			if ( ! is_numeric( $fb_app_id ) ) {
1261
				$fb_app_id = '';
1262
			}
1263
			wp_localize_script(
1264
				'jetpack-facebook-embed',
1265
				'jpfbembed',
1266
				array(
1267
					'appid'  => $fb_app_id,
1268
					'locale' => $this->get_locale(),
1269
				)
1270
			);
1271
		}
1272
1273
		/**
1274
		 * As jetpack_register_genericons is by default fired off a hook,
1275
		 * the hook may have already fired by this point.
1276
		 * So, let's just trigger it manually.
1277
		 */
1278
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1279
		jetpack_register_genericons();
1280
1281
		/**
1282
		 * Register the social logos
1283
		 */
1284
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1285
		jetpack_register_social_logos();
1286
1287 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1288
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1289
		}
1290
	}
1291
1292
	/**
1293
	 * Guess locale from language code.
1294
	 *
1295
	 * @param string $lang Language code.
1296
	 * @return string|bool
1297
	 */
1298 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1299
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1300
			return 'en_US';
1301
		}
1302
1303
		if ( ! class_exists( 'GP_Locales' ) ) {
1304
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1305
				return false;
1306
			}
1307
1308
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1309
		}
1310
1311
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1312
			// WP.com: get_locale() returns 'it'
1313
			$locale = GP_Locales::by_slug( $lang );
1314
		} else {
1315
			// Jetpack: get_locale() returns 'it_IT';
1316
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1317
		}
1318
1319
		if ( ! $locale ) {
1320
			return false;
1321
		}
1322
1323
		if ( empty( $locale->facebook_locale ) ) {
1324
			if ( empty( $locale->wp_locale ) ) {
1325
				return false;
1326
			} else {
1327
				// Facebook SDK is smart enough to fall back to en_US if a
1328
				// locale isn't supported. Since supported Facebook locales
1329
				// can fall out of sync, we'll attempt to use the known
1330
				// wp_locale value and rely on said fallback.
1331
				return $locale->wp_locale;
1332
			}
1333
		}
1334
1335
		return $locale->facebook_locale;
1336
	}
1337
1338
	/**
1339
	 * Get the locale.
1340
	 *
1341
	 * @return string|bool
1342
	 */
1343
	function get_locale() {
1344
		$locale = $this->guess_locale_from_lang( get_locale() );
1345
1346
		if ( ! $locale ) {
1347
			$locale = 'en_US';
1348
		}
1349
1350
		return $locale;
1351
	}
1352
1353
	/**
1354
	 * Return the network_site_url so that .com knows what network this site is a part of.
1355
	 *
1356
	 * @param  bool $option
1357
	 * @return string
1358
	 */
1359
	public function jetpack_main_network_site_option( $option ) {
1360
		return network_site_url();
1361
	}
1362
	/**
1363
	 * Network Name.
1364
	 */
1365
	static function network_name( $option = null ) {
1366
		global $current_site;
1367
		return $current_site->site_name;
1368
	}
1369
	/**
1370
	 * Does the network allow new user and site registrations.
1371
	 *
1372
	 * @return string
1373
	 */
1374
	static function network_allow_new_registrations( $option = null ) {
1375
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1376
	}
1377
	/**
1378
	 * Does the network allow admins to add new users.
1379
	 *
1380
	 * @return boolian
1381
	 */
1382
	static function network_add_new_users( $option = null ) {
1383
		return (bool) get_site_option( 'add_new_users' );
1384
	}
1385
	/**
1386
	 * File upload psace left per site in MB.
1387
	 *  -1 means NO LIMIT.
1388
	 *
1389
	 * @return number
1390
	 */
1391
	static function network_site_upload_space( $option = null ) {
1392
		// value in MB
1393
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1394
	}
1395
1396
	/**
1397
	 * Network allowed file types.
1398
	 *
1399
	 * @return string
1400
	 */
1401
	static function network_upload_file_types( $option = null ) {
1402
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1403
	}
1404
1405
	/**
1406
	 * Maximum file upload size set by the network.
1407
	 *
1408
	 * @return number
1409
	 */
1410
	static function network_max_upload_file_size( $option = null ) {
1411
		// value in KB
1412
		return get_site_option( 'fileupload_maxk', 300 );
1413
	}
1414
1415
	/**
1416
	 * Lets us know if a site allows admins to manage the network.
1417
	 *
1418
	 * @return array
1419
	 */
1420
	static function network_enable_administration_menus( $option = null ) {
1421
		return get_site_option( 'menu_items' );
1422
	}
1423
1424
	/**
1425
	 * If a user has been promoted to or demoted from admin, we need to clear the
1426
	 * jetpack_other_linked_admins transient.
1427
	 *
1428
	 * @since 4.3.2
1429
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1430
	 *
1431
	 * @param int    $user_id   The user ID whose role changed.
1432
	 * @param string $role      The new role.
1433
	 * @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...
1434
	 */
1435
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1436
		if ( 'administrator' == $role
1437
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1438
			|| is_null( $old_roles )
1439
		) {
1440
			delete_transient( 'jetpack_other_linked_admins' );
1441
		}
1442
	}
1443
1444
	/**
1445
	 * Checks to see if there are any other users available to become primary
1446
	 * Users must both:
1447
	 * - Be linked to wpcom
1448
	 * - Be an admin
1449
	 *
1450
	 * @return mixed False if no other users are linked, Int if there are.
1451
	 */
1452
	static function get_other_linked_admins() {
1453
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1454
1455
		if ( false === $other_linked_users ) {
1456
			$admins = get_users( array( 'role' => 'administrator' ) );
1457
			if ( count( $admins ) > 1 ) {
1458
				$available = array();
1459
				foreach ( $admins as $admin ) {
1460
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1461
						$available[] = $admin->ID;
1462
					}
1463
				}
1464
1465
				$count_connected_admins = count( $available );
1466
				if ( count( $available ) > 1 ) {
1467
					$other_linked_users = $count_connected_admins;
1468
				} else {
1469
					$other_linked_users = 0;
1470
				}
1471
			} else {
1472
				$other_linked_users = 0;
1473
			}
1474
1475
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1476
		}
1477
1478
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1479
	}
1480
1481
	/**
1482
	 * Return whether we are dealing with a multi network setup or not.
1483
	 * The reason we are type casting this is because we want to avoid the situation where
1484
	 * the result is false since when is_main_network_option return false it cases
1485
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1486
	 * database which could be set to anything as opposed to what this function returns.
1487
	 *
1488
	 * @param  bool $option
1489
	 *
1490
	 * @return boolean
1491
	 */
1492
	public function is_main_network_option( $option ) {
1493
		// return '1' or ''
1494
		return (string) (bool) self::is_multi_network();
1495
	}
1496
1497
	/**
1498
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1499
	 *
1500
	 * @param  string $option
1501
	 * @return boolean
1502
	 */
1503
	public function is_multisite( $option ) {
1504
		return (string) (bool) is_multisite();
1505
	}
1506
1507
	/**
1508
	 * Implemented since there is no core is multi network function
1509
	 * Right now there is no way to tell if we which network is the dominant network on the system
1510
	 *
1511
	 * @since  3.3
1512
	 * @return boolean
1513
	 */
1514 View Code Duplication
	public static function is_multi_network() {
1515
		global  $wpdb;
1516
1517
		// if we don't have a multi site setup no need to do any more
1518
		if ( ! is_multisite() ) {
1519
			return false;
1520
		}
1521
1522
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1523
		if ( $num_sites > 1 ) {
1524
			return true;
1525
		} else {
1526
			return false;
1527
		}
1528
	}
1529
1530
	/**
1531
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1532
	 *
1533
	 * @return null
1534
	 */
1535
	function update_jetpack_main_network_site_option() {
1536
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1537
	}
1538
	/**
1539
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1540
	 */
1541
	function update_jetpack_network_settings() {
1542
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1543
		// Only sync this info for the main network site.
1544
	}
1545
1546
	/**
1547
	 * Get back if the current site is single user site.
1548
	 *
1549
	 * @return bool
1550
	 */
1551 View Code Duplication
	public static function is_single_user_site() {
1552
		global $wpdb;
1553
1554
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1555
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1556
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1557
		}
1558
		return 1 === (int) $some_users;
1559
	}
1560
1561
	/**
1562
	 * Returns true if the site has file write access false otherwise.
1563
	 *
1564
	 * @return string ( '1' | '0' )
1565
	 **/
1566
	public static function file_system_write_access() {
1567
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1568
			require_once ABSPATH . 'wp-admin/includes/file.php';
1569
		}
1570
1571
		require_once ABSPATH . 'wp-admin/includes/template.php';
1572
1573
		$filesystem_method = get_filesystem_method();
1574
		if ( $filesystem_method === 'direct' ) {
1575
			return 1;
1576
		}
1577
1578
		ob_start();
1579
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1580
		ob_end_clean();
1581
		if ( $filesystem_credentials_are_stored ) {
1582
			return 1;
1583
		}
1584
		return 0;
1585
	}
1586
1587
	/**
1588
	 * Finds out if a site is using a version control system.
1589
	 *
1590
	 * @return string ( '1' | '0' )
1591
	 **/
1592
	public static function is_version_controlled() {
1593
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1594
		return (string) (int) Functions::is_version_controlled();
1595
	}
1596
1597
	/**
1598
	 * Determines whether the current theme supports featured images or not.
1599
	 *
1600
	 * @return string ( '1' | '0' )
1601
	 */
1602
	public static function featured_images_enabled() {
1603
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1604
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1605
	}
1606
1607
	/**
1608
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1609
	 *
1610
	 * @deprecated 4.7 use get_avatar_url instead.
1611
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1612
	 * @param int               $size Size of the avatar image
1613
	 * @param string            $default URL to a default image to use if no avatar is available
1614
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1615
	 *
1616
	 * @return array
1617
	 */
1618
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1619
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1620
		return get_avatar_url(
1621
			$id_or_email,
1622
			array(
1623
				'size'          => $size,
1624
				'default'       => $default,
1625
				'force_default' => $force_display,
1626
			)
1627
		);
1628
	}
1629
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1630
	/**
1631
	 * jetpack_updates is saved in the following schema:
1632
	 *
1633
	 * array (
1634
	 *      'plugins'                       => (int) Number of plugin updates available.
1635
	 *      'themes'                        => (int) Number of theme updates available.
1636
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1637
	 *      'translations'                  => (int) Number of translation updates available.
1638
	 *      'total'                         => (int) Total of all available updates.
1639
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1640
	 * )
1641
	 *
1642
	 * @return array
1643
	 */
1644
	public static function get_updates() {
1645
		$update_data = wp_get_update_data();
1646
1647
		// Stores the individual update counts as well as the total count.
1648
		if ( isset( $update_data['counts'] ) ) {
1649
			$updates = $update_data['counts'];
1650
		}
1651
1652
		// If we need to update WordPress core, let's find the latest version number.
1653 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1654
			$cur = get_preferred_from_update_core();
1655
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1656
				$updates['wp_update_version'] = $cur->current;
1657
			}
1658
		}
1659
		return isset( $updates ) ? $updates : array();
1660
	}
1661
	// phpcs:enable
1662
1663
	public static function get_update_details() {
1664
		$update_details = array(
1665
			'update_core'    => get_site_transient( 'update_core' ),
1666
			'update_plugins' => get_site_transient( 'update_plugins' ),
1667
			'update_themes'  => get_site_transient( 'update_themes' ),
1668
		);
1669
		return $update_details;
1670
	}
1671
1672
	public static function refresh_update_data() {
1673
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1674
1675
	}
1676
1677
	public static function refresh_theme_data() {
1678
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1679
	}
1680
1681
	/**
1682
	 * Is Jetpack active?
1683
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1684
	 *
1685
	 * @return bool
1686
	 */
1687
	public static function is_active() {
1688
		return self::connection()->is_active();
1689
	}
1690
1691
	/**
1692
	 * Make an API call to WordPress.com for plan status
1693
	 *
1694
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1695
	 *
1696
	 * @return bool True if plan is updated, false if no update
1697
	 */
1698
	public static function refresh_active_plan_from_wpcom() {
1699
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1700
		return Jetpack_Plan::refresh_from_wpcom();
1701
	}
1702
1703
	/**
1704
	 * Get the plan that this Jetpack site is currently using
1705
	 *
1706
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1707
	 * @return array Active Jetpack plan details.
1708
	 */
1709
	public static function get_active_plan() {
1710
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1711
		return Jetpack_Plan::get();
1712
	}
1713
1714
	/**
1715
	 * Determine whether the active plan supports a particular feature
1716
	 *
1717
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1718
	 * @return bool True if plan supports feature, false if not.
1719
	 */
1720
	public static function active_plan_supports( $feature ) {
1721
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1722
		return Jetpack_Plan::supports( $feature );
1723
	}
1724
1725
	/**
1726
	 * Deprecated: Is Jetpack in development (offline) mode?
1727
	 *
1728
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1729
	 * and themes still use it, and we do not want to flood them with notices.
1730
	 *
1731
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1732
	 *
1733
	 * @deprecated since 8.0.
1734
	 */
1735
	public static function is_development_mode() {
1736
		return ( new Status() )->is_offline_mode();
1737
	}
1738
1739
	/**
1740
	 * Whether the site is currently onboarding or not.
1741
	 * A site is considered as being onboarded if it currently has an onboarding token.
1742
	 *
1743
	 * @since 5.8
1744
	 *
1745
	 * @access public
1746
	 * @static
1747
	 *
1748
	 * @return bool True if the site is currently onboarding, false otherwise
1749
	 */
1750
	public static function is_onboarding() {
1751
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1752
	}
1753
1754
	/**
1755
	 * Determines reason for Jetpack offline mode.
1756
	 */
1757
	public static function development_mode_trigger_text() {
1758
		$status = new Status();
1759
1760
		if ( ! $status->is_offline_mode() ) {
1761
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1762
		}
1763
1764
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1765
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1766
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1767
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1768
		} elseif ( $status->is_local_site() ) {
1769
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1770
			/** This filter is documented in packages/status/src/class-status.php */
1771
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1772
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1773
		} else {
1774
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1775
		}
1776
1777
		return $notice;
1778
1779
	}
1780
	/**
1781
	 * Get Jetpack offline mode notice text and notice class.
1782
	 *
1783
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1784
	 */
1785
	public static function show_development_mode_notice() {
1786 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1787
			$notice = sprintf(
1788
				/* translators: %s is a URL */
1789
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1790
				Redirect::get_url( 'jetpack-support-development-mode' )
1791
			);
1792
1793
			$notice .= ' ' . self::development_mode_trigger_text();
1794
1795
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1796
		}
1797
1798
		// Throw up a notice if using a development version and as for feedback.
1799
		if ( self::is_development_version() ) {
1800
			/* translators: %s is a URL */
1801
			$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' ) );
1802
1803
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1804
		}
1805
		// Throw up a notice if using staging mode
1806 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1807
			/* translators: %s is a URL */
1808
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1809
1810
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1811
		}
1812
	}
1813
1814
	/**
1815
	 * Whether Jetpack's version maps to a public release, or a development version.
1816
	 */
1817
	public static function is_development_version() {
1818
		/**
1819
		 * Allows filtering whether this is a development version of Jetpack.
1820
		 *
1821
		 * This filter is especially useful for tests.
1822
		 *
1823
		 * @since 4.3.0
1824
		 *
1825
		 * @param bool $development_version Is this a develoment version of Jetpack?
1826
		 */
1827
		return (bool) apply_filters(
1828
			'jetpack_development_version',
1829
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1830
		);
1831
	}
1832
1833
	/**
1834
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1835
	 */
1836
	public static function is_user_connected( $user_id = false ) {
1837
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1838
		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...
1839
	}
1840
1841
	/**
1842
	 * Get the wpcom user data of the current|specified connected user.
1843
	 */
1844
	public static function get_connected_user_data( $user_id = null ) {
1845
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1846
		return self::connection()->get_connected_user_data( $user_id );
1847
	}
1848
1849
	/**
1850
	 * Get the wpcom email of the current|specified connected user.
1851
	 */
1852
	public static function get_connected_user_email( $user_id = null ) {
1853
		if ( ! $user_id ) {
1854
			$user_id = get_current_user_id();
1855
		}
1856
1857
		$xml = new Jetpack_IXR_Client(
1858
			array(
1859
				'user_id' => $user_id,
1860
			)
1861
		);
1862
		$xml->query( 'wpcom.getUserEmail' );
1863
		if ( ! $xml->isError() ) {
1864
			return $xml->getResponse();
1865
		}
1866
		return false;
1867
	}
1868
1869
	/**
1870
	 * Get the wpcom email of the master user.
1871
	 */
1872
	public static function get_master_user_email() {
1873
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1874
		if ( $master_user_id ) {
1875
			return self::get_connected_user_email( $master_user_id );
1876
		}
1877
		return '';
1878
	}
1879
1880
	/**
1881
	 * Whether the current user is the connection owner.
1882
	 *
1883
	 * @deprecated since 7.7
1884
	 *
1885
	 * @return bool Whether the current user is the connection owner.
1886
	 */
1887
	public function current_user_is_connection_owner() {
1888
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1889
		return self::connection()->is_connection_owner();
1890
	}
1891
1892
	/**
1893
	 * Gets current user IP address.
1894
	 *
1895
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1896
	 *
1897
	 * @return string                  Current user IP address.
1898
	 */
1899
	public static function current_user_ip( $check_all_headers = false ) {
1900
		if ( $check_all_headers ) {
1901
			foreach ( array(
1902
				'HTTP_CF_CONNECTING_IP',
1903
				'HTTP_CLIENT_IP',
1904
				'HTTP_X_FORWARDED_FOR',
1905
				'HTTP_X_FORWARDED',
1906
				'HTTP_X_CLUSTER_CLIENT_IP',
1907
				'HTTP_FORWARDED_FOR',
1908
				'HTTP_FORWARDED',
1909
				'HTTP_VIA',
1910
			) as $key ) {
1911
				if ( ! empty( $_SERVER[ $key ] ) ) {
1912
					return $_SERVER[ $key ];
1913
				}
1914
			}
1915
		}
1916
1917
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1918
	}
1919
1920
	/**
1921
	 * Synchronize connected user role changes
1922
	 */
1923
	function user_role_change( $user_id ) {
1924
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1925
		Users::user_role_change( $user_id );
1926
	}
1927
1928
	/**
1929
	 * Loads the currently active modules.
1930
	 */
1931
	public static function load_modules() {
1932
		$is_offline_mode = ( new Status() )->is_offline_mode();
1933
		if (
1934
			! self::is_active()
1935
			&& ! $is_offline_mode
1936
			&& ! self::is_onboarding()
1937
			&& (
1938
				! is_multisite()
1939
				|| ! get_site_option( 'jetpack_protect_active' )
1940
			)
1941
		) {
1942
			return;
1943
		}
1944
1945
		$version = Jetpack_Options::get_option( 'version' );
1946 View Code Duplication
		if ( ! $version ) {
1947
			$version = $old_version = JETPACK__VERSION . ':' . time();
1948
			/** This action is documented in class.jetpack.php */
1949
			do_action( 'updating_jetpack_version', $version, false );
1950
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1951
		}
1952
		list( $version ) = explode( ':', $version );
1953
1954
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1955
1956
		$modules_data = array();
1957
1958
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1959
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1960
			$updated_modules = array();
1961
			foreach ( $modules as $module ) {
1962
				$modules_data[ $module ] = self::get_module( $module );
1963
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1964
					continue;
1965
				}
1966
1967
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1968
					continue;
1969
				}
1970
1971
				$updated_modules[] = $module;
1972
			}
1973
1974
			$modules = array_diff( $modules, $updated_modules );
1975
		}
1976
1977
		foreach ( $modules as $index => $module ) {
1978
			// If we're in offline mode, disable modules requiring a connection.
1979
			if ( $is_offline_mode ) {
1980
				// Prime the pump if we need to
1981
				if ( empty( $modules_data[ $module ] ) ) {
1982
					$modules_data[ $module ] = self::get_module( $module );
1983
				}
1984
				// If the module requires a connection, but we're in local mode, don't include it.
1985
				if ( $modules_data[ $module ]['requires_connection'] ) {
1986
					continue;
1987
				}
1988
			}
1989
1990
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1991
				continue;
1992
			}
1993
1994
			if ( ! include_once self::get_module_path( $module ) ) {
1995
				unset( $modules[ $index ] );
1996
				self::update_active_modules( array_values( $modules ) );
1997
				continue;
1998
			}
1999
2000
			/**
2001
			 * Fires when a specific module is loaded.
2002
			 * The dynamic part of the hook, $module, is the module slug.
2003
			 *
2004
			 * @since 1.1.0
2005
			 */
2006
			do_action( 'jetpack_module_loaded_' . $module );
2007
		}
2008
2009
		/**
2010
		 * Fires when all the modules are loaded.
2011
		 *
2012
		 * @since 1.1.0
2013
		 */
2014
		do_action( 'jetpack_modules_loaded' );
2015
2016
		// 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.
2017
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2018
	}
2019
2020
	/**
2021
	 * Check if Jetpack's REST API compat file should be included
2022
	 *
2023
	 * @action plugins_loaded
2024
	 * @return null
2025
	 */
2026
	public function check_rest_api_compat() {
2027
		/**
2028
		 * Filters the list of REST API compat files to be included.
2029
		 *
2030
		 * @since 2.2.5
2031
		 *
2032
		 * @param array $args Array of REST API compat files to include.
2033
		 */
2034
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2035
2036
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2037
			require_once $_jetpack_rest_api_compat_include;
2038
		}
2039
	}
2040
2041
	/**
2042
	 * Gets all plugins currently active in values, regardless of whether they're
2043
	 * traditionally activated or network activated.
2044
	 *
2045
	 * @todo Store the result in core's object cache maybe?
2046
	 */
2047
	public static function get_active_plugins() {
2048
		$active_plugins = (array) get_option( 'active_plugins', array() );
2049
2050
		if ( is_multisite() ) {
2051
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2052
			// whereas active_plugins stores them in the values.
2053
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2054
			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...
2055
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2056
			}
2057
		}
2058
2059
		sort( $active_plugins );
2060
2061
		return array_unique( $active_plugins );
2062
	}
2063
2064
	/**
2065
	 * Gets and parses additional plugin data to send with the heartbeat data
2066
	 *
2067
	 * @since 3.8.1
2068
	 *
2069
	 * @return array Array of plugin data
2070
	 */
2071
	public static function get_parsed_plugin_data() {
2072
		if ( ! function_exists( 'get_plugins' ) ) {
2073
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2074
		}
2075
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2076
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2077
		$active_plugins = self::get_active_plugins();
2078
2079
		$plugins = array();
2080
		foreach ( $all_plugins as $path => $plugin_data ) {
2081
			$plugins[ $path ] = array(
2082
				'is_active' => in_array( $path, $active_plugins ),
2083
				'file'      => $path,
2084
				'name'      => $plugin_data['Name'],
2085
				'version'   => $plugin_data['Version'],
2086
				'author'    => $plugin_data['Author'],
2087
			);
2088
		}
2089
2090
		return $plugins;
2091
	}
2092
2093
	/**
2094
	 * Gets and parses theme data to send with the heartbeat data
2095
	 *
2096
	 * @since 3.8.1
2097
	 *
2098
	 * @return array Array of theme data
2099
	 */
2100
	public static function get_parsed_theme_data() {
2101
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2102
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2103
2104
		$themes = array();
2105
		foreach ( $all_themes as $slug => $theme_data ) {
2106
			$theme_headers = array();
2107
			foreach ( $header_keys as $header_key ) {
2108
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2109
			}
2110
2111
			$themes[ $slug ] = array(
2112
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2113
				'slug'            => $slug,
2114
				'theme_root'      => $theme_data->get_theme_root_uri(),
2115
				'parent'          => $theme_data->parent(),
2116
				'headers'         => $theme_headers,
2117
			);
2118
		}
2119
2120
		return $themes;
2121
	}
2122
2123
	/**
2124
	 * Checks whether a specific plugin is active.
2125
	 *
2126
	 * We don't want to store these in a static variable, in case
2127
	 * there are switch_to_blog() calls involved.
2128
	 */
2129
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2130
		return in_array( $plugin, self::get_active_plugins() );
2131
	}
2132
2133
	/**
2134
	 * Check if Jetpack's Open Graph tags should be used.
2135
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2136
	 *
2137
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2138
	 * @action plugins_loaded
2139
	 * @return null
2140
	 */
2141
	public function check_open_graph() {
2142
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2143
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2144
		}
2145
2146
		$active_plugins = self::get_active_plugins();
2147
2148
		if ( ! empty( $active_plugins ) ) {
2149
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2150
				if ( in_array( $plugin, $active_plugins ) ) {
2151
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2152
					break;
2153
				}
2154
			}
2155
		}
2156
2157
		/**
2158
		 * Allow the addition of Open Graph Meta Tags to all pages.
2159
		 *
2160
		 * @since 2.0.3
2161
		 *
2162
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2163
		 */
2164
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2165
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2166
		}
2167
	}
2168
2169
	/**
2170
	 * Check if Jetpack's Twitter tags should be used.
2171
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2172
	 *
2173
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2174
	 * @action plugins_loaded
2175
	 * @return null
2176
	 */
2177
	public function check_twitter_tags() {
2178
2179
		$active_plugins = self::get_active_plugins();
2180
2181
		if ( ! empty( $active_plugins ) ) {
2182
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2183
				if ( in_array( $plugin, $active_plugins ) ) {
2184
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2185
					break;
2186
				}
2187
			}
2188
		}
2189
2190
		/**
2191
		 * Allow Twitter Card Meta tags to be disabled.
2192
		 *
2193
		 * @since 2.6.0
2194
		 *
2195
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2196
		 */
2197
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2198
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2199
		}
2200
	}
2201
2202
	/**
2203
	 * Allows plugins to submit security reports.
2204
	 *
2205
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2206
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2207
	 * @param array  $args         See definitions above
2208
	 */
2209
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2210
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2211
	}
2212
2213
	/* Jetpack Options API */
2214
2215
	public static function get_option_names( $type = 'compact' ) {
2216
		return Jetpack_Options::get_option_names( $type );
2217
	}
2218
2219
	/**
2220
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2221
	 *
2222
	 * @param string $name    Option name
2223
	 * @param mixed  $default (optional)
2224
	 */
2225
	public static function get_option( $name, $default = false ) {
2226
		return Jetpack_Options::get_option( $name, $default );
2227
	}
2228
2229
	/**
2230
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2231
	 *
2232
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2233
	 * @param string $name  Option name
2234
	 * @param mixed  $value Option value
2235
	 */
2236
	public static function update_option( $name, $value ) {
2237
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2238
		return Jetpack_Options::update_option( $name, $value );
2239
	}
2240
2241
	/**
2242
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2243
	 *
2244
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2245
	 * @param array $array array( option name => option value, ... )
2246
	 */
2247
	public static function update_options( $array ) {
2248
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2249
		return Jetpack_Options::update_options( $array );
2250
	}
2251
2252
	/**
2253
	 * Deletes the given option.  May be passed multiple option names as an array.
2254
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2255
	 *
2256
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2257
	 * @param string|array $names
2258
	 */
2259
	public static function delete_option( $names ) {
2260
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2261
		return Jetpack_Options::delete_option( $names );
2262
	}
2263
2264
	/**
2265
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2266
	 *
2267
	 * Enters a user token into the user_tokens option
2268
	 *
2269
	 * @param int    $user_id The user id.
2270
	 * @param string $token The user token.
2271
	 * @param bool   $is_master_user Whether the user is the master user.
2272
	 * @return bool
2273
	 */
2274
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2275
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2276
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2277
	}
2278
2279
	/**
2280
	 * Returns an array of all PHP files in the specified absolute path.
2281
	 * Equivalent to glob( "$absolute_path/*.php" ).
2282
	 *
2283
	 * @param string $absolute_path The absolute path of the directory to search.
2284
	 * @return array Array of absolute paths to the PHP files.
2285
	 */
2286
	public static function glob_php( $absolute_path ) {
2287
		if ( function_exists( 'glob' ) ) {
2288
			return glob( "$absolute_path/*.php" );
2289
		}
2290
2291
		$absolute_path = untrailingslashit( $absolute_path );
2292
		$files         = array();
2293
		if ( ! $dir = @opendir( $absolute_path ) ) {
2294
			return $files;
2295
		}
2296
2297
		while ( false !== $file = readdir( $dir ) ) {
2298
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2299
				continue;
2300
			}
2301
2302
			$file = "$absolute_path/$file";
2303
2304
			if ( ! is_file( $file ) ) {
2305
				continue;
2306
			}
2307
2308
			$files[] = $file;
2309
		}
2310
2311
		closedir( $dir );
2312
2313
		return $files;
2314
	}
2315
2316
	public static function activate_new_modules( $redirect = false ) {
2317
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2318
			return;
2319
		}
2320
2321
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2322 View Code Duplication
		if ( ! $jetpack_old_version ) {
2323
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2324
			/** This action is documented in class.jetpack.php */
2325
			do_action( 'updating_jetpack_version', $version, false );
2326
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2327
		}
2328
2329
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2330
2331
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2332
			return;
2333
		}
2334
2335
		$active_modules     = self::get_active_modules();
2336
		$reactivate_modules = array();
2337
		foreach ( $active_modules as $active_module ) {
2338
			$module = self::get_module( $active_module );
2339
			if ( ! isset( $module['changed'] ) ) {
2340
				continue;
2341
			}
2342
2343
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2344
				continue;
2345
			}
2346
2347
			$reactivate_modules[] = $active_module;
2348
			self::deactivate_module( $active_module );
2349
		}
2350
2351
		$new_version = JETPACK__VERSION . ':' . time();
2352
		/** This action is documented in class.jetpack.php */
2353
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2354
		Jetpack_Options::update_options(
2355
			array(
2356
				'version'     => $new_version,
2357
				'old_version' => $jetpack_old_version,
2358
			)
2359
		);
2360
2361
		self::state( 'message', 'modules_activated' );
2362
2363
		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...
2364
2365
		if ( $redirect ) {
2366
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2367
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2368
				$page = $_GET['page'];
2369
			}
2370
2371
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2372
			exit;
2373
		}
2374
	}
2375
2376
	/**
2377
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2378
	 * Make sure to tuck away module "library" files in a sub-directory.
2379
	 */
2380
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2381
		static $modules = null;
2382
2383
		if ( ! isset( $modules ) ) {
2384
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2385
			// Use the cache if we're on the front-end and it's available...
2386
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2387
				$modules = $available_modules_option[ JETPACK__VERSION ];
2388
			} else {
2389
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2390
2391
				$modules = array();
2392
2393
				foreach ( $files as $file ) {
2394
					if ( ! $headers = self::get_module( $file ) ) {
2395
						continue;
2396
					}
2397
2398
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2399
				}
2400
2401
				Jetpack_Options::update_option(
2402
					'available_modules',
2403
					array(
2404
						JETPACK__VERSION => $modules,
2405
					)
2406
				);
2407
			}
2408
		}
2409
2410
		/**
2411
		 * Filters the array of modules available to be activated.
2412
		 *
2413
		 * @since 2.4.0
2414
		 *
2415
		 * @param array $modules Array of available modules.
2416
		 * @param string $min_version Minimum version number required to use modules.
2417
		 * @param string $max_version Maximum version number required to use modules.
2418
		 */
2419
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

Loading history...
2420
2421
		if ( ! $min_version && ! $max_version ) {
2422
			return array_keys( $mods );
2423
		}
2424
2425
		$r = array();
2426
		foreach ( $mods as $slug => $introduced ) {
2427
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2428
				continue;
2429
			}
2430
2431
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2432
				continue;
2433
			}
2434
2435
			$r[] = $slug;
2436
		}
2437
2438
		return $r;
2439
	}
2440
2441
	/**
2442
	 * Default modules loaded on activation.
2443
	 */
2444
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2445
		$return = array();
2446
2447
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2448
			$module_data = self::get_module( $module );
2449
2450
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2451
				case 'yes':
2452
					$return[] = $module;
2453
					break;
2454
				case 'public':
2455
					if ( Jetpack_Options::get_option( 'public' ) ) {
2456
						$return[] = $module;
2457
					}
2458
					break;
2459
				case 'no':
2460
				default:
2461
					break;
2462
			}
2463
		}
2464
		/**
2465
		 * Filters the array of default modules.
2466
		 *
2467
		 * @since 2.5.0
2468
		 *
2469
		 * @param array $return Array of default modules.
2470
		 * @param string $min_version Minimum version number required to use modules.
2471
		 * @param string $max_version Maximum version number required to use modules.
2472
		 */
2473
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

Loading history...
2474
	}
2475
2476
	/**
2477
	 * Checks activated modules during auto-activation to determine
2478
	 * if any of those modules are being deprecated.  If so, close
2479
	 * them out, and add any replacement modules.
2480
	 *
2481
	 * Runs at priority 99 by default.
2482
	 *
2483
	 * This is run late, so that it can still activate a module if
2484
	 * the new module is a replacement for another that the user
2485
	 * currently has active, even if something at the normal priority
2486
	 * would kibosh everything.
2487
	 *
2488
	 * @since 2.6
2489
	 * @uses jetpack_get_default_modules filter
2490
	 * @param array $modules
2491
	 * @return array
2492
	 */
2493
	function handle_deprecated_modules( $modules ) {
2494
		$deprecated_modules = array(
2495
			'debug'            => null,  // Closed out and moved to the debugger library.
2496
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2497
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2498
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2499
		);
2500
2501
		// Don't activate SSO if they never completed activating WPCC.
2502
		if ( self::is_module_active( 'wpcc' ) ) {
2503
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2504
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2505
				$deprecated_modules['wpcc'] = null;
2506
			}
2507
		}
2508
2509
		foreach ( $deprecated_modules as $module => $replacement ) {
2510
			if ( self::is_module_active( $module ) ) {
2511
				self::deactivate_module( $module );
2512
				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...
2513
					$modules[] = $replacement;
2514
				}
2515
			}
2516
		}
2517
2518
		return array_unique( $modules );
2519
	}
2520
2521
	/**
2522
	 * Checks activated plugins during auto-activation to determine
2523
	 * if any of those plugins are in the list with a corresponding module
2524
	 * that is not compatible with the plugin. The module will not be allowed
2525
	 * to auto-activate.
2526
	 *
2527
	 * @since 2.6
2528
	 * @uses jetpack_get_default_modules filter
2529
	 * @param array $modules
2530
	 * @return array
2531
	 */
2532
	function filter_default_modules( $modules ) {
2533
2534
		$active_plugins = self::get_active_plugins();
2535
2536
		if ( ! empty( $active_plugins ) ) {
2537
2538
			// For each module we'd like to auto-activate...
2539
			foreach ( $modules as $key => $module ) {
2540
				// If there are potential conflicts for it...
2541
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2542
					// For each potential conflict...
2543
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2544
						// If that conflicting plugin is active...
2545
						if ( in_array( $plugin, $active_plugins ) ) {
2546
							// Remove that item from being auto-activated.
2547
							unset( $modules[ $key ] );
2548
						}
2549
					}
2550
				}
2551
			}
2552
		}
2553
2554
		return $modules;
2555
	}
2556
2557
	/**
2558
	 * Extract a module's slug from its full path.
2559
	 */
2560
	public static function get_module_slug( $file ) {
2561
		return str_replace( '.php', '', basename( $file ) );
2562
	}
2563
2564
	/**
2565
	 * Generate a module's path from its slug.
2566
	 */
2567
	public static function get_module_path( $slug ) {
2568
		/**
2569
		 * Filters the path of a modules.
2570
		 *
2571
		 * @since 7.4.0
2572
		 *
2573
		 * @param array $return The absolute path to a module's root php file
2574
		 * @param string $slug The module slug
2575
		 */
2576
		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...
2577
	}
2578
2579
	/**
2580
	 * Load module data from module file. Headers differ from WordPress
2581
	 * plugin headers to avoid them being identified as standalone
2582
	 * plugins on the WordPress plugins page.
2583
	 */
2584
	public static function get_module( $module ) {
2585
		$headers = array(
2586
			'name'                      => 'Module Name',
2587
			'description'               => 'Module Description',
2588
			'sort'                      => 'Sort Order',
2589
			'recommendation_order'      => 'Recommendation Order',
2590
			'introduced'                => 'First Introduced',
2591
			'changed'                   => 'Major Changes In',
2592
			'deactivate'                => 'Deactivate',
2593
			'free'                      => 'Free',
2594
			'requires_connection'       => 'Requires Connection',
2595
			'auto_activate'             => 'Auto Activate',
2596
			'module_tags'               => 'Module Tags',
2597
			'feature'                   => 'Feature',
2598
			'additional_search_queries' => 'Additional Search Queries',
2599
			'plan_classes'              => 'Plans',
2600
		);
2601
2602
		$file = self::get_module_path( self::get_module_slug( $module ) );
2603
2604
		$mod = self::get_file_data( $file, $headers );
2605
		if ( empty( $mod['name'] ) ) {
2606
			return false;
2607
		}
2608
2609
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2610
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2611
		$mod['deactivate']           = empty( $mod['deactivate'] );
2612
		$mod['free']                 = empty( $mod['free'] );
2613
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2614
2615
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2616
			$mod['auto_activate'] = 'No';
2617
		} else {
2618
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2619
		}
2620
2621
		if ( $mod['module_tags'] ) {
2622
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2623
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2624
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2625
		} else {
2626
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2627
		}
2628
2629 View Code Duplication
		if ( $mod['plan_classes'] ) {
2630
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2631
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2632
		} else {
2633
			$mod['plan_classes'] = array( 'free' );
2634
		}
2635
2636 View Code Duplication
		if ( $mod['feature'] ) {
2637
			$mod['feature'] = explode( ',', $mod['feature'] );
2638
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2639
		} else {
2640
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2641
		}
2642
2643
		/**
2644
		 * Filters the feature array on a module.
2645
		 *
2646
		 * This filter allows you to control where each module is filtered: Recommended,
2647
		 * and the default "Other" listing.
2648
		 *
2649
		 * @since 3.5.0
2650
		 *
2651
		 * @param array   $mod['feature'] The areas to feature this module:
2652
		 *     'Recommended' shows on the main Jetpack admin screen.
2653
		 *     'Other' should be the default if no other value is in the array.
2654
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2655
		 * @param array   $mod All the currently assembled module data.
2656
		 */
2657
		$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...
2658
2659
		/**
2660
		 * Filter the returned data about a module.
2661
		 *
2662
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2663
		 * so please be careful.
2664
		 *
2665
		 * @since 3.6.0
2666
		 *
2667
		 * @param array   $mod    The details of the requested module.
2668
		 * @param string  $module The slug of the module, e.g. sharedaddy
2669
		 * @param string  $file   The path to the module source file.
2670
		 */
2671
		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...
2672
	}
2673
2674
	/**
2675
	 * Like core's get_file_data implementation, but caches the result.
2676
	 */
2677
	public static function get_file_data( $file, $headers ) {
2678
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2679
		$file_name = basename( $file );
2680
2681
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2682
2683
		$file_data_option = get_transient( $cache_key );
2684
2685
		if ( ! is_array( $file_data_option ) ) {
2686
			delete_transient( $cache_key );
2687
			$file_data_option = false;
2688
		}
2689
2690
		if ( false === $file_data_option ) {
2691
			$file_data_option = array();
2692
		}
2693
2694
		$key           = md5( $file_name . serialize( $headers ) );
2695
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2696
2697
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2698
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2699
			return $file_data_option[ $key ];
2700
		}
2701
2702
		$data = get_file_data( $file, $headers );
2703
2704
		$file_data_option[ $key ] = $data;
2705
2706
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2707
2708
		return $data;
2709
	}
2710
2711
	/**
2712
	 * Return translated module tag.
2713
	 *
2714
	 * @param string $tag Tag as it appears in each module heading.
2715
	 *
2716
	 * @return mixed
2717
	 */
2718
	public static function translate_module_tag( $tag ) {
2719
		return jetpack_get_module_i18n_tag( $tag );
2720
	}
2721
2722
	/**
2723
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2724
	 *
2725
	 * @since 3.9.2
2726
	 *
2727
	 * @param array $modules
2728
	 *
2729
	 * @return string|void
2730
	 */
2731
	public static function get_translated_modules( $modules ) {
2732
		foreach ( $modules as $index => $module ) {
2733
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2734
			if ( isset( $module['name'] ) ) {
2735
				$modules[ $index ]['name'] = $i18n_module['name'];
2736
			}
2737
			if ( isset( $module['description'] ) ) {
2738
				$modules[ $index ]['description']       = $i18n_module['description'];
2739
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2740
			}
2741
		}
2742
		return $modules;
2743
	}
2744
2745
	/**
2746
	 * Get a list of activated modules as an array of module slugs.
2747
	 */
2748
	public static function get_active_modules() {
2749
		$active = Jetpack_Options::get_option( 'active_modules' );
2750
2751
		if ( ! is_array( $active ) ) {
2752
			$active = array();
2753
		}
2754
2755
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2756
			$active[] = 'vaultpress';
2757
		} else {
2758
			$active = array_diff( $active, array( 'vaultpress' ) );
2759
		}
2760
2761
		// If protect is active on the main site of a multisite, it should be active on all sites.
2762
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2763
			$active[] = 'protect';
2764
		}
2765
2766
		/**
2767
		 * Allow filtering of the active modules.
2768
		 *
2769
		 * Gives theme and plugin developers the power to alter the modules that
2770
		 * are activated on the fly.
2771
		 *
2772
		 * @since 5.8.0
2773
		 *
2774
		 * @param array $active Array of active module slugs.
2775
		 */
2776
		$active = apply_filters( 'jetpack_active_modules', $active );
2777
2778
		return array_unique( $active );
2779
	}
2780
2781
	/**
2782
	 * Check whether or not a Jetpack module is active.
2783
	 *
2784
	 * @param string $module The slug of a Jetpack module.
2785
	 * @return bool
2786
	 *
2787
	 * @static
2788
	 */
2789
	public static function is_module_active( $module ) {
2790
		return in_array( $module, self::get_active_modules() );
2791
	}
2792
2793
	public static function is_module( $module ) {
2794
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2795
	}
2796
2797
	/**
2798
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2799
	 *
2800
	 * @param bool $catch True to start catching, False to stop.
2801
	 *
2802
	 * @static
2803
	 */
2804
	public static function catch_errors( $catch ) {
2805
		static $display_errors, $error_reporting;
2806
2807
		if ( $catch ) {
2808
			$display_errors  = @ini_set( 'display_errors', 1 );
2809
			$error_reporting = @error_reporting( E_ALL );
2810
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2811
		} else {
2812
			@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...
2813
			@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...
2814
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2815
		}
2816
	}
2817
2818
	/**
2819
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2820
	 */
2821
	public static function catch_errors_on_shutdown() {
2822
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2823
	}
2824
2825
	/**
2826
	 * Rewrite any string to make paths easier to read.
2827
	 *
2828
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2829
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2830
	 *
2831
	 * @param $string
2832
	 * @return mixed
2833
	 */
2834
	public static function alias_directories( $string ) {
2835
		// ABSPATH has a trailing slash.
2836
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2837
		// WP_CONTENT_DIR does not have a trailing slash.
2838
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2839
2840
		return $string;
2841
	}
2842
2843
	public static function activate_default_modules(
2844
		$min_version = false,
2845
		$max_version = false,
2846
		$other_modules = array(),
2847
		$redirect = null,
2848
		$send_state_messages = null
2849
	) {
2850
		$jetpack = self::init();
2851
2852
		if ( is_null( $redirect ) ) {
2853
			if (
2854
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2855
			||
2856
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2857
			||
2858
				( defined( 'WP_CLI' ) && WP_CLI )
2859
			||
2860
				( defined( 'DOING_CRON' ) && DOING_CRON )
2861
			||
2862
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2863
			) {
2864
				$redirect = false;
2865
			} elseif ( is_admin() ) {
2866
				$redirect = true;
2867
			} else {
2868
				$redirect = false;
2869
			}
2870
		}
2871
2872
		if ( is_null( $send_state_messages ) ) {
2873
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2874
		}
2875
2876
		$modules = self::get_default_modules( $min_version, $max_version );
2877
		$modules = array_merge( $other_modules, $modules );
2878
2879
		// Look for standalone plugins and disable if active.
2880
2881
		$to_deactivate = array();
2882
		foreach ( $modules as $module ) {
2883
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2884
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2885
			}
2886
		}
2887
2888
		$deactivated = array();
2889
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2890
			list( $probable_file, $probable_title ) = $deactivate_me;
2891
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2892
				$deactivated[] = $module;
2893
			}
2894
		}
2895
2896
		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...
2897
			if ( $send_state_messages ) {
2898
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2899
			}
2900
2901
			if ( $redirect ) {
2902
				$url = add_query_arg(
2903
					array(
2904
						'action'   => 'activate_default_modules',
2905
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2906
					),
2907
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2908
				);
2909
				wp_safe_redirect( $url );
2910
				exit;
2911
			}
2912
		}
2913
2914
		/**
2915
		 * Fires before default modules are activated.
2916
		 *
2917
		 * @since 1.9.0
2918
		 *
2919
		 * @param string $min_version Minimum version number required to use modules.
2920
		 * @param string $max_version Maximum version number required to use modules.
2921
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2922
		 */
2923
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2924
2925
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2926
		if ( $send_state_messages ) {
2927
			self::restate();
2928
			self::catch_errors( true );
2929
		}
2930
2931
		$active = self::get_active_modules();
2932
2933
		foreach ( $modules as $module ) {
2934
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2935
				$active[] = $module;
2936
				self::update_active_modules( $active );
2937
				continue;
2938
			}
2939
2940
			if ( $send_state_messages && in_array( $module, $active ) ) {
2941
				$module_info = self::get_module( $module );
2942 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2943
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2944
					if ( $active_state = self::state( $state ) ) {
2945
						$active_state = explode( ',', $active_state );
2946
					} else {
2947
						$active_state = array();
2948
					}
2949
					$active_state[] = $module;
2950
					self::state( $state, implode( ',', $active_state ) );
2951
				}
2952
				continue;
2953
			}
2954
2955
			$file = self::get_module_path( $module );
2956
			if ( ! file_exists( $file ) ) {
2957
				continue;
2958
			}
2959
2960
			// we'll override this later if the plugin can be included without fatal error
2961
			if ( $redirect ) {
2962
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2963
			}
2964
2965
			if ( $send_state_messages ) {
2966
				self::state( 'error', 'module_activation_failed' );
2967
				self::state( 'module', $module );
2968
			}
2969
2970
			ob_start();
2971
			require_once $file;
2972
2973
			$active[] = $module;
2974
2975 View Code Duplication
			if ( $send_state_messages ) {
2976
2977
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2978
				if ( $active_state = self::state( $state ) ) {
2979
					$active_state = explode( ',', $active_state );
2980
				} else {
2981
					$active_state = array();
2982
				}
2983
				$active_state[] = $module;
2984
				self::state( $state, implode( ',', $active_state ) );
2985
			}
2986
2987
			self::update_active_modules( $active );
2988
2989
			ob_end_clean();
2990
		}
2991
2992
		if ( $send_state_messages ) {
2993
			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...
2994
			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...
2995
		}
2996
2997
		self::catch_errors( false );
2998
		/**
2999
		 * Fires when default modules are activated.
3000
		 *
3001
		 * @since 1.9.0
3002
		 *
3003
		 * @param string $min_version Minimum version number required to use modules.
3004
		 * @param string $max_version Maximum version number required to use modules.
3005
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3006
		 */
3007
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
3008
	}
3009
3010
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3011
		/**
3012
		 * Fires before a module is activated.
3013
		 *
3014
		 * @since 2.6.0
3015
		 *
3016
		 * @param string $module Module slug.
3017
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3018
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3019
		 */
3020
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3021
3022
		$jetpack = self::init();
3023
3024
		if ( ! strlen( $module ) ) {
3025
			return false;
3026
		}
3027
3028
		if ( ! self::is_module( $module ) ) {
3029
			return false;
3030
		}
3031
3032
		// If it's already active, then don't do it again
3033
		$active = self::get_active_modules();
3034
		foreach ( $active as $act ) {
3035
			if ( $act == $module ) {
3036
				return true;
3037
			}
3038
		}
3039
3040
		$module_data = self::get_module( $module );
3041
3042
		$is_offline_mode = ( new Status() )->is_offline_mode();
3043
		if ( ! self::is_active() ) {
3044
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3045
				return false;
3046
			}
3047
3048
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3049
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3050
				return false;
3051
			}
3052
		}
3053
3054
		// Check and see if the old plugin is active
3055
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3056
			// Deactivate the old plugin
3057
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3058
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3059
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3060
				self::state( 'deactivated_plugins', $module );
3061
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3062
				exit;
3063
			}
3064
		}
3065
3066
		// Protect won't work with mis-configured IPs
3067
		if ( 'protect' === $module ) {
3068
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3069
			if ( ! jetpack_protect_get_ip() ) {
3070
				self::state( 'message', 'protect_misconfigured_ip' );
3071
				return false;
3072
			}
3073
		}
3074
3075
		if ( ! Jetpack_Plan::supports( $module ) ) {
3076
			return false;
3077
		}
3078
3079
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3080
		self::state( 'module', $module );
3081
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3082
3083
		self::catch_errors( true );
3084
		ob_start();
3085
		require self::get_module_path( $module );
3086
		/** This action is documented in class.jetpack.php */
3087
		do_action( 'jetpack_activate_module', $module );
3088
		$active[] = $module;
3089
		self::update_active_modules( $active );
3090
3091
		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...
3092
		ob_end_clean();
3093
		self::catch_errors( false );
3094
3095
		if ( $redirect ) {
3096
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3097
		}
3098
		if ( $exit ) {
3099
			exit;
3100
		}
3101
		return true;
3102
	}
3103
3104
	function activate_module_actions( $module ) {
3105
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3106
	}
3107
3108
	public static function deactivate_module( $module ) {
3109
		/**
3110
		 * Fires when a module is deactivated.
3111
		 *
3112
		 * @since 1.9.0
3113
		 *
3114
		 * @param string $module Module slug.
3115
		 */
3116
		do_action( 'jetpack_pre_deactivate_module', $module );
3117
3118
		$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...
3119
3120
		$active = self::get_active_modules();
3121
		$new    = array_filter( array_diff( $active, (array) $module ) );
3122
3123
		return self::update_active_modules( $new );
3124
	}
3125
3126
	public static function enable_module_configurable( $module ) {
3127
		$module = self::get_module_slug( $module );
3128
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3129
	}
3130
3131
	/**
3132
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3133
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3134
	 *
3135
	 * @param string $module Module slug
3136
	 * @return string $url module configuration URL
3137
	 */
3138
	public static function module_configuration_url( $module ) {
3139
		$module      = self::get_module_slug( $module );
3140
		$default_url = self::admin_url() . "#/settings?term=$module";
3141
		/**
3142
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3143
		 *
3144
		 * @since 6.9.0
3145
		 *
3146
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3147
		 */
3148
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3149
3150
		return $url;
3151
	}
3152
3153
	/* Installation */
3154
	public static function bail_on_activation( $message, $deactivate = true ) {
3155
		?>
3156
<!doctype html>
3157
<html>
3158
<head>
3159
<meta charset="<?php bloginfo( 'charset' ); ?>">
3160
<style>
3161
* {
3162
	text-align: center;
3163
	margin: 0;
3164
	padding: 0;
3165
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3166
}
3167
p {
3168
	margin-top: 1em;
3169
	font-size: 18px;
3170
}
3171
</style>
3172
<body>
3173
<p><?php echo esc_html( $message ); ?></p>
3174
</body>
3175
</html>
3176
		<?php
3177
		if ( $deactivate ) {
3178
			$plugins = get_option( 'active_plugins' );
3179
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3180
			$update  = false;
3181
			foreach ( $plugins as $i => $plugin ) {
3182
				if ( $plugin === $jetpack ) {
3183
					$plugins[ $i ] = false;
3184
					$update        = true;
3185
				}
3186
			}
3187
3188
			if ( $update ) {
3189
				update_option( 'active_plugins', array_filter( $plugins ) );
3190
			}
3191
		}
3192
		exit;
3193
	}
3194
3195
	/**
3196
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3197
	 *
3198
	 * @static
3199
	 */
3200
	public static function plugin_activation( $network_wide ) {
3201
		Jetpack_Options::update_option( 'activated', 1 );
3202
3203
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3204
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3205
		}
3206
3207
		if ( $network_wide ) {
3208
			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...
3209
		}
3210
3211
		// For firing one-off events (notices) immediately after activation
3212
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3213
3214
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3215
3216
		Health::on_jetpack_activated();
3217
3218
		self::plugin_initialize();
3219
	}
3220
3221
	public static function get_activation_source( $referer_url ) {
3222
3223
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3224
			return array( 'wp-cli', null );
3225
		}
3226
3227
		$referer = wp_parse_url( $referer_url );
3228
3229
		$source_type  = 'unknown';
3230
		$source_query = null;
3231
3232
		if ( ! is_array( $referer ) ) {
3233
			return array( $source_type, $source_query );
3234
		}
3235
3236
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3237
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3238
3239
		if ( isset( $referer['query'] ) ) {
3240
			parse_str( $referer['query'], $query_parts );
3241
		} else {
3242
			$query_parts = array();
3243
		}
3244
3245
		if ( $plugins_path === $referer['path'] ) {
3246
			$source_type = 'list';
3247
		} elseif ( $plugins_install_path === $referer['path'] ) {
3248
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3249
			switch ( $tab ) {
3250
				case 'popular':
3251
					$source_type = 'popular';
3252
					break;
3253
				case 'recommended':
3254
					$source_type = 'recommended';
3255
					break;
3256
				case 'favorites':
3257
					$source_type = 'favorites';
3258
					break;
3259
				case 'search':
3260
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3261
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3262
					break;
3263
				default:
3264
					$source_type = 'featured';
3265
			}
3266
		}
3267
3268
		return array( $source_type, $source_query );
3269
	}
3270
3271
	/**
3272
	 * Runs before bumping version numbers up to a new version
3273
	 *
3274
	 * @param string $version    Version:timestamp.
3275
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3276
	 */
3277
	public static function do_version_bump( $version, $old_version ) {
3278
		if ( $old_version ) { // For existing Jetpack installations.
3279
3280
			// If a front end page is visited after the update, the 'wp' action will fire.
3281
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3282
3283
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3284
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3285
		}
3286
	}
3287
3288
	/**
3289
	 * Sets the display_update_modal state.
3290
	 */
3291
	public static function set_update_modal_display() {
3292
		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...
3293
	}
3294
3295
	/**
3296
	 * Sets the internal version number and activation state.
3297
	 *
3298
	 * @static
3299
	 */
3300
	public static function plugin_initialize() {
3301
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3302
			Jetpack_Options::update_option( 'activated', 2 );
3303
		}
3304
3305 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3306
			$version = $old_version = JETPACK__VERSION . ':' . time();
3307
			/** This action is documented in class.jetpack.php */
3308
			do_action( 'updating_jetpack_version', $version, false );
3309
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3310
		}
3311
3312
		self::load_modules();
3313
3314
		Jetpack_Options::delete_option( 'do_activate' );
3315
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3316
	}
3317
3318
	/**
3319
	 * Removes all connection options
3320
	 *
3321
	 * @static
3322
	 */
3323
	public static function plugin_deactivation() {
3324
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3325
		$tracking = new Tracking();
3326
		$tracking->record_user_event( 'deactivate_plugin', array() );
3327
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3328
			Jetpack_Network::init()->deactivate();
3329
		} else {
3330
			self::disconnect( false );
3331
			// Jetpack_Heartbeat::init()->deactivate();
3332
		}
3333
	}
3334
3335
	/**
3336
	 * Disconnects from the Jetpack servers.
3337
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3338
	 *
3339
	 * @static
3340
	 */
3341
	public static function disconnect( $update_activated_state = true ) {
3342
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3343
3344
		$connection = self::connection();
3345
		$connection->clean_nonces( true );
3346
3347
		// If the site is in an IDC because sync is not allowed,
3348
		// let's make sure to not disconnect the production site.
3349
		if ( ! self::validate_sync_error_idc_option() ) {
3350
			$tracking = new Tracking();
3351
			$tracking->record_user_event( 'disconnect_site', array() );
3352
3353
			$connection->disconnect_site_wpcom( true );
3354
		}
3355
3356
		$connection->delete_all_connection_tokens( true );
3357
		Jetpack_IDC::clear_all_idc_options();
3358
3359
		if ( $update_activated_state ) {
3360
			Jetpack_Options::update_option( 'activated', 4 );
3361
		}
3362
3363
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3364
			// Check then record unique disconnection if site has never been disconnected previously
3365
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3366
				$jetpack_unique_connection['disconnected'] = 1;
3367
			} else {
3368
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3369
					// track unique disconnect
3370
					$jetpack = self::init();
3371
3372
					$jetpack->stat( 'connections', 'unique-disconnect' );
3373
					$jetpack->do_stats( 'server_side' );
3374
				}
3375
				// increment number of times disconnected
3376
				$jetpack_unique_connection['disconnected'] += 1;
3377
			}
3378
3379
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3380
		}
3381
3382
		// Delete all the sync related data. Since it could be taking up space.
3383
		Sender::get_instance()->uninstall();
3384
3385
	}
3386
3387
	/**
3388
	 * Unlinks the current user from the linked WordPress.com user.
3389
	 *
3390
	 * @deprecated since 7.7
3391
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3392
	 *
3393
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|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...
3394
	 * @return Boolean Whether the disconnection of the user was successful.
3395
	 */
3396
	public static function unlink_user( $user_id = null ) {
3397
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3398
		return Connection_Manager::disconnect_user( $user_id );
3399
	}
3400
3401
	/**
3402
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3403
	 */
3404
	public static function try_registration() {
3405
		$terms_of_service = new Terms_Of_Service();
3406
		// The user has agreed to the TOS at some point by now.
3407
		$terms_of_service->agree();
3408
3409
		// Let's get some testing in beta versions and such.
3410
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3411
			// Before attempting to connect, let's make sure that the domains are viable.
3412
			$domains_to_check = array_unique(
3413
				array(
3414
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3415
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3416
				)
3417
			);
3418
			foreach ( $domains_to_check as $domain ) {
3419
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3418 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...
3420
				if ( is_wp_error( $result ) ) {
3421
					return $result;
3422
				}
3423
			}
3424
		}
3425
3426
		$result = self::register();
3427
3428
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3429
		if ( ! $result || is_wp_error( $result ) ) {
3430
			return $result;
3431
		} else {
3432
			return true;
3433
		}
3434
	}
3435
3436
	/**
3437
	 * Tracking an internal event log. Try not to put too much chaff in here.
3438
	 *
3439
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3440
	 */
3441
	public static function log( $code, $data = null ) {
3442
		// only grab the latest 200 entries
3443
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3444
3445
		// Append our event to the log
3446
		$log_entry = array(
3447
			'time'    => time(),
3448
			'user_id' => get_current_user_id(),
3449
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3450
			'code'    => $code,
3451
		);
3452
		// Don't bother storing it unless we've got some.
3453
		if ( ! is_null( $data ) ) {
3454
			$log_entry['data'] = $data;
3455
		}
3456
		$log[] = $log_entry;
3457
3458
		// Try add_option first, to make sure it's not autoloaded.
3459
		// @todo: Add an add_option method to Jetpack_Options
3460
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3461
			Jetpack_Options::update_option( 'log', $log );
3462
		}
3463
3464
		/**
3465
		 * Fires when Jetpack logs an internal event.
3466
		 *
3467
		 * @since 3.0.0
3468
		 *
3469
		 * @param array $log_entry {
3470
		 *  Array of details about the log entry.
3471
		 *
3472
		 *  @param string time Time of the event.
3473
		 *  @param int user_id ID of the user who trigerred the event.
3474
		 *  @param int blog_id Jetpack Blog ID.
3475
		 *  @param string code Unique name for the event.
3476
		 *  @param string data Data about the event.
3477
		 * }
3478
		 */
3479
		do_action( 'jetpack_log_entry', $log_entry );
3480
	}
3481
3482
	/**
3483
	 * Get the internal event log.
3484
	 *
3485
	 * @param $event (string) - only return the specific log events
3486
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3487
	 *
3488
	 * @return array of log events || WP_Error for invalid params
3489
	 */
3490
	public static function get_log( $event = false, $num = false ) {
3491
		if ( $event && ! is_string( $event ) ) {
3492
			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...
3493
		}
3494
3495
		if ( $num && ! is_numeric( $num ) ) {
3496
			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...
3497
		}
3498
3499
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3500
3501
		// If nothing set - act as it did before, otherwise let's start customizing the output
3502
		if ( ! $num && ! $event ) {
3503
			return $entire_log;
3504
		} else {
3505
			$entire_log = array_reverse( $entire_log );
3506
		}
3507
3508
		$custom_log_output = array();
3509
3510
		if ( $event ) {
3511
			foreach ( $entire_log as $log_event ) {
3512
				if ( $event == $log_event['code'] ) {
3513
					$custom_log_output[] = $log_event;
3514
				}
3515
			}
3516
		} else {
3517
			$custom_log_output = $entire_log;
3518
		}
3519
3520
		if ( $num ) {
3521
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3522
		}
3523
3524
		return $custom_log_output;
3525
	}
3526
3527
	/**
3528
	 * Log modification of important settings.
3529
	 */
3530
	public static function log_settings_change( $option, $old_value, $value ) {
3531
		switch ( $option ) {
3532
			case 'jetpack_sync_non_public_post_stati':
3533
				self::log( $option, $value );
3534
				break;
3535
		}
3536
	}
3537
3538
	/**
3539
	 * Return stat data for WPCOM sync
3540
	 */
3541
	public static function get_stat_data( $encode = true, $extended = true ) {
3542
		$data = Jetpack_Heartbeat::generate_stats_array();
3543
3544
		if ( $extended ) {
3545
			$additional_data = self::get_additional_stat_data();
3546
			$data            = array_merge( $data, $additional_data );
3547
		}
3548
3549
		if ( $encode ) {
3550
			return json_encode( $data );
3551
		}
3552
3553
		return $data;
3554
	}
3555
3556
	/**
3557
	 * Get additional stat data to sync to WPCOM
3558
	 */
3559
	public static function get_additional_stat_data( $prefix = '' ) {
3560
		$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...
3561
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3562
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3563
		$return[ "{$prefix}site-count" ]    = 0;
3564
3565
		if ( function_exists( 'get_blog_count' ) ) {
3566
			$return[ "{$prefix}site-count" ] = get_blog_count();
3567
		}
3568
		return $return;
3569
	}
3570
3571
	private static function get_site_user_count() {
3572
		global $wpdb;
3573
3574
		if ( function_exists( 'wp_is_large_network' ) ) {
3575
			if ( wp_is_large_network( 'users' ) ) {
3576
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3577
			}
3578
		}
3579
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3580
			// It wasn't there, so regenerate the data and save the transient
3581
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3582
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3583
		}
3584
		return $user_count;
3585
	}
3586
3587
	/* Admin Pages */
3588
3589
	function admin_init() {
3590
		// If the plugin is not connected, display a connect message.
3591
		if (
3592
			// the plugin was auto-activated and needs its candy
3593
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3594
		||
3595
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3596
			! Jetpack_Options::get_option( 'activated' )
3597
		) {
3598
			self::plugin_initialize();
3599
		}
3600
3601
		$is_offline_mode = ( new Status() )->is_offline_mode();
3602
		if ( ! self::is_active() && ! $is_offline_mode ) {
3603
			Jetpack_Connection_Banner::init();
3604
			/** Already documented in automattic/jetpack-connection::src/class-client.php */
3605
		} elseif ( ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) && ! apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
3606
			// Upgrade: 1.1 -> 1.1.1
3607
			// Check and see if host can verify the Jetpack servers' SSL certificate
3608
			$args = array();
3609
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3610
		}
3611
3612
		Jetpack_Wizard_Banner::init();
3613
3614
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3615
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3616
		}
3617
3618
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3619
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3620
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3621
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3622
3623
		if ( self::is_active() || $is_offline_mode ) {
3624
			// Artificially throw errors in certain specific cases during plugin activation.
3625
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3626
		}
3627
3628
		// Add custom column in wp-admin/users.php to show whether user is linked.
3629
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3630
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3631
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3632
	}
3633
3634
	function admin_body_class( $admin_body_class = '' ) {
3635
		$classes = explode( ' ', trim( $admin_body_class ) );
3636
3637
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3638
3639
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3640
		return " $admin_body_class ";
3641
	}
3642
3643
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3644
		return $admin_body_class . ' jetpack-pagestyles ';
3645
	}
3646
3647
	/**
3648
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3649
	 * This function artificially throws errors for such cases (per a specific list).
3650
	 *
3651
	 * @param string $plugin The activated plugin.
3652
	 */
3653
	function throw_error_on_activate_plugin( $plugin ) {
3654
		$active_modules = self::get_active_modules();
3655
3656
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3657
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3658
			$throw = false;
3659
3660
			// Try and make sure it really was the stats plugin
3661
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3662
				if ( 'stats.php' == basename( $plugin ) ) {
3663
					$throw = true;
3664
				}
3665
			} else {
3666
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3667
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3668
					$throw = true;
3669
				}
3670
			}
3671
3672
			if ( $throw ) {
3673
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3674
			}
3675
		}
3676
	}
3677
3678
	function intercept_plugin_error_scrape_init() {
3679
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3680
	}
3681
3682
	function intercept_plugin_error_scrape( $action, $result ) {
3683
		if ( ! $result ) {
3684
			return;
3685
		}
3686
3687
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3688
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3689
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3690
			}
3691
		}
3692
	}
3693
3694
	/**
3695
	 * Register the remote file upload request handlers, if needed.
3696
	 *
3697
	 * @access public
3698
	 */
3699
	public function add_remote_request_handlers() {
3700
		// Remote file uploads are allowed only via AJAX requests.
3701
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3702
			return;
3703
		}
3704
3705
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3706
		$remote_request_actions = array(
3707
			'jetpack_upload_file',
3708
			'jetpack_update_file',
3709
		);
3710
3711
		// phpcs:ignore WordPress.Security.NonceVerification
3712
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3713
			return;
3714
		}
3715
3716
		// Require Jetpack authentication for the remote file upload AJAX requests.
3717
		if ( ! $this->connection_manager ) {
3718
			$this->connection_manager = new Connection_Manager();
3719
		}
3720
3721
		$this->connection_manager->require_jetpack_authentication();
3722
3723
		// Register the remote file upload AJAX handlers.
3724
		foreach ( $remote_request_actions as $action ) {
3725
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3726
		}
3727
	}
3728
3729
	/**
3730
	 * Handler for Jetpack remote file uploads.
3731
	 *
3732
	 * @access public
3733
	 */
3734
	public function remote_request_handlers() {
3735
		$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...
3736
3737
		switch ( current_filter() ) {
3738
			case 'wp_ajax_nopriv_jetpack_upload_file':
3739
				$response = $this->upload_handler();
3740
				break;
3741
3742
			case 'wp_ajax_nopriv_jetpack_update_file':
3743
				$response = $this->upload_handler( true );
3744
				break;
3745
			default:
3746
				$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...
3747
				break;
3748
		}
3749
3750
		if ( ! $response ) {
3751
			$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...
3752
		}
3753
3754
		if ( is_wp_error( $response ) ) {
3755
			$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...
3756
			$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...
3757
			$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...
3758
3759
			if ( ! is_int( $status_code ) ) {
3760
				$status_code = 400;
3761
			}
3762
3763
			status_header( $status_code );
3764
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3765
		}
3766
3767
		status_header( 200 );
3768
		if ( true === $response ) {
3769
			exit;
3770
		}
3771
3772
		die( json_encode( (object) $response ) );
3773
	}
3774
3775
	/**
3776
	 * Uploads a file gotten from the global $_FILES.
3777
	 * If `$update_media_item` is true and `post_id` is defined
3778
	 * the attachment file of the media item (gotten through of the post_id)
3779
	 * will be updated instead of add a new one.
3780
	 *
3781
	 * @param  boolean $update_media_item - update media attachment
3782
	 * @return array - An array describing the uploadind files process
3783
	 */
3784
	function upload_handler( $update_media_item = false ) {
3785
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3786
			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...
3787
		}
3788
3789
		$user = wp_authenticate( '', '' );
3790
		if ( ! $user || is_wp_error( $user ) ) {
3791
			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...
3792
		}
3793
3794
		wp_set_current_user( $user->ID );
3795
3796
		if ( ! current_user_can( 'upload_files' ) ) {
3797
			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...
3798
		}
3799
3800
		if ( empty( $_FILES ) ) {
3801
			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...
3802
		}
3803
3804
		foreach ( array_keys( $_FILES ) as $files_key ) {
3805
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3806
				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...
3807
			}
3808
		}
3809
3810
		$media_keys = array_keys( $_FILES['media'] );
3811
3812
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
3813
		if ( ! $token || is_wp_error( $token ) ) {
3814
			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...
3815
		}
3816
3817
		$uploaded_files = array();
3818
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3819
		unset( $GLOBALS['post'] );
3820
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3821
			$file = array();
3822
			foreach ( $media_keys as $media_key ) {
3823
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3824
			}
3825
3826
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3827
3828
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3829
			if ( $hmac_provided !== $hmac_file ) {
3830
				$uploaded_files[ $index ] = (object) array(
3831
					'error'             => 'invalid_hmac',
3832
					'error_description' => 'The corresponding HMAC for this file does not match',
3833
				);
3834
				continue;
3835
			}
3836
3837
			$_FILES['.jetpack.upload.'] = $file;
3838
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3839
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3840
				$post_id = 0;
3841
			}
3842
3843
			if ( $update_media_item ) {
3844
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3845
					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...
3846
				}
3847
3848
				$media_array = $_FILES['media'];
3849
3850
				$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...
3851
				$file_array['type']     = $media_array['type'][0];
3852
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3853
				$file_array['error']    = $media_array['error'][0];
3854
				$file_array['size']     = $media_array['size'][0];
3855
3856
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3857
3858
				if ( is_wp_error( $edited_media_item ) ) {
3859
					return $edited_media_item;
3860
				}
3861
3862
				$response = (object) array(
3863
					'id'   => (string) $post_id,
3864
					'file' => (string) $edited_media_item->post_title,
3865
					'url'  => (string) wp_get_attachment_url( $post_id ),
3866
					'type' => (string) $edited_media_item->post_mime_type,
3867
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3868
				);
3869
3870
				return (array) array( $response );
3871
			}
3872
3873
			$attachment_id = media_handle_upload(
3874
				'.jetpack.upload.',
3875
				$post_id,
3876
				array(),
3877
				array(
3878
					'action' => 'jetpack_upload_file',
3879
				)
3880
			);
3881
3882
			if ( ! $attachment_id ) {
3883
				$uploaded_files[ $index ] = (object) array(
3884
					'error'             => 'unknown',
3885
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3886
				);
3887
			} elseif ( is_wp_error( $attachment_id ) ) {
3888
				$uploaded_files[ $index ] = (object) array(
3889
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3890
					'error_description' => $attachment_id->get_error_message(),
3891
				);
3892
			} else {
3893
				$attachment               = get_post( $attachment_id );
3894
				$uploaded_files[ $index ] = (object) array(
3895
					'id'   => (string) $attachment_id,
3896
					'file' => $attachment->post_title,
3897
					'url'  => wp_get_attachment_url( $attachment_id ),
3898
					'type' => $attachment->post_mime_type,
3899
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3900
				);
3901
				// Zip files uploads are not supported unless they are done for installation purposed
3902
				// lets delete them in case something goes wrong in this whole process
3903
				if ( 'application/zip' === $attachment->post_mime_type ) {
3904
					// Schedule a cleanup for 2 hours from now in case of failed install.
3905
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3906
				}
3907
			}
3908
		}
3909
		if ( ! is_null( $global_post ) ) {
3910
			$GLOBALS['post'] = $global_post;
3911
		}
3912
3913
		return $uploaded_files;
3914
	}
3915
3916
	/**
3917
	 * Add help to the Jetpack page
3918
	 *
3919
	 * @since Jetpack (1.2.3)
3920
	 * @return false if not the Jetpack page
3921
	 */
3922
	function admin_help() {
3923
		$current_screen = get_current_screen();
3924
3925
		// Overview
3926
		$current_screen->add_help_tab(
3927
			array(
3928
				'id'      => 'home',
3929
				'title'   => __( 'Home', 'jetpack' ),
3930
				'content' =>
3931
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3932
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3933
					'<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>',
3934
			)
3935
		);
3936
3937
		// Screen Content
3938
		if ( current_user_can( 'manage_options' ) ) {
3939
			$current_screen->add_help_tab(
3940
				array(
3941
					'id'      => 'settings',
3942
					'title'   => __( 'Settings', 'jetpack' ),
3943
					'content' =>
3944
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3945
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3946
						'<ol>' .
3947
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3948
							'<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>' .
3949
						'</ol>' .
3950
						'<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>',
3951
				)
3952
			);
3953
		}
3954
3955
		// Help Sidebar
3956
		$support_url = Redirect::get_url( 'jetpack-support' );
3957
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3958
		$current_screen->set_help_sidebar(
3959
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3960
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3961
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3962
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3963
		);
3964
	}
3965
3966
	function admin_menu_css() {
3967
		wp_enqueue_style( 'jetpack-icons' );
3968
	}
3969
3970
	function admin_menu_order() {
3971
		return true;
3972
	}
3973
3974
	function jetpack_menu_order( $menu_order ) {
3975
		$jp_menu_order = array();
3976
3977
		foreach ( $menu_order as $index => $item ) {
3978
			if ( $item != 'jetpack' ) {
3979
				$jp_menu_order[] = $item;
3980
			}
3981
3982
			if ( $index == 0 ) {
3983
				$jp_menu_order[] = 'jetpack';
3984
			}
3985
		}
3986
3987
		return $jp_menu_order;
3988
	}
3989
3990
	function admin_banner_styles() {
3991
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3992
3993 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3994
			wp_register_style(
3995
				'jetpack-dops-style',
3996
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3997
				array(),
3998
				JETPACK__VERSION
3999
			);
4000
		}
4001
4002
		wp_enqueue_style(
4003
			'jetpack',
4004
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4005
			array( 'jetpack-dops-style' ),
4006
			JETPACK__VERSION . '-20121016'
4007
		);
4008
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4009
		wp_style_add_data( 'jetpack', 'suffix', $min );
4010
	}
4011
4012
	function plugin_action_links( $actions ) {
4013
4014
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4015
4016
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
4017
			return array_merge(
4018
				$jetpack_home,
4019
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4020
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4021
				$actions
4022
			);
4023
		}
4024
4025
		return array_merge( $jetpack_home, $actions );
4026
	}
4027
4028
	/**
4029
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4030
	 *
4031
	 * @param string $hook The current admin page.
4032
	 *
4033
	 * @return void
4034
	 */
4035
	public function deactivate_dialog( $hook ) {
4036
		if (
4037
			'plugins.php' === $hook
4038
			&& self::is_active()
4039
		) {
4040
4041
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4042
4043
			if ( count( $active_plugins_using_connection ) > 1 ) {
4044
4045
				add_thickbox();
4046
4047
				wp_register_script(
4048
					'jp-tracks',
4049
					'//stats.wp.com/w.js',
4050
					array(),
4051
					gmdate( 'YW' ),
4052
					true
4053
				);
4054
4055
				wp_register_script(
4056
					'jp-tracks-functions',
4057
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4058
					array( 'jp-tracks' ),
4059
					JETPACK__VERSION,
4060
					false
4061
				);
4062
4063
				wp_enqueue_script(
4064
					'jetpack-deactivate-dialog-js',
4065
					Assets::get_file_url_for_environment(
4066
						'_inc/build/jetpack-deactivate-dialog.min.js',
4067
						'_inc/jetpack-deactivate-dialog.js'
4068
					),
4069
					array( 'jquery', 'jp-tracks-functions' ),
4070
					JETPACK__VERSION,
4071
					true
4072
				);
4073
4074
				wp_localize_script(
4075
					'jetpack-deactivate-dialog-js',
4076
					'deactivate_dialog',
4077
					array(
4078
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4079
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4080
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4081
					)
4082
				);
4083
4084
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4085
4086
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4087
			}
4088
		}
4089
	}
4090
4091
	/**
4092
	 * Outputs the content of the deactivation modal
4093
	 *
4094
	 * @return void
4095
	 */
4096
	public function deactivate_dialog_content() {
4097
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4098
		unset( $active_plugins_using_connection['jetpack'] );
4099
		$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 4097 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...
4100
	}
4101
4102
	/**
4103
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4104
	 *
4105
	 * @param string $login_url The wp-login URL.
4106
	 * @param string $redirect  URL to redirect users after logging in.
4107
	 * @since Jetpack 8.4
4108
	 * @return string
4109
	 */
4110
	public function login_url( $login_url, $redirect ) {
4111
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4112
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4113
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4114
		}
4115
		return $login_url;
4116
	}
4117
4118
	/**
4119
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4120
	 *
4121
	 * @since Jetpack 8.4
4122
	 */
4123
	public function login_init() {
4124
		// phpcs:ignore WordPress.Security.NonceVerification
4125
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4126
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4127
			wp_safe_redirect(
4128
				add_query_arg(
4129
					array(
4130
						'forceInstall' => 1,
4131
						'url'          => rawurlencode( get_site_url() ),
4132
					),
4133
					// @todo provide way to go to specific calypso env.
4134
					self::get_calypso_host() . 'jetpack/connect'
4135
				)
4136
			);
4137
			exit;
4138
		}
4139
	}
4140
4141
	/*
4142
	 * Registration flow:
4143
	 * 1 - ::admin_page_load() action=register
4144
	 * 2 - ::try_registration()
4145
	 * 3 - ::register()
4146
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4147
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4148
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4149
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4150
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4151
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4152
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4153
	 *       jetpack_id, jetpack_secret, jetpack_public
4154
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4155
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4156
	 * 5 - user logs in with WP.com account
4157
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4158
	 *		- Manager::authorize()
4159
	 *		- Manager::get_token()
4160
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4161
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4162
	 *			- which responds with access_token, token_type, scope
4163
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4164
	 *		- Jetpack::activate_default_modules()
4165
	 *     		- Deactivates deprecated plugins
4166
	 *     		- Activates all default modules
4167
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4168
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4169
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4170
	 *     Done!
4171
	 */
4172
4173
	/**
4174
	 * Handles the page load events for the Jetpack admin page
4175
	 */
4176
	function admin_page_load() {
4177
		$error = false;
4178
4179
		// Make sure we have the right body class to hook stylings for subpages off of.
4180
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4181
4182
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4183
			// Should only be used in intermediate redirects to preserve state across redirects
4184
			self::restate();
4185
		}
4186
4187
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4188
			// @todo: Add validation against a known allowed list.
4189
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4190
			// User clicked in the iframe to link their accounts
4191
			if ( ! self::connection()->is_user_connected() ) {
4192
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4193
4194
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4195
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4196
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4197
4198
				if ( isset( $_GET['notes_iframe'] ) ) {
4199
					$connect_url .= '&notes_iframe';
4200
				}
4201
				wp_redirect( $connect_url );
4202
				exit;
4203
			} else {
4204
				if ( ! isset( $_GET['calypso_env'] ) ) {
4205
					self::state( 'message', 'already_authorized' );
4206
					wp_safe_redirect( self::admin_url() );
4207
					exit;
4208
				} else {
4209
					$connect_url  = $this->build_connect_url( true, false, $from );
4210
					$connect_url .= '&already_authorized=true';
4211
					wp_redirect( $connect_url );
4212
					exit;
4213
				}
4214
			}
4215
		}
4216
4217
		if ( isset( $_GET['action'] ) ) {
4218
			switch ( $_GET['action'] ) {
4219
				case 'authorize_redirect':
4220
					self::log( 'authorize_redirect' );
4221
4222
					add_filter(
4223
						'allowed_redirect_hosts',
4224
						function ( $domains ) {
4225
							$domains[] = 'jetpack.com';
4226
							$domains[] = 'jetpack.wordpress.com';
4227
							$domains[] = 'wordpress.com';
4228
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4229
							return array_unique( $domains );
4230
						}
4231
					);
4232
4233
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4234
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4235
4236
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4237
						// The destination URL is missing or invalid, nothing to do here.
4238
						exit;
4239
					}
4240
4241
					if ( self::is_active() && self::is_user_connected() ) {
4242
						// The user is either already connected, or finished the connection process.
4243
						wp_safe_redirect( $dest_url );
4244
						exit;
4245
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4246
						// The user decided not to proceed with setting up the connection.
4247
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4248
						exit;
4249
					}
4250
4251
					$redirect_url = self::admin_url(
4252
						array(
4253
							'page'     => 'jetpack',
4254
							'action'   => 'authorize_redirect',
4255
							'dest_url' => rawurlencode( $dest_url ),
4256
							'done'     => '1',
4257
						)
4258
					);
4259
4260
					wp_safe_redirect( static::build_authorize_url( $redirect_url ) );
0 ignored issues
show
Documentation introduced by
$redirect_url is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4261
					exit;
4262
				case 'authorize':
4263
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4264
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4265
					exit;
4266
				case 'register':
4267
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4268
						$error = 'cheatin';
4269
						break;
4270
					}
4271
					check_admin_referer( 'jetpack-register' );
4272
					self::log( 'register' );
4273
					self::maybe_set_version_option();
4274
					$registered = self::try_registration();
4275
					if ( is_wp_error( $registered ) ) {
4276
						$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...
4277
						self::state( 'error', $error );
4278
						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...
4279
4280
						/**
4281
						 * Jetpack registration Error.
4282
						 *
4283
						 * @since 7.5.0
4284
						 *
4285
						 * @param string|int $error The error code.
4286
						 * @param \WP_Error $registered The error object.
4287
						 */
4288
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4289
						break;
4290
					}
4291
4292
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4293
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4294
4295
					/**
4296
					 * Jetpack registration Success.
4297
					 *
4298
					 * @since 7.5.0
4299
					 *
4300
					 * @param string $from 'from' GET parameter;
4301
					 */
4302
					do_action( 'jetpack_connection_register_success', $from );
4303
4304
					$url = $this->build_connect_url( true, $redirect, $from );
4305
4306
					if ( ! empty( $_GET['onboarding'] ) ) {
4307
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4308
					}
4309
4310
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4311
						$url = add_query_arg( 'auth_approved', 'true', $url );
4312
					}
4313
4314
					wp_redirect( $url );
4315
					exit;
4316
				case 'activate':
4317
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4318
						$error = 'cheatin';
4319
						break;
4320
					}
4321
4322
					$module = stripslashes( $_GET['module'] );
4323
					check_admin_referer( "jetpack_activate-$module" );
4324
					self::log( 'activate', $module );
4325
					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...
4326
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4327
					}
4328
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4329
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4330
					exit;
4331
				case 'activate_default_modules':
4332
					check_admin_referer( 'activate_default_modules' );
4333
					self::log( 'activate_default_modules' );
4334
					self::restate();
4335
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4336
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4337
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4338
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4339
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4340
					exit;
4341
				case 'disconnect':
4342
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4343
						$error = 'cheatin';
4344
						break;
4345
					}
4346
4347
					check_admin_referer( 'jetpack-disconnect' );
4348
					self::log( 'disconnect' );
4349
					self::disconnect();
4350
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4351
					exit;
4352
				case 'reconnect':
4353
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4354
						$error = 'cheatin';
4355
						break;
4356
					}
4357
4358
					check_admin_referer( 'jetpack-reconnect' );
4359
					self::log( 'reconnect' );
4360
					$this->disconnect();
4361
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4362
					exit;
4363 View Code Duplication
				case 'deactivate':
4364
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4365
						$error = 'cheatin';
4366
						break;
4367
					}
4368
4369
					$modules = stripslashes( $_GET['module'] );
4370
					check_admin_referer( "jetpack_deactivate-$modules" );
4371
					foreach ( explode( ',', $modules ) as $module ) {
4372
						self::log( 'deactivate', $module );
4373
						self::deactivate_module( $module );
4374
						self::state( 'message', 'module_deactivated' );
4375
					}
4376
					self::state( 'module', $modules );
4377
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4378
					exit;
4379
				case 'unlink':
4380
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4381
					check_admin_referer( 'jetpack-unlink' );
4382
					self::log( 'unlink' );
4383
					Connection_Manager::disconnect_user();
4384
					self::state( 'message', 'unlinked' );
4385
					if ( 'sub-unlink' == $redirect ) {
4386
						wp_safe_redirect( admin_url() );
4387
					} else {
4388
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4389
					}
4390
					exit;
4391
				case 'onboard':
4392
					if ( ! current_user_can( 'manage_options' ) ) {
4393
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4394
					} else {
4395
						self::create_onboarding_token();
4396
						$url = $this->build_connect_url( true );
4397
4398
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4399
							$url = add_query_arg( 'onboarding', $token, $url );
4400
						}
4401
4402
						$calypso_env = $this->get_calypso_env();
4403
						if ( ! empty( $calypso_env ) ) {
4404
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4405
						}
4406
4407
						wp_redirect( $url );
4408
						exit;
4409
					}
4410
					exit;
4411
				default:
4412
					/**
4413
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4414
					 *
4415
					 * @since 2.6.0
4416
					 *
4417
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4418
					 */
4419
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4420
			}
4421
		}
4422
4423
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4424
			self::activate_new_modules( true );
4425
		}
4426
4427
		$message_code = self::state( 'message' );
4428
		if ( self::state( 'optin-manage' ) ) {
4429
			$activated_manage = $message_code;
4430
			$message_code     = 'jetpack-manage';
4431
		}
4432
4433
		switch ( $message_code ) {
4434
			case 'jetpack-manage':
4435
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4436
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4437
				$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>';
4438
				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...
4439
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4440
				}
4441
				break;
4442
4443
		}
4444
4445
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4446
4447
		if ( ! empty( $deactivated_plugins ) ) {
4448
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4449
			$deactivated_titles  = array();
4450
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4451
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4452
					continue;
4453
				}
4454
4455
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4456
			}
4457
4458
			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...
4459
				if ( $this->message ) {
4460
					$this->message .= "<br /><br />\n";
4461
				}
4462
4463
				$this->message .= wp_sprintf(
4464
					_n(
4465
						'Jetpack contains the most recent version of the old %l plugin.',
4466
						'Jetpack contains the most recent versions of the old %l plugins.',
4467
						count( $deactivated_titles ),
4468
						'jetpack'
4469
					),
4470
					$deactivated_titles
4471
				);
4472
4473
				$this->message .= "<br />\n";
4474
4475
				$this->message .= _n(
4476
					'The old version has been deactivated and can be removed from your site.',
4477
					'The old versions have been deactivated and can be removed from your site.',
4478
					count( $deactivated_titles ),
4479
					'jetpack'
4480
				);
4481
			}
4482
		}
4483
4484
		$this->privacy_checks = self::state( 'privacy_checks' );
4485
4486
		if ( $this->message || $this->error || $this->privacy_checks ) {
4487
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4488
		}
4489
4490
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4491
	}
4492
4493
	function admin_notices() {
4494
4495
		if ( $this->error ) {
4496
			?>
4497
<div id="message" class="jetpack-message jetpack-err">
4498
	<div class="squeezer">
4499
		<h2>
4500
			<?php
4501
			echo wp_kses(
4502
				$this->error,
4503
				array(
4504
					'a'      => array( 'href' => array() ),
4505
					'small'  => true,
4506
					'code'   => true,
4507
					'strong' => true,
4508
					'br'     => true,
4509
					'b'      => true,
4510
				)
4511
			);
4512
			?>
4513
			</h2>
4514
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4515
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4516
<?php	endif; ?>
4517
	</div>
4518
</div>
4519
			<?php
4520
		}
4521
4522
		if ( $this->message ) {
4523
			?>
4524
<div id="message" class="jetpack-message">
4525
	<div class="squeezer">
4526
		<h2>
4527
			<?php
4528
			echo wp_kses(
4529
				$this->message,
4530
				array(
4531
					'strong' => array(),
4532
					'a'      => array( 'href' => true ),
4533
					'br'     => true,
4534
				)
4535
			);
4536
			?>
4537
			</h2>
4538
	</div>
4539
</div>
4540
			<?php
4541
		}
4542
4543
		if ( $this->privacy_checks ) :
4544
			$module_names = $module_slugs = array();
4545
4546
			$privacy_checks = explode( ',', $this->privacy_checks );
4547
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4548
			foreach ( $privacy_checks as $module_slug ) {
4549
				$module = self::get_module( $module_slug );
4550
				if ( ! $module ) {
4551
					continue;
4552
				}
4553
4554
				$module_slugs[] = $module_slug;
4555
				$module_names[] = "<strong>{$module['name']}</strong>";
4556
			}
4557
4558
			$module_slugs = join( ',', $module_slugs );
4559
			?>
4560
<div id="message" class="jetpack-message jetpack-err">
4561
	<div class="squeezer">
4562
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4563
		<p>
4564
			<?php
4565
			echo wp_kses(
4566
				wptexturize(
4567
					wp_sprintf(
4568
						_nx(
4569
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4570
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4571
							count( $privacy_checks ),
4572
							'%l = list of Jetpack module/feature names',
4573
							'jetpack'
4574
						),
4575
						$module_names
4576
					)
4577
				),
4578
				array( 'strong' => true )
4579
			);
4580
4581
			echo "\n<br />\n";
4582
4583
			echo wp_kses(
4584
				sprintf(
4585
					_nx(
4586
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4587
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4588
						count( $privacy_checks ),
4589
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4590
						'jetpack'
4591
					),
4592
					wp_nonce_url(
4593
						self::admin_url(
4594
							array(
4595
								'page'   => 'jetpack',
4596
								'action' => 'deactivate',
4597
								'module' => urlencode( $module_slugs ),
4598
							)
4599
						),
4600
						"jetpack_deactivate-$module_slugs"
4601
					),
4602
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4603
				),
4604
				array(
4605
					'a' => array(
4606
						'href'  => true,
4607
						'title' => true,
4608
					),
4609
				)
4610
			);
4611
			?>
4612
		</p>
4613
	</div>
4614
</div>
4615
			<?php
4616
endif;
4617
	}
4618
4619
	/**
4620
	 * We can't always respond to a signed XML-RPC request with a
4621
	 * helpful error message. In some circumstances, doing so could
4622
	 * leak information.
4623
	 *
4624
	 * Instead, track that the error occurred via a Jetpack_Option,
4625
	 * and send that data back in the heartbeat.
4626
	 * All this does is increment a number, but it's enough to find
4627
	 * trends.
4628
	 *
4629
	 * @param WP_Error $xmlrpc_error The error produced during
4630
	 *                               signature validation.
4631
	 */
4632
	function track_xmlrpc_error( $xmlrpc_error ) {
4633
		$code = is_wp_error( $xmlrpc_error )
4634
			? $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...
4635
			: 'should-not-happen';
4636
4637
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4638
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4639
			// No need to update the option if we already have
4640
			// this code stored.
4641
			return;
4642
		}
4643
		$xmlrpc_errors[ $code ] = true;
4644
4645
		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...
4646
	}
4647
4648
	/**
4649
	 * Initialize the jetpack stats instance only when needed
4650
	 *
4651
	 * @return void
4652
	 */
4653
	private function initialize_stats() {
4654
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4655
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4656
		}
4657
	}
4658
4659
	/**
4660
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4661
	 */
4662
	function stat( $group, $detail ) {
4663
		$this->initialize_stats();
4664
		$this->a8c_mc_stats_instance->add( $group, $detail );
4665
4666
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4667
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4668
	}
4669
4670
	/**
4671
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4672
	 */
4673
	function do_stats( $method = '' ) {
4674
		$this->initialize_stats();
4675
		if ( 'server_side' === $method ) {
4676
			$this->a8c_mc_stats_instance->do_server_side_stats();
4677
		} else {
4678
			$this->a8c_mc_stats_instance->do_stats();
4679
		}
4680
4681
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4682
		$this->stats = array();
4683
	}
4684
4685
	/**
4686
	 * Runs stats code for a one-off, server-side.
4687
	 *
4688
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4689
	 *
4690
	 * @return bool If it worked.
4691
	 */
4692
	static function do_server_side_stat( $args ) {
4693
		$url                   = self::build_stats_url( $args );
4694
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4695
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4696
	}
4697
4698
	/**
4699
	 * Builds the stats url.
4700
	 *
4701
	 * @param $args array|string The arguments to append to the URL.
4702
	 *
4703
	 * @return string The URL to be pinged.
4704
	 */
4705
	static function build_stats_url( $args ) {
4706
4707
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4708
		return $a8c_mc_stats_instance->build_stats_url( $args );
4709
4710
	}
4711
4712
	/**
4713
	 * Get the role of the current user.
4714
	 *
4715
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4716
	 *
4717
	 * @access public
4718
	 * @static
4719
	 *
4720
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4721
	 */
4722
	public static function translate_current_user_to_role() {
4723
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4724
4725
		$roles = new Roles();
4726
		return $roles->translate_current_user_to_role();
4727
	}
4728
4729
	/**
4730
	 * Get the role of a particular user.
4731
	 *
4732
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4733
	 *
4734
	 * @access public
4735
	 * @static
4736
	 *
4737
	 * @param \WP_User $user User object.
4738
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4739
	 */
4740
	public static function translate_user_to_role( $user ) {
4741
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4742
4743
		$roles = new Roles();
4744
		return $roles->translate_user_to_role( $user );
4745
	}
4746
4747
	/**
4748
	 * Get the minimum capability for a role.
4749
	 *
4750
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4751
	 *
4752
	 * @access public
4753
	 * @static
4754
	 *
4755
	 * @param string $role Role name.
4756
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4757
	 */
4758
	public static function translate_role_to_cap( $role ) {
4759
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4760
4761
		$roles = new Roles();
4762
		return $roles->translate_role_to_cap( $role );
4763
	}
4764
4765
	/**
4766
	 * Sign a user role with the master access token.
4767
	 * If not specified, will default to the current user.
4768
	 *
4769
	 * @deprecated since 7.7
4770
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4771
	 *
4772
	 * @access public
4773
	 * @static
4774
	 *
4775
	 * @param string $role    User role.
4776
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|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...
4777
	 * @return string Signed user role.
4778
	 */
4779
	public static function sign_role( $role, $user_id = null ) {
4780
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4781
		return self::connection()->sign_role( $role, $user_id );
4782
	}
4783
4784
	/**
4785
	 * Builds a URL to the Jetpack connection auth page
4786
	 *
4787
	 * @since 3.9.5
4788
	 *
4789
	 * @param bool        $raw If true, URL will not be escaped.
4790
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4791
	 *                              If string, will be a custom redirect.
4792
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4793
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4794
	 *
4795
	 * @return string Connect URL
4796
	 */
4797
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4798
		$site_id    = Jetpack_Options::get_option( 'id' );
4799
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4800
4801
		if ( $register || ! $blog_token || ! $site_id ) {
4802
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4803
4804
			if ( ! empty( $redirect ) ) {
4805
				$url = add_query_arg(
4806
					'redirect',
4807
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4808
					$url
4809
				);
4810
			}
4811
4812
			if ( is_network_admin() ) {
4813
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4814
			}
4815
4816
			$calypso_env = self::get_calypso_env();
4817
4818
			if ( ! empty( $calypso_env ) ) {
4819
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4820
			}
4821
		} else {
4822
4823
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4824
			// because otherwise this logic can get us in to a loop.
4825
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4826
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4827
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4828
4829
				$response = Client::wpcom_json_api_request_as_blog(
4830
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4831
					'1.1'
4832
				);
4833
4834
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4835
4836
					// Generating a register URL instead to refresh the existing token
4837
					return $this->build_connect_url( $raw, $redirect, $from, true );
4838
				}
4839
			}
4840
4841
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4797 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...
4842
		}
4843
4844
		if ( $from ) {
4845
			$url = add_query_arg( 'from', $from, $url );
4846
		}
4847
4848
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4849
		/**
4850
		 * Filter the URL used when connecting a user to a WordPress.com account.
4851
		 *
4852
		 * @since 8.1.0
4853
		 *
4854
		 * @param string $url Connection URL.
4855
		 * @param bool   $raw If true, URL will not be escaped.
4856
		 */
4857
		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...
4858
	}
4859
4860
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4861
4862
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4863
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4864
4865
		if ( $iframe ) {
4866
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4867
		}
4868
4869
		$c8n = self::connection();
4870
		$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...
4871
4872
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4873
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4874
4875
		if ( $iframe ) {
4876
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4877
		}
4878
4879
		/**
4880
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4881
		 *
4882
		 * @since 8.9.0
4883
		 *
4884
		 * @param string $url Connection URL.
4885
		 */
4886
		return apply_filters( 'jetpack_build_authorize_url', $url );
4887
	}
4888
4889
	/**
4890
	 * Filters the connection URL parameter array.
4891
	 *
4892
	 * @param array $args default URL parameters used by the package.
4893
	 * @return array the modified URL arguments array.
4894
	 */
4895
	public static function filter_connect_request_body( $args ) {
4896
		if (
4897
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4898
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4899
		) {
4900
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4901
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4902
				? $gp_locale->slug
4903
				: '';
4904
		}
4905
4906
		$tracking        = new Tracking();
4907
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4908
4909
		$args = array_merge(
4910
			$args,
4911
			array(
4912
				'_ui' => $tracks_identity['_ui'],
4913
				'_ut' => $tracks_identity['_ut'],
4914
			)
4915
		);
4916
4917
		$calypso_env = self::get_calypso_env();
4918
4919
		if ( ! empty( $calypso_env ) ) {
4920
			$args['calypso_env'] = $calypso_env;
4921
		}
4922
4923
		return $args;
4924
	}
4925
4926
	/**
4927
	 * Filters the URL that will process the connection data. It can be different from the URL
4928
	 * that we send the user to after everything is done.
4929
	 *
4930
	 * @param String $processing_url the default redirect URL used by the package.
4931
	 * @return String the modified URL.
4932
	 *
4933
	 * @deprecated since Jetpack 9.5.0
4934
	 */
4935
	public static function filter_connect_processing_url( $processing_url ) {
4936
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4937
4938
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4939
		return $processing_url;
4940
	}
4941
4942
	/**
4943
	 * Filters the redirection URL that is used for connect requests. The redirect
4944
	 * URL should return the user back to the Jetpack console.
4945
	 *
4946
	 * @param String $redirect the default redirect URL used by the package.
4947
	 * @return String the modified URL.
4948
	 */
4949
	public static function filter_connect_redirect_url( $redirect ) {
4950
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4951
		$redirect           = $redirect
4952
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4953
			: $jetpack_admin_page;
4954
4955
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4956
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4957
		}
4958
4959
		return $redirect;
4960
	}
4961
4962
	/**
4963
	 * This action fires at the beginning of the Manager::authorize method.
4964
	 */
4965
	public static function authorize_starting() {
4966
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4967
		// Checking if site has been active/connected previously before recording unique connection.
4968
		if ( ! $jetpack_unique_connection ) {
4969
			// jetpack_unique_connection option has never been set.
4970
			$jetpack_unique_connection = array(
4971
				'connected'    => 0,
4972
				'disconnected' => 0,
4973
				'version'      => '3.6.1',
4974
			);
4975
4976
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4977
4978
			// Track unique connection.
4979
			$jetpack = self::init();
4980
4981
			$jetpack->stat( 'connections', 'unique-connection' );
4982
			$jetpack->do_stats( 'server_side' );
4983
		}
4984
4985
		// Increment number of times connected.
4986
		$jetpack_unique_connection['connected'] += 1;
4987
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4988
	}
4989
4990
	/**
4991
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4992
	 * linked.
4993
	 */
4994
	public static function authorize_ending_linked() {
4995
		// Don't activate anything since we are just connecting a user.
4996
		self::state( 'message', 'linked' );
4997
	}
4998
4999
	/**
5000
	 * This action fires at the end of the Manager::authorize method when the master user is
5001
	 * authorized.
5002
	 *
5003
	 * @param array $data The request data.
5004
	 */
5005
	public static function authorize_ending_authorized( $data ) {
5006
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5007
		self::invalidate_onboarding_token();
5008
5009
		// If redirect_uri is SSO, ensure SSO module is enabled.
5010
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5011
5012
		/** This filter is documented in class.jetpack-cli.php */
5013
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5014
5015
		$activate_sso = (
5016
			isset( $redirect_options['action'] ) &&
5017
			'jetpack-sso' === $redirect_options['action'] &&
5018
			$jetpack_start_enable_sso
5019
		);
5020
5021
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5022
5023
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5024
	}
5025
5026
	/**
5027
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5028
	 * reconnect process is completed.
5029
	 * Note that this currently only happens when we don't need the user to re-authorize
5030
	 * their WP.com account, eg in cases where we are restoring a connection with
5031
	 * unhealthy blog token.
5032
	 */
5033
	public static function reconnection_completed() {
5034
		self::state( 'message', 'reconnection_completed' );
5035
	}
5036
5037
	/**
5038
	 * Get our assumed site creation date.
5039
	 * Calculated based on the earlier date of either:
5040
	 * - Earliest admin user registration date.
5041
	 * - Earliest date of post of any post type.
5042
	 *
5043
	 * @since 7.2.0
5044
	 * @deprecated since 7.8.0
5045
	 *
5046
	 * @return string Assumed site creation date and time.
5047
	 */
5048
	public static function get_assumed_site_creation_date() {
5049
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5050
		return self::connection()->get_assumed_site_creation_date();
5051
	}
5052
5053 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5054
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5055
5056
		if ( $activation_source_name ) {
5057
			$args['_as'] = urlencode( $activation_source_name );
5058
		}
5059
5060
		if ( $activation_source_keyword ) {
5061
			$args['_ak'] = urlencode( $activation_source_keyword );
5062
		}
5063
	}
5064
5065
	function build_reconnect_url( $raw = false ) {
5066
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5067
		return $raw ? $url : esc_url( $url );
5068
	}
5069
5070
	public static function admin_url( $args = null ) {
5071
		$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...
5072
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5073
		return $url;
5074
	}
5075
5076
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5077
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5078
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5079
	}
5080
5081
	function dismiss_jetpack_notice() {
5082
5083
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5084
			return;
5085
		}
5086
5087
		switch ( $_GET['jetpack-notice'] ) {
5088
			case 'dismiss':
5089
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5090
5091
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5092
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5093
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5094
				}
5095
				break;
5096
		}
5097
	}
5098
5099
	public static function sort_modules( $a, $b ) {
5100
		if ( $a['sort'] == $b['sort'] ) {
5101
			return 0;
5102
		}
5103
5104
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5105
	}
5106
5107
	function ajax_recheck_ssl() {
5108
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5109
		$result = self::permit_ssl( true );
5110
		wp_send_json(
5111
			array(
5112
				'enabled' => $result,
5113
				'message' => get_transient( 'jetpack_https_test_message' ),
5114
			)
5115
		);
5116
	}
5117
5118
	/* Client API */
5119
5120
	/**
5121
	 * Returns the requested Jetpack API URL
5122
	 *
5123
	 * @deprecated since 7.7
5124
	 * @return string
5125
	 */
5126
	public static function api_url( $relative_url ) {
5127
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5128
		$connection = self::connection();
5129
		return $connection->api_url( $relative_url );
5130
	}
5131
5132
	/**
5133
	 * @deprecated 8.0
5134
	 *
5135
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5136
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5137
	 */
5138
	public static function fix_url_for_bad_hosts( $url ) {
5139
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5140
		return $url;
5141
	}
5142
5143
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5144
		// Default to a blog token.
5145
		$token_type = 'blog';
5146
5147
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5148
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5149
			if ( ! empty( $_GET['onboarding'] ) ) {
5150
				$jpo = $_GET;
5151
			} else {
5152
				$jpo = json_decode( $request_data, true );
5153
			}
5154
5155
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5156
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5157
5158
			if (
5159
				isset( $jpo_user )
5160
				&& isset( $jpo_token )
5161
				&& is_email( $jpo_user )
5162
				&& ctype_alnum( $jpo_token )
5163
				&& isset( $_GET['rest_route'] )
5164
				&& self::validate_onboarding_token_action(
5165
					$jpo_token,
5166
					$_GET['rest_route']
5167
				)
5168
			) {
5169
				$jp_user = get_user_by( 'email', $jpo_user );
5170
				if ( is_a( $jp_user, 'WP_User' ) ) {
5171
					wp_set_current_user( $jp_user->ID );
5172
					$user_can = is_multisite()
5173
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5174
						: current_user_can( 'manage_options' );
5175
					if ( $user_can ) {
5176
						$token_type              = 'user';
5177
						$token->external_user_id = $jp_user->ID;
5178
					}
5179
				}
5180
			}
5181
5182
			$token_data['type']    = $token_type;
5183
			$token_data['user_id'] = $token->external_user_id;
5184
		}
5185
5186
		return $token_data;
5187
	}
5188
5189
	/**
5190
	 * Create a random secret for validating onboarding payload
5191
	 *
5192
	 * @return string Secret token
5193
	 */
5194
	public static function create_onboarding_token() {
5195
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5196
			$token = wp_generate_password( 32, false );
5197
			Jetpack_Options::update_option( 'onboarding', $token );
5198
		}
5199
5200
		return $token;
5201
	}
5202
5203
	/**
5204
	 * Remove the onboarding token
5205
	 *
5206
	 * @return bool True on success, false on failure
5207
	 */
5208
	public static function invalidate_onboarding_token() {
5209
		return Jetpack_Options::delete_option( 'onboarding' );
5210
	}
5211
5212
	/**
5213
	 * Validate an onboarding token for a specific action
5214
	 *
5215
	 * @return boolean True if token/action pair is accepted, false if not
5216
	 */
5217
	public static function validate_onboarding_token_action( $token, $action ) {
5218
		// Compare tokens, bail if tokens do not match
5219
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5220
			return false;
5221
		}
5222
5223
		// List of valid actions we can take
5224
		$valid_actions = array(
5225
			'/jetpack/v4/settings',
5226
		);
5227
5228
		// Only allow valid actions.
5229
		if ( ! in_array( $action, $valid_actions ) ) {
5230
			return false;
5231
		}
5232
5233
		return true;
5234
	}
5235
5236
	/**
5237
	 * Checks to see if the URL is using SSL to connect with Jetpack
5238
	 *
5239
	 * @since 2.3.3
5240
	 * @return boolean
5241
	 */
5242
	public static function permit_ssl( $force_recheck = false ) {
5243
		// Do some fancy tests to see if ssl is being supported
5244
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5245
			$message = '';
5246
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5247
				$ssl = 0;
5248
			} else {
5249
				$ssl = 1;
5250
5251
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5252
					$ssl     = 0;
5253
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5254
				} else {
5255
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5256
					if ( is_wp_error( $response ) ) {
5257
						$ssl     = 0;
5258
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5259
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5260
						$ssl     = 0;
5261
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5262
					}
5263
				}
5264
			}
5265
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5266
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5267
		}
5268
5269
		return (bool) $ssl;
5270
	}
5271
5272
	/*
5273
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5274
	 */
5275
	public function alert_auto_ssl_fail() {
5276
		if ( ! current_user_can( 'manage_options' ) ) {
5277
			return;
5278
		}
5279
5280
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5281
		?>
5282
5283
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5284
			<div class="jp-banner__content">
5285
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5286
				<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>
5287
				<p>
5288
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5289
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5290
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5291
				</p>
5292
				<p>
5293
					<?php
5294
					printf(
5295
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5296
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5297
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5298
					);
5299
					?>
5300
				</p>
5301
			</div>
5302
		</div>
5303
		<style>
5304
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5305
		</style>
5306
		<script type="text/javascript">
5307
			jQuery( document ).ready( function( $ ) {
5308
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5309
					var $this = $( this );
5310
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5311
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5312
					e.preventDefault();
5313
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5314
					$.post( ajaxurl, data )
5315
					  .done( function( response ) {
5316
						  if ( response.enabled ) {
5317
							  $( '#jetpack-ssl-warning' ).hide();
5318
						  } else {
5319
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5320
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5321
						  }
5322
					  }.bind( $this ) );
5323
				} );
5324
			} );
5325
		</script>
5326
5327
		<?php
5328
	}
5329
5330
	/**
5331
	 * Returns the Jetpack XML-RPC API
5332
	 *
5333
	 * @deprecated 8.0 Use Connection_Manager instead.
5334
	 * @return string
5335
	 */
5336
	public static function xmlrpc_api_url() {
5337
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5338
		return self::connection()->xmlrpc_api_url();
5339
	}
5340
5341
	/**
5342
	 * Returns the connection manager object.
5343
	 *
5344
	 * @return Automattic\Jetpack\Connection\Manager
5345
	 */
5346
	public static function connection() {
5347
		$jetpack = static::init();
5348
5349
		// If the connection manager hasn't been instantiated, do that now.
5350
		if ( ! $jetpack->connection_manager ) {
5351
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5352
		}
5353
5354
		return $jetpack->connection_manager;
5355
	}
5356
5357
	/**
5358
	 * Creates two secret tokens and the end of life timestamp for them.
5359
	 *
5360
	 * Note these tokens are unique per call, NOT static per site for connecting.
5361
	 *
5362
	 * @since 2.6
5363
	 * @param String  $action  The action name.
5364
	 * @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...
5365
	 * @param Integer $exp     Expiration time in seconds.
5366
	 * @return array
5367
	 */
5368
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5369
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5370
	}
5371
5372
	public static function get_secrets( $action, $user_id ) {
5373
		$secrets = self::connection()->get_secrets( $action, $user_id );
5374
5375
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5376
			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...
5377
		}
5378
5379
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5380
			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...
5381
		}
5382
5383
		return $secrets;
5384
	}
5385
5386
	/**
5387
	 * @deprecated 7.5 Use Connection_Manager instead.
5388
	 *
5389
	 * @param $action
5390
	 * @param $user_id
5391
	 */
5392
	public static function delete_secrets( $action, $user_id ) {
5393
		return self::connection()->delete_secrets( $action, $user_id );
5394
	}
5395
5396
	/**
5397
	 * Builds the timeout limit for queries talking with the wpcom servers.
5398
	 *
5399
	 * Based on local php max_execution_time in php.ini
5400
	 *
5401
	 * @since 2.6
5402
	 * @return int
5403
	 * @deprecated
5404
	 **/
5405
	public function get_remote_query_timeout_limit() {
5406
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5407
		return self::get_max_execution_time();
5408
	}
5409
5410
	/**
5411
	 * Builds the timeout limit for queries talking with the wpcom servers.
5412
	 *
5413
	 * Based on local php max_execution_time in php.ini
5414
	 *
5415
	 * @since 5.4
5416
	 * @return int
5417
	 **/
5418
	public static function get_max_execution_time() {
5419
		$timeout = (int) ini_get( 'max_execution_time' );
5420
5421
		// Ensure exec time set in php.ini
5422
		if ( ! $timeout ) {
5423
			$timeout = 30;
5424
		}
5425
		return $timeout;
5426
	}
5427
5428
	/**
5429
	 * Sets a minimum request timeout, and returns the current timeout
5430
	 *
5431
	 * @since 5.4
5432
	 **/
5433 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5434
		$timeout = self::get_max_execution_time();
5435
		if ( $timeout < $min_timeout ) {
5436
			$timeout = $min_timeout;
5437
			set_time_limit( $timeout );
5438
		}
5439
		return $timeout;
5440
	}
5441
5442
	/**
5443
	 * Takes the response from the Jetpack register new site endpoint and
5444
	 * verifies it worked properly.
5445
	 *
5446
	 * @since 2.6
5447
	 * @deprecated since 7.7.0
5448
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5449
	 **/
5450
	public function validate_remote_register_response() {
5451
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5452
	}
5453
5454
	/**
5455
	 * @return bool|WP_Error
5456
	 */
5457
	public static function register() {
5458
		$tracking = new Tracking();
5459
		$tracking->record_user_event( 'jpc_register_begin' );
5460
5461
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5462
5463
		$connection   = self::connection();
5464
		$registration = $connection->register();
5465
5466
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5467
5468
		if ( ! $registration || is_wp_error( $registration ) ) {
5469
			return $registration;
5470
		}
5471
5472
		return true;
5473
	}
5474
5475
	/**
5476
	 * Filters the registration request body to include tracking properties.
5477
	 *
5478
	 * @param array $properties
5479
	 * @return array amended properties.
5480
	 */
5481 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5482
		$tracking        = new Tracking();
5483
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5484
5485
		return array_merge(
5486
			$properties,
5487
			array(
5488
				'_ui' => $tracks_identity['_ui'],
5489
				'_ut' => $tracks_identity['_ut'],
5490
			)
5491
		);
5492
	}
5493
5494
	/**
5495
	 * Filters the token request body to include tracking properties.
5496
	 *
5497
	 * @param array $properties
5498
	 * @return array amended properties.
5499
	 */
5500 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5501
		$tracking        = new Tracking();
5502
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5503
5504
		return array_merge(
5505
			$properties,
5506
			array(
5507
				'_ui' => $tracks_identity['_ui'],
5508
				'_ut' => $tracks_identity['_ut'],
5509
			)
5510
		);
5511
	}
5512
5513
	/**
5514
	 * If the db version is showing something other that what we've got now, bump it to current.
5515
	 *
5516
	 * @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...
5517
	 */
5518
	public static function maybe_set_version_option() {
5519
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5520
		if ( JETPACK__VERSION != $version ) {
5521
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5522
5523
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5524
				/** This action is documented in class.jetpack.php */
5525
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5526
			}
5527
5528
			return true;
5529
		}
5530
		return false;
5531
	}
5532
5533
	/* Client Server API */
5534
5535
	/**
5536
	 * Loads the Jetpack XML-RPC client.
5537
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5538
	 *
5539
	 * @deprecated since 7.7.0
5540
	 */
5541
	public static function load_xml_rpc_client() {
5542
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5543
	}
5544
5545
	/**
5546
	 * Resets the saved authentication state in between testing requests.
5547
	 *
5548
	 * @deprecated since 8.9.0
5549
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5550
	 */
5551
	public function reset_saved_auth_state() {
5552
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5553
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5554
	}
5555
5556
	/**
5557
	 * Verifies the signature of the current request.
5558
	 *
5559
	 * @deprecated since 7.7.0
5560
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5561
	 *
5562
	 * @return false|array
5563
	 */
5564
	public function verify_xml_rpc_signature() {
5565
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5566
		return self::connection()->verify_xml_rpc_signature();
5567
	}
5568
5569
	/**
5570
	 * Verifies the signature of the current request.
5571
	 *
5572
	 * This function has side effects and should not be used. Instead,
5573
	 * use the memoized version `->verify_xml_rpc_signature()`.
5574
	 *
5575
	 * @deprecated since 7.7.0
5576
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5577
	 * @internal
5578
	 */
5579
	private function internal_verify_xml_rpc_signature() {
5580
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5581
	}
5582
5583
	/**
5584
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5585
	 *
5586
	 * @deprecated since 7.7.0
5587
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5588
	 *
5589
	 * @param \WP_User|mixed $user     User object if authenticated.
5590
	 * @param string         $username Username.
5591
	 * @param string         $password Password string.
5592
	 * @return \WP_User|mixed Authenticated user or error.
5593
	 */
5594 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5595
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5596
5597
		if ( ! $this->connection_manager ) {
5598
			$this->connection_manager = new Connection_Manager();
5599
		}
5600
5601
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5602
	}
5603
5604
	/**
5605
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5606
	 * Uses the existing XMLRPC request signing implementation.
5607
	 *
5608
	 * @deprecated since 8.9.0
5609
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5610
	 */
5611
	function wp_rest_authenticate( $user ) {
5612
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5613
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5614
	}
5615
5616
	/**
5617
	 * Report authentication status to the WP REST API.
5618
	 *
5619
	 * @deprecated since 8.9.0
5620
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5621
	 *
5622
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5623
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5624
	 */
5625
	public function wp_rest_authentication_errors( $value ) {
5626
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5627
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5628
	}
5629
5630
	/**
5631
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5632
	 * Capture it here so we can verify the signature later.
5633
	 *
5634
	 * @deprecated since 7.7.0
5635
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5636
	 *
5637
	 * @param array $methods XMLRPC methods.
5638
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5639
	 */
5640 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5641
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5642
5643
		if ( ! $this->connection_manager ) {
5644
			$this->connection_manager = new Connection_Manager();
5645
		}
5646
5647
		return $this->connection_manager->xmlrpc_methods( $methods );
5648
	}
5649
5650
	/**
5651
	 * Register additional public XMLRPC methods.
5652
	 *
5653
	 * @deprecated since 7.7.0
5654
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5655
	 *
5656
	 * @param array $methods Public XMLRPC methods.
5657
	 * @return array Public XMLRPC methods, with the getOptions one.
5658
	 */
5659 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5660
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5661
5662
		if ( ! $this->connection_manager ) {
5663
			$this->connection_manager = new Connection_Manager();
5664
		}
5665
5666
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5667
	}
5668
5669
	/**
5670
	 * Handles a getOptions XMLRPC method call.
5671
	 *
5672
	 * @deprecated since 7.7.0
5673
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5674
	 *
5675
	 * @param array $args method call arguments.
5676
	 * @return array an amended XMLRPC server options array.
5677
	 */
5678 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5679
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5680
5681
		if ( ! $this->connection_manager ) {
5682
			$this->connection_manager = new Connection_Manager();
5683
		}
5684
5685
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
Bug introduced by
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

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

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

Loading history...
5686
	}
5687
5688
	/**
5689
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5690
	 *
5691
	 * @deprecated since 7.7.0
5692
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5693
	 *
5694
	 * @param array $options Standard Core options.
5695
	 * @return array Amended options.
5696
	 */
5697 View Code Duplication
	public function xmlrpc_options( $options ) {
5698
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5699
5700
		if ( ! $this->connection_manager ) {
5701
			$this->connection_manager = new Connection_Manager();
5702
		}
5703
5704
		return $this->connection_manager->xmlrpc_options( $options );
5705
	}
5706
5707
	/**
5708
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5709
	 * SET: state( $key, $value );
5710
	 * GET: $value = state( $key );
5711
	 *
5712
	 * @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...
5713
	 * @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...
5714
	 * @param bool   $restate private
5715
	 */
5716
	public static function state( $key = null, $value = null, $restate = false ) {
5717
		static $state = array();
5718
		static $path, $domain;
5719
		if ( ! isset( $path ) ) {
5720
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5721
			$admin_url = self::admin_url();
5722
			$bits      = wp_parse_url( $admin_url );
5723
5724
			if ( is_array( $bits ) ) {
5725
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5726
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5727
			} else {
5728
				$path = $domain = null;
5729
			}
5730
		}
5731
5732
		// Extract state from cookies and delete cookies
5733
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5734
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5735
			unset( $_COOKIE['jetpackState'] );
5736
			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...
5737
				if ( strlen( $v ) ) {
5738
					$state[ $k ] = $v;
5739
				}
5740
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5741
			}
5742
		}
5743
5744
		if ( $restate ) {
5745
			foreach ( $state as $k => $v ) {
5746
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5747
			}
5748
			return;
5749
		}
5750
5751
		// Get a state variable.
5752
		if ( isset( $key ) && ! isset( $value ) ) {
5753
			if ( array_key_exists( $key, $state ) ) {
5754
				return $state[ $key ];
5755
			}
5756
			return null;
5757
		}
5758
5759
		// Set a state variable.
5760
		if ( isset( $key ) && isset( $value ) ) {
5761
			if ( is_array( $value ) && isset( $value[0] ) ) {
5762
				$value = $value[0];
5763
			}
5764
			$state[ $key ] = $value;
5765
			if ( ! headers_sent() ) {
5766
				if ( self::should_set_cookie( $key ) ) {
5767
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5768
				}
5769
			}
5770
		}
5771
	}
5772
5773
	public static function restate() {
5774
		self::state( null, null, true );
5775
	}
5776
5777
	/**
5778
	 * Determines whether the jetpackState[$key] value should be added to the
5779
	 * cookie.
5780
	 *
5781
	 * @param string $key The state key.
5782
	 *
5783
	 * @return boolean Whether the value should be added to the cookie.
5784
	 */
5785
	public static function should_set_cookie( $key ) {
5786
		global $current_screen;
5787
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5788
5789
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5790
			return false;
5791
		}
5792
5793
		return true;
5794
	}
5795
5796
	public static function check_privacy( $file ) {
5797
		static $is_site_publicly_accessible = null;
5798
5799
		if ( is_null( $is_site_publicly_accessible ) ) {
5800
			$is_site_publicly_accessible = false;
5801
5802
			$rpc = new Jetpack_IXR_Client();
5803
5804
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5805
			if ( $success ) {
5806
				$response = $rpc->getResponse();
5807
				if ( $response ) {
5808
					$is_site_publicly_accessible = true;
5809
				}
5810
			}
5811
5812
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5813
		}
5814
5815
		if ( $is_site_publicly_accessible ) {
5816
			return;
5817
		}
5818
5819
		$module_slug = self::get_module_slug( $file );
5820
5821
		$privacy_checks = self::state( 'privacy_checks' );
5822
		if ( ! $privacy_checks ) {
5823
			$privacy_checks = $module_slug;
5824
		} else {
5825
			$privacy_checks .= ",$module_slug";
5826
		}
5827
5828
		self::state( 'privacy_checks', $privacy_checks );
5829
	}
5830
5831
	/**
5832
	 * Helper method for multicall XMLRPC.
5833
	 *
5834
	 * @deprecated since 8.9.0
5835
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5836
	 *
5837
	 * @param ...$args Args for the async_call.
5838
	 */
5839
	public static function xmlrpc_async_call( ...$args ) {
5840
5841
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5842
5843
		global $blog_id;
5844
		static $clients = array();
5845
5846
		$client_blog_id = is_multisite() ? $blog_id : 0;
5847
5848
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5849
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => Connection_Manager::CONNECTION_OWNER ) );
5850
			if ( function_exists( 'ignore_user_abort' ) ) {
5851
				ignore_user_abort( true );
5852
			}
5853
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5854
		}
5855
5856
		if ( ! empty( $args[0] ) ) {
5857
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5858
		} elseif ( is_multisite() ) {
5859
			foreach ( $clients as $client_blog_id => $client ) {
5860
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5861
					continue;
5862
				}
5863
5864
				$switch_success = switch_to_blog( $client_blog_id, true );
5865
				if ( ! $switch_success ) {
5866
					continue;
5867
				}
5868
5869
				flush();
5870
				$client->query();
5871
5872
				restore_current_blog();
5873
			}
5874
		} else {
5875
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5876
				flush();
5877
				$clients[0]->query();
5878
			}
5879
		}
5880
	}
5881
5882
	/**
5883
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5884
	 *
5885
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5886
	 *
5887
	 * @param string $url WordPress.com static resource URL.
5888
	 */
5889
	public static function staticize_subdomain( $url ) {
5890
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5891
		return Assets::staticize_subdomain( $url );
5892
	}
5893
5894
	/* JSON API Authorization */
5895
5896
	/**
5897
	 * Handles the login action for Authorizing the JSON API
5898
	 */
5899
	function login_form_json_api_authorization() {
5900
		$this->verify_json_api_authorization_request();
5901
5902
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5903
5904
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5905
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5906
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5907
	}
5908
5909
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5910
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5911
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5912
			return $url;
5913
		}
5914
5915
		$parsed_url = wp_parse_url( $url );
5916
		$url        = strtok( $url, '?' );
5917
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5918
		if ( ! empty( $parsed_url['query'] ) ) {
5919
			$url .= "&{$parsed_url['query']}";
5920
		}
5921
5922
		return $url;
5923
	}
5924
5925
	// Make sure the POSTed request is handled by the same action
5926
	function preserve_action_in_login_form_for_json_api_authorization() {
5927
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5928
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5929
	}
5930
5931
	// If someone logs in to approve API access, store the Access Code in usermeta
5932
	function store_json_api_authorization_token( $user_login, $user ) {
5933
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5934
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5935
		$token = wp_generate_password( 32, false );
5936
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5937
	}
5938
5939
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5940
	function allow_wpcom_public_api_domain( $domains ) {
5941
		$domains[] = 'public-api.wordpress.com';
5942
		return $domains;
5943
	}
5944
5945
	static function is_redirect_encoded( $redirect_url ) {
5946
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5947
	}
5948
5949
	// Add all wordpress.com environments to the safe redirect allowed list.
5950
	function allow_wpcom_environments( $domains ) {
5951
		$domains[] = 'wordpress.com';
5952
		$domains[] = 'wpcalypso.wordpress.com';
5953
		$domains[] = 'horizon.wordpress.com';
5954
		$domains[] = 'calypso.localhost';
5955
		return $domains;
5956
	}
5957
5958
	// Add the Access Code details to the public-api.wordpress.com redirect
5959
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5960
		return add_query_arg(
5961
			urlencode_deep(
5962
				array(
5963
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5964
					'jetpack-user-id' => (int) $user->ID,
5965
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5966
				)
5967
			),
5968
			$redirect_to
5969
		);
5970
	}
5971
5972
	/**
5973
	 * Verifies the request by checking the signature
5974
	 *
5975
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5976
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5977
	 *
5978
	 * @param null|array $environment
5979
	 */
5980
	function verify_json_api_authorization_request( $environment = null ) {
5981
		$environment = is_null( $environment )
5982
			? $_REQUEST
5983
			: $environment;
5984
5985
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5986
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
5987
		if ( ! $token || empty( $token->secret ) ) {
5988
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5989
		}
5990
5991
		$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' );
5992
5993
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5994
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5995
			/**
5996
			 * Jetpack authorisation request Error.
5997
			 *
5998
			 * @since 7.5.0
5999
			 */
6000
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6001
			$die_error = sprintf(
6002
				/* translators: %s is a URL */
6003
				__( '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' ),
6004
				Redirect::get_url( 'jetpack-support-double-encoding' )
6005
			);
6006
		}
6007
6008
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6009
6010
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6011
			$signature = $jetpack_signature->sign_request(
6012
				$environment['token'],
6013
				$environment['timestamp'],
6014
				$environment['nonce'],
6015
				'',
6016
				'GET',
6017
				$environment['jetpack_json_api_original_query'],
6018
				null,
6019
				true
6020
			);
6021
		} else {
6022
			$signature = $jetpack_signature->sign_current_request(
6023
				array(
6024
					'body'   => null,
6025
					'method' => 'GET',
6026
				)
6027
			);
6028
		}
6029
6030
		if ( ! $signature ) {
6031
			wp_die( $die_error );
6032
		} elseif ( is_wp_error( $signature ) ) {
6033
			wp_die( $die_error );
6034
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6035
			if ( is_ssl() ) {
6036
				// 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
6037
				$signature = $jetpack_signature->sign_current_request(
6038
					array(
6039
						'scheme' => 'http',
6040
						'body'   => null,
6041
						'method' => 'GET',
6042
					)
6043
				);
6044
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6045
					wp_die( $die_error );
6046
				}
6047
			} else {
6048
				wp_die( $die_error );
6049
			}
6050
		}
6051
6052
		$timestamp = (int) $environment['timestamp'];
6053
		$nonce     = stripslashes( (string) $environment['nonce'] );
6054
6055
		if ( ! $this->connection_manager ) {
6056
			$this->connection_manager = new Connection_Manager();
6057
		}
6058
6059
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6060
			// De-nonce the nonce, at least for 5 minutes.
6061
			// 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)
6062
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6063
			if ( $old_nonce_time < time() - 300 ) {
6064
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6065
			}
6066
		}
6067
6068
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6069
		$data_filters = array(
6070
			'state'        => 'opaque',
6071
			'client_id'    => 'int',
6072
			'client_title' => 'string',
6073
			'client_image' => 'url',
6074
		);
6075
6076
		foreach ( $data_filters as $key => $sanitation ) {
6077
			if ( ! isset( $data->$key ) ) {
6078
				wp_die( $die_error );
6079
			}
6080
6081
			switch ( $sanitation ) {
6082
				case 'int':
6083
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6084
					break;
6085
				case 'opaque':
6086
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6087
					break;
6088
				case 'string':
6089
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6090
					break;
6091
				case 'url':
6092
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6093
					break;
6094
			}
6095
		}
6096
6097
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6098
			wp_die( $die_error );
6099
		}
6100
	}
6101
6102
	function login_message_json_api_authorization( $message ) {
6103
		return '<p class="message">' . sprintf(
6104
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6105
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6106
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6107
	}
6108
6109
	/**
6110
	 * Get $content_width, but with a <s>twist</s> filter.
6111
	 */
6112
	public static function get_content_width() {
6113
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6114
			? $GLOBALS['content_width']
6115
			: false;
6116
		/**
6117
		 * Filter the Content Width value.
6118
		 *
6119
		 * @since 2.2.3
6120
		 *
6121
		 * @param string $content_width Content Width value.
6122
		 */
6123
		return apply_filters( 'jetpack_content_width', $content_width );
6124
	}
6125
6126
	/**
6127
	 * Pings the WordPress.com Mirror Site for the specified options.
6128
	 *
6129
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6130
	 *
6131
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6132
	 */
6133
	public function get_cloud_site_options( $option_names ) {
6134
		$option_names = array_filter( (array) $option_names, 'is_string' );
6135
6136
		$xml = new Jetpack_IXR_Client();
6137
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6138
		if ( $xml->isError() ) {
6139
			return array(
6140
				'error_code' => $xml->getErrorCode(),
6141
				'error_msg'  => $xml->getErrorMessage(),
6142
			);
6143
		}
6144
		$cloud_site_options = $xml->getResponse();
6145
6146
		return $cloud_site_options;
6147
	}
6148
6149
	/**
6150
	 * Checks if the site is currently in an identity crisis.
6151
	 *
6152
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6153
	 */
6154
	public static function check_identity_crisis() {
6155
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6156
			return false;
6157
		}
6158
6159
		return Jetpack_Options::get_option( 'sync_error_idc' );
6160
	}
6161
6162
	/**
6163
	 * Checks whether the home and siteurl specifically are allowed.
6164
	 * Written so that we don't have re-check $key and $value params every time
6165
	 * we want to check if this site is allowed, for example in footer.php
6166
	 *
6167
	 * @since  3.8.0
6168
	 * @return bool True = already allowed False = not on the allowed list.
6169
	 */
6170
	public static function is_staging_site() {
6171
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6172
		return ( new Status() )->is_staging_site();
6173
	}
6174
6175
	/**
6176
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6177
	 *
6178
	 * @since 4.4.0
6179
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6180
	 *
6181
	 * @return bool
6182
	 */
6183
	public static function validate_sync_error_idc_option() {
6184
		$is_valid = false;
6185
6186
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6187
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6188
		if ( $sync_error && self::sync_idc_optin() ) {
6189
			$local_options = self::get_sync_error_idc_option();
6190
			// Ensure all values are set.
6191
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6192
6193
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6194
				if (
6195
						isset( $sync_error['wpcom_home'] ) &&
6196
						isset( $sync_error['wpcom_siteurl'] ) &&
6197
						$sync_error['wpcom_home'] === $local_options['home'] &&
6198
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6199
				) {
6200
					$is_valid = false;
6201
					// Enable migrate_for_idc so that sync actions are accepted.
6202
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6203
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6204
					$is_valid = true;
6205
				}
6206
			}
6207
		}
6208
6209
		/**
6210
		 * Filters whether the sync_error_idc option is valid.
6211
		 *
6212
		 * @since 4.4.0
6213
		 *
6214
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6215
		 */
6216
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6217
6218
		if ( ! $is_valid && $sync_error ) {
6219
			// Since the option exists, and did not validate, delete it
6220
			Jetpack_Options::delete_option( 'sync_error_idc' );
6221
		}
6222
6223
		return $is_valid;
6224
	}
6225
6226
	/**
6227
	 * Normalizes a url by doing three things:
6228
	 *  - Strips protocol
6229
	 *  - Strips www
6230
	 *  - Adds a trailing slash
6231
	 *
6232
	 * @since 4.4.0
6233
	 * @param string $url
6234
	 * @return WP_Error|string
6235
	 */
6236
	public static function normalize_url_protocol_agnostic( $url ) {
6237
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6238 View Code Duplication
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsed_url of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

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

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

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

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
6239
			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...
6240
		}
6241
6242
		// Strip www and protocols
6243
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6244
		return $url;
6245
	}
6246
6247
	/**
6248
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6249
	 *
6250
	 * @since 4.4.0
6251
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6252
	 *
6253
	 * @param array $response
6254
	 * @return array Array of the local urls, wpcom urls, and error code
6255
	 */
6256
	public static function get_sync_error_idc_option( $response = array() ) {
6257
		// Since the local options will hit the database directly, store the values
6258
		// in a transient to allow for autoloading and caching on subsequent views.
6259
		$local_options = get_transient( 'jetpack_idc_local' );
6260
		if ( false === $local_options ) {
6261
			$local_options = array(
6262
				'home'    => Functions::home_url(),
6263
				'siteurl' => Functions::site_url(),
6264
			);
6265
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6266
		}
6267
6268
		$options = array_merge( $local_options, $response );
6269
6270
		$returned_values = array();
6271
		foreach ( $options as $key => $option ) {
6272
			if ( 'error_code' === $key ) {
6273
				$returned_values[ $key ] = $option;
6274
				continue;
6275
			}
6276
6277
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6278
				continue;
6279
			}
6280
6281
			$returned_values[ $key ] = $normalized_url;
6282
		}
6283
6284
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6285
6286
		return $returned_values;
6287
	}
6288
6289
	/**
6290
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6291
	 * If set to true, the site will be put into staging mode.
6292
	 *
6293
	 * @since 4.3.2
6294
	 * @return bool
6295
	 */
6296
	public static function sync_idc_optin() {
6297
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6298
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6299
		} else {
6300
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6301
		}
6302
6303
		/**
6304
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
6305
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
6306
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6307
		 *
6308
		 * @since 4.3.2
6309
		 *
6310
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6311
		 */
6312
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6313
	}
6314
6315
	/**
6316
	 * Maybe Use a .min.css stylesheet, maybe not.
6317
	 *
6318
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6319
	 */
6320
	public static function maybe_min_asset( $url, $path, $plugin ) {
6321
		// Short out on things trying to find actual paths.
6322
		if ( ! $path || empty( $plugin ) ) {
6323
			return $url;
6324
		}
6325
6326
		$path = ltrim( $path, '/' );
6327
6328
		// Strip out the abspath.
6329
		$base = dirname( plugin_basename( $plugin ) );
6330
6331
		// Short out on non-Jetpack assets.
6332
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6333
			return $url;
6334
		}
6335
6336
		// File name parsing.
6337
		$file              = "{$base}/{$path}";
6338
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6339
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6340
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6341
		$extension         = array_shift( $file_name_parts_r );
6342
6343
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6344
			// Already pointing at the minified version.
6345
			if ( 'min' === $file_name_parts_r[0] ) {
6346
				return $url;
6347
			}
6348
6349
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6350
			if ( file_exists( $min_full_path ) ) {
6351
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6352
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6353
				if ( 'css' === $extension ) {
6354
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6355
					self::$min_assets[ $key ] = $path;
6356
				}
6357
			}
6358
		}
6359
6360
		return $url;
6361
	}
6362
6363
	/**
6364
	 * If the asset is minified, let's flag .min as the suffix.
6365
	 *
6366
	 * Attached to `style_loader_src` filter.
6367
	 *
6368
	 * @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...
6369
	 * @param string $handle The registered handle of the script in question.
6370
	 * @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...
6371
	 */
6372
	public static function set_suffix_on_min( $src, $handle ) {
6373
		if ( false === strpos( $src, '.min.css' ) ) {
6374
			return $src;
6375
		}
6376
6377
		if ( ! empty( self::$min_assets ) ) {
6378
			foreach ( self::$min_assets as $file => $path ) {
6379
				if ( false !== strpos( $src, $file ) ) {
6380
					wp_style_add_data( $handle, 'suffix', '.min' );
6381
					return $src;
6382
				}
6383
			}
6384
		}
6385
6386
		return $src;
6387
	}
6388
6389
	/**
6390
	 * Maybe inlines a stylesheet.
6391
	 *
6392
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6393
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6394
	 *
6395
	 * Attached to `style_loader_tag` filter.
6396
	 *
6397
	 * @param string $tag The tag that would link to the external asset.
6398
	 * @param string $handle The registered handle of the script in question.
6399
	 *
6400
	 * @return string
6401
	 */
6402
	public static function maybe_inline_style( $tag, $handle ) {
6403
		global $wp_styles;
6404
		$item = $wp_styles->registered[ $handle ];
6405
6406
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6407
			return $tag;
6408
		}
6409
6410
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6411
			$href = $matches[1];
6412
			// Strip off query string
6413
			if ( $pos = strpos( $href, '?' ) ) {
6414
				$href = substr( $href, 0, $pos );
6415
			}
6416
			// Strip off fragment
6417
			if ( $pos = strpos( $href, '#' ) ) {
6418
				$href = substr( $href, 0, $pos );
6419
			}
6420
		} else {
6421
			return $tag;
6422
		}
6423
6424
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6425
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6426
			return $tag;
6427
		}
6428
6429
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6430
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6431
			// And this isn't the pass that actually deals with the RTL version...
6432
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6433
				// Short out, as the RTL version will deal with it in a moment.
6434
				return $tag;
6435
			}
6436
		}
6437
6438
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6439
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6440
		if ( $css ) {
6441
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6442
			if ( empty( $item->extra['after'] ) ) {
6443
				wp_add_inline_style( $handle, $css );
6444
			} else {
6445
				array_unshift( $item->extra['after'], $css );
6446
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6447
			}
6448
		}
6449
6450
		return $tag;
6451
	}
6452
6453
	/**
6454
	 * Loads a view file from the views
6455
	 *
6456
	 * Data passed in with the $data parameter will be available in the
6457
	 * template file as $data['value']
6458
	 *
6459
	 * @param string $template - Template file to load
6460
	 * @param array  $data - Any data to pass along to the template
6461
	 * @return boolean - If template file was found
6462
	 **/
6463
	public function load_view( $template, $data = array() ) {
6464
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6465
6466
		if ( file_exists( $views_dir . $template ) ) {
6467
			require_once $views_dir . $template;
6468
			return true;
6469
		}
6470
6471
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6472
		return false;
6473
	}
6474
6475
	/**
6476
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6477
	 */
6478
	public function deprecated_hooks() {
6479
		$filter_deprecated_list = array(
6480
			'jetpack_bail_on_shortcode'                    => array(
6481
				'replacement' => 'jetpack_shortcodes_to_include',
6482
				'version'     => 'jetpack-3.1.0',
6483
			),
6484
			'wpl_sharing_2014_1'                           => array(
6485
				'replacement' => null,
6486
				'version'     => 'jetpack-3.6.0',
6487
			),
6488
			'jetpack-tools-to-include'                     => array(
6489
				'replacement' => 'jetpack_tools_to_include',
6490
				'version'     => 'jetpack-3.9.0',
6491
			),
6492
			'jetpack_identity_crisis_options_to_check'     => array(
6493
				'replacement' => null,
6494
				'version'     => 'jetpack-4.0.0',
6495
			),
6496
			'update_option_jetpack_single_user_site'       => array(
6497
				'replacement' => null,
6498
				'version'     => 'jetpack-4.3.0',
6499
			),
6500
			'audio_player_default_colors'                  => array(
6501
				'replacement' => null,
6502
				'version'     => 'jetpack-4.3.0',
6503
			),
6504
			'add_option_jetpack_featured_images_enabled'   => array(
6505
				'replacement' => null,
6506
				'version'     => 'jetpack-4.3.0',
6507
			),
6508
			'add_option_jetpack_update_details'            => array(
6509
				'replacement' => null,
6510
				'version'     => 'jetpack-4.3.0',
6511
			),
6512
			'add_option_jetpack_updates'                   => array(
6513
				'replacement' => null,
6514
				'version'     => 'jetpack-4.3.0',
6515
			),
6516
			'add_option_jetpack_network_name'              => array(
6517
				'replacement' => null,
6518
				'version'     => 'jetpack-4.3.0',
6519
			),
6520
			'add_option_jetpack_network_allow_new_registrations' => array(
6521
				'replacement' => null,
6522
				'version'     => 'jetpack-4.3.0',
6523
			),
6524
			'add_option_jetpack_network_add_new_users'     => array(
6525
				'replacement' => null,
6526
				'version'     => 'jetpack-4.3.0',
6527
			),
6528
			'add_option_jetpack_network_site_upload_space' => array(
6529
				'replacement' => null,
6530
				'version'     => 'jetpack-4.3.0',
6531
			),
6532
			'add_option_jetpack_network_upload_file_types' => array(
6533
				'replacement' => null,
6534
				'version'     => 'jetpack-4.3.0',
6535
			),
6536
			'add_option_jetpack_network_enable_administration_menus' => array(
6537
				'replacement' => null,
6538
				'version'     => 'jetpack-4.3.0',
6539
			),
6540
			'add_option_jetpack_is_multi_site'             => array(
6541
				'replacement' => null,
6542
				'version'     => 'jetpack-4.3.0',
6543
			),
6544
			'add_option_jetpack_is_main_network'           => array(
6545
				'replacement' => null,
6546
				'version'     => 'jetpack-4.3.0',
6547
			),
6548
			'add_option_jetpack_main_network_site'         => array(
6549
				'replacement' => null,
6550
				'version'     => 'jetpack-4.3.0',
6551
			),
6552
			'jetpack_sync_all_registered_options'          => array(
6553
				'replacement' => null,
6554
				'version'     => 'jetpack-4.3.0',
6555
			),
6556
			'jetpack_has_identity_crisis'                  => array(
6557
				'replacement' => 'jetpack_sync_error_idc_validation',
6558
				'version'     => 'jetpack-4.4.0',
6559
			),
6560
			'jetpack_is_post_mailable'                     => array(
6561
				'replacement' => null,
6562
				'version'     => 'jetpack-4.4.0',
6563
			),
6564
			'jetpack_seo_site_host'                        => array(
6565
				'replacement' => null,
6566
				'version'     => 'jetpack-5.1.0',
6567
			),
6568
			'jetpack_installed_plugin'                     => array(
6569
				'replacement' => 'jetpack_plugin_installed',
6570
				'version'     => 'jetpack-6.0.0',
6571
			),
6572
			'jetpack_holiday_snow_option_name'             => array(
6573
				'replacement' => null,
6574
				'version'     => 'jetpack-6.0.0',
6575
			),
6576
			'jetpack_holiday_chance_of_snow'               => array(
6577
				'replacement' => null,
6578
				'version'     => 'jetpack-6.0.0',
6579
			),
6580
			'jetpack_holiday_snow_js_url'                  => array(
6581
				'replacement' => null,
6582
				'version'     => 'jetpack-6.0.0',
6583
			),
6584
			'jetpack_is_holiday_snow_season'               => array(
6585
				'replacement' => null,
6586
				'version'     => 'jetpack-6.0.0',
6587
			),
6588
			'jetpack_holiday_snow_option_updated'          => array(
6589
				'replacement' => null,
6590
				'version'     => 'jetpack-6.0.0',
6591
			),
6592
			'jetpack_holiday_snowing'                      => array(
6593
				'replacement' => null,
6594
				'version'     => 'jetpack-6.0.0',
6595
			),
6596
			'jetpack_sso_auth_cookie_expirtation'          => array(
6597
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6598
				'version'     => 'jetpack-6.1.0',
6599
			),
6600
			'jetpack_cache_plans'                          => array(
6601
				'replacement' => null,
6602
				'version'     => 'jetpack-6.1.0',
6603
			),
6604
6605
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6606
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6607
				'version'     => 'jetpack-6.5.0',
6608
			),
6609
			'jetpack_enable_site_verification'             => array(
6610
				'replacement' => null,
6611
				'version'     => 'jetpack-6.5.0',
6612
			),
6613
			'can_display_jetpack_manage_notice'            => array(
6614
				'replacement' => null,
6615
				'version'     => 'jetpack-7.3.0',
6616
			),
6617
			'atd_http_post_timeout'                        => array(
6618
				'replacement' => null,
6619
				'version'     => 'jetpack-7.3.0',
6620
			),
6621
			'atd_service_domain'                           => array(
6622
				'replacement' => null,
6623
				'version'     => 'jetpack-7.3.0',
6624
			),
6625
			'atd_load_scripts'                             => array(
6626
				'replacement' => null,
6627
				'version'     => 'jetpack-7.3.0',
6628
			),
6629
			'jetpack_widget_authors_exclude'               => array(
6630
				'replacement' => 'jetpack_widget_authors_params',
6631
				'version'     => 'jetpack-7.7.0',
6632
			),
6633
			// Removed in Jetpack 7.9.0
6634
			'jetpack_pwa_manifest'                         => array(
6635
				'replacement' => null,
6636
				'version'     => 'jetpack-7.9.0',
6637
			),
6638
			'jetpack_pwa_background_color'                 => array(
6639
				'replacement' => null,
6640
				'version'     => 'jetpack-7.9.0',
6641
			),
6642
			'jetpack_check_mobile'                         => array(
6643
				'replacement' => null,
6644
				'version'     => 'jetpack-8.3.0',
6645
			),
6646
			'jetpack_mobile_stylesheet'                    => array(
6647
				'replacement' => null,
6648
				'version'     => 'jetpack-8.3.0',
6649
			),
6650
			'jetpack_mobile_template'                      => array(
6651
				'replacement' => null,
6652
				'version'     => 'jetpack-8.3.0',
6653
			),
6654
			'jetpack_mobile_theme_menu'                    => array(
6655
				'replacement' => null,
6656
				'version'     => 'jetpack-8.3.0',
6657
			),
6658
			'minileven_show_featured_images'               => array(
6659
				'replacement' => null,
6660
				'version'     => 'jetpack-8.3.0',
6661
			),
6662
			'minileven_attachment_size'                    => array(
6663
				'replacement' => null,
6664
				'version'     => 'jetpack-8.3.0',
6665
			),
6666
			'instagram_cache_oembed_api_response_body'     => array(
6667
				'replacement' => null,
6668
				'version'     => 'jetpack-9.1.0',
6669
			),
6670
			'jetpack_can_make_outbound_https'              => array(
6671
				'replacement' => null,
6672
				'version'     => 'jetpack-9.1.0',
6673
			),
6674
		);
6675
6676
		foreach ( $filter_deprecated_list as $tag => $args ) {
6677
			if ( has_filter( $tag ) ) {
6678
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6679
			}
6680
		}
6681
6682
		$action_deprecated_list = array(
6683
			'jetpack_updated_theme'        => array(
6684
				'replacement' => 'jetpack_updated_themes',
6685
				'version'     => 'jetpack-6.2.0',
6686
			),
6687
			'atd_http_post_error'          => array(
6688
				'replacement' => null,
6689
				'version'     => 'jetpack-7.3.0',
6690
			),
6691
			'mobile_reject_mobile'         => array(
6692
				'replacement' => null,
6693
				'version'     => 'jetpack-8.3.0',
6694
			),
6695
			'mobile_force_mobile'          => array(
6696
				'replacement' => null,
6697
				'version'     => 'jetpack-8.3.0',
6698
			),
6699
			'mobile_app_promo_download'    => array(
6700
				'replacement' => null,
6701
				'version'     => 'jetpack-8.3.0',
6702
			),
6703
			'mobile_setup'                 => array(
6704
				'replacement' => null,
6705
				'version'     => 'jetpack-8.3.0',
6706
			),
6707
			'jetpack_mobile_footer_before' => array(
6708
				'replacement' => null,
6709
				'version'     => 'jetpack-8.3.0',
6710
			),
6711
			'wp_mobile_theme_footer'       => array(
6712
				'replacement' => null,
6713
				'version'     => 'jetpack-8.3.0',
6714
			),
6715
			'minileven_credits'            => array(
6716
				'replacement' => null,
6717
				'version'     => 'jetpack-8.3.0',
6718
			),
6719
			'jetpack_mobile_header_before' => array(
6720
				'replacement' => null,
6721
				'version'     => 'jetpack-8.3.0',
6722
			),
6723
			'jetpack_mobile_header_after'  => array(
6724
				'replacement' => null,
6725
				'version'     => 'jetpack-8.3.0',
6726
			),
6727
		);
6728
6729
		foreach ( $action_deprecated_list as $tag => $args ) {
6730
			if ( has_action( $tag ) ) {
6731
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6732
			}
6733
		}
6734
	}
6735
6736
	/**
6737
	 * Converts any url in a stylesheet, to the correct absolute url.
6738
	 *
6739
	 * Considerations:
6740
	 *  - Normal, relative URLs     `feh.png`
6741
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6742
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6743
	 *  - Absolute URLs             `http://domain.com/feh.png`
6744
	 *  - Domain root relative URLs `/feh.png`
6745
	 *
6746
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6747
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6748
	 *
6749
	 * @return mixed|string
6750
	 */
6751
	public static function absolutize_css_urls( $css, $css_file_url ) {
6752
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6753
		$css_dir = dirname( $css_file_url );
6754
		$p       = wp_parse_url( $css_dir );
6755
		$domain  = sprintf(
6756
			'%1$s//%2$s%3$s%4$s',
6757
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6758
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6759
			$p['host'],
6760
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6761
		);
6762
6763
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6764
			$find = $replace = array();
6765
			foreach ( $matches as $match ) {
6766
				$url = trim( $match['path'], "'\" \t" );
6767
6768
				// If this is a data url, we don't want to mess with it.
6769
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6770
					continue;
6771
				}
6772
6773
				// If this is an absolute or protocol-agnostic url,
6774
				// we don't want to mess with it.
6775
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6776
					continue;
6777
				}
6778
6779
				switch ( substr( $url, 0, 1 ) ) {
6780
					case '/':
6781
						$absolute = $domain . $url;
6782
						break;
6783
					default:
6784
						$absolute = $css_dir . '/' . $url;
6785
				}
6786
6787
				$find[]    = $match[0];
6788
				$replace[] = sprintf( 'url("%s")', $absolute );
6789
			}
6790
			$css = str_replace( $find, $replace, $css );
6791
		}
6792
6793
		return $css;
6794
	}
6795
6796
	/**
6797
	 * This methods removes all of the registered css files on the front end
6798
	 * from Jetpack in favor of using a single file. In effect "imploding"
6799
	 * all the files into one file.
6800
	 *
6801
	 * Pros:
6802
	 * - Uses only ONE css asset connection instead of 15
6803
	 * - Saves a minimum of 56k
6804
	 * - Reduces server load
6805
	 * - Reduces time to first painted byte
6806
	 *
6807
	 * Cons:
6808
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6809
	 *      should not cause any issues with themes.
6810
	 * - Plugins/themes dequeuing styles no longer do anything. See
6811
	 *      jetpack_implode_frontend_css filter for a workaround
6812
	 *
6813
	 * For some situations developers may wish to disable css imploding and
6814
	 * instead operate in legacy mode where each file loads seperately and
6815
	 * can be edited individually or dequeued. This can be accomplished with
6816
	 * the following line:
6817
	 *
6818
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6819
	 *
6820
	 * @since 3.2
6821
	 **/
6822
	public function implode_frontend_css( $travis_test = false ) {
6823
		$do_implode = true;
6824
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6825
			$do_implode = false;
6826
		}
6827
6828
		// Do not implode CSS when the page loads via the AMP plugin.
6829
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6830
			$do_implode = false;
6831
		}
6832
6833
		/**
6834
		 * Allow CSS to be concatenated into a single jetpack.css file.
6835
		 *
6836
		 * @since 3.2.0
6837
		 *
6838
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6839
		 */
6840
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6841
6842
		// Do not use the imploded file when default behavior was altered through the filter
6843
		if ( ! $do_implode ) {
6844
			return;
6845
		}
6846
6847
		// We do not want to use the imploded file in dev mode, or if not connected
6848
		if ( ( new Status() )->is_offline_mode() || ! self::is_active() ) {
6849
			if ( ! $travis_test ) {
6850
				return;
6851
			}
6852
		}
6853
6854
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6855
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6856
			return;
6857
		}
6858
6859
		/*
6860
		 * Now we assume Jetpack is connected and able to serve the single
6861
		 * file.
6862
		 *
6863
		 * In the future there will be a check here to serve the file locally
6864
		 * or potentially from the Jetpack CDN
6865
		 *
6866
		 * For now:
6867
		 * - Enqueue a single imploded css file
6868
		 * - Zero out the style_loader_tag for the bundled ones
6869
		 * - Be happy, drink scotch
6870
		 */
6871
6872
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6873
6874
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6875
6876
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6877
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6878
	}
6879
6880
	function concat_remove_style_loader_tag( $tag, $handle ) {
6881
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6882
			$tag = '';
6883
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6884
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6885
			}
6886
		}
6887
6888
		return $tag;
6889
	}
6890
6891
	/**
6892
	 * @deprecated
6893
	 * @see Automattic\Jetpack\Assets\add_aync_script
6894
	 */
6895
	public function script_add_async( $tag, $handle, $src ) {
6896
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6897
	}
6898
6899
	/*
6900
	 * Check the heartbeat data
6901
	 *
6902
	 * Organizes the heartbeat data by severity.  For example, if the site
6903
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6904
	 *
6905
	 * Data will be added to "caution" array, if it either:
6906
	 *  - Out of date Jetpack version
6907
	 *  - Out of date WP version
6908
	 *  - Out of date PHP version
6909
	 *
6910
	 * $return array $filtered_data
6911
	 */
6912
	public static function jetpack_check_heartbeat_data() {
6913
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6914
6915
		$good    = array();
6916
		$caution = array();
6917
		$bad     = array();
6918
6919
		foreach ( $raw_data as $stat => $value ) {
6920
6921
			// Check jetpack version
6922
			if ( 'version' == $stat ) {
6923
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6924
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6925
					continue;
6926
				}
6927
			}
6928
6929
			// Check WP version
6930
			if ( 'wp-version' == $stat ) {
6931
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6932
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6933
					continue;
6934
				}
6935
			}
6936
6937
			// Check PHP version
6938
			if ( 'php-version' == $stat ) {
6939
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6940
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6941
					continue;
6942
				}
6943
			}
6944
6945
			// Check ID crisis
6946
			if ( 'identitycrisis' == $stat ) {
6947
				if ( 'yes' == $value ) {
6948
					$bad[ $stat ] = $value;
6949
					continue;
6950
				}
6951
			}
6952
6953
			// The rest are good :)
6954
			$good[ $stat ] = $value;
6955
		}
6956
6957
		$filtered_data = array(
6958
			'good'    => $good,
6959
			'caution' => $caution,
6960
			'bad'     => $bad,
6961
		);
6962
6963
		return $filtered_data;
6964
	}
6965
6966
	/*
6967
	 * This method is used to organize all options that can be reset
6968
	 * without disconnecting Jetpack.
6969
	 *
6970
	 * It is used in class.jetpack-cli.php to reset options
6971
	 *
6972
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6973
	 *
6974
	 * @return array of options to delete.
6975
	 */
6976
	public static function get_jetpack_options_for_reset() {
6977
		return Jetpack_Options::get_options_for_reset();
6978
	}
6979
6980
	/*
6981
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6982
	 * so we can bring them directly to their site in calypso.
6983
	 *
6984
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
6985
	 *
6986
	 * @param string | url
6987
	 * @return string | url without the guff
6988
	 */
6989
	public static function build_raw_urls( $url ) {
6990
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
6991
6992
		return ( new Status() )->get_site_suffix( $url );
6993
	}
6994
6995
	/**
6996
	 * Stores and prints out domains to prefetch for page speed optimization.
6997
	 *
6998
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
6999
	 *
7000
	 * @param string|array $urls URLs to hint.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $urls not be string|array|null?

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

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

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

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