Completed
Push — update/idc-endpoint-migration ( d9f03f...11415c )
by
unknown
34:21 queued 24:16
created

Jetpack::refresh_update_data()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

Loading history...
1713
	}
1714
1715
	/**
1716
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1717
	 *
1718
	 * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1719
	 * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1720
	 * users and this option will be available by default for everybody.
1721
	 *
1722
	 * @since 9.6.0
1723
	 * @since 9.7.0 returns is_connected in all cases and adds filter to the returned value
1724
	 *
1725
	 * @return bool is the site connection ready to be used?
1726
	 */
1727
	public static function is_connection_ready() {
1728
		/**
1729
		 * Allows filtering whether the connection is ready to be used. If true, this will enable the Jetpack UI and modules
1730
		 *
1731
		 * Modules will be enabled depending on the connection status and if the module requires a connection or user connection.
1732
		 *
1733
		 * @since 9.7.0
1734
		 *
1735
		 * @param bool                                  $is_connection_ready Is the connection ready?
1736
		 * @param Automattic\Jetpack\Connection\Manager $connection_manager Instance of the Manager class, can be used to check the connection status.
1737
		 */
1738
		return apply_filters( 'jetpack_is_connection_ready', self::connection()->is_connected(), self::connection() );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with self::connection().

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

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

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

Loading history...
1739
	}
1740
1741
	/**
1742
	 * Make an API call to WordPress.com for plan status
1743
	 *
1744
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1745
	 *
1746
	 * @return bool True if plan is updated, false if no update
1747
	 */
1748
	public static function refresh_active_plan_from_wpcom() {
1749
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1750
		return Jetpack_Plan::refresh_from_wpcom();
1751
	}
1752
1753
	/**
1754
	 * Get the plan that this Jetpack site is currently using
1755
	 *
1756
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1757
	 * @return array Active Jetpack plan details.
1758
	 */
1759
	public static function get_active_plan() {
1760
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1761
		return Jetpack_Plan::get();
1762
	}
1763
1764
	/**
1765
	 * Determine whether the active plan supports a particular feature
1766
	 *
1767
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1768
	 * @return bool True if plan supports feature, false if not.
1769
	 */
1770
	public static function active_plan_supports( $feature ) {
1771
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1772
		return Jetpack_Plan::supports( $feature );
1773
	}
1774
1775
	/**
1776
	 * Deprecated: Is Jetpack in development (offline) mode?
1777
	 *
1778
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1779
	 * and themes still use it, and we do not want to flood them with notices.
1780
	 *
1781
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1782
	 *
1783
	 * @deprecated since 8.0.
1784
	 */
1785
	public static function is_development_mode() {
1786
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1787
		return ( new Status() )->is_offline_mode();
1788
	}
1789
1790
	/**
1791
	 * Whether the site is currently onboarding or not.
1792
	 * A site is considered as being onboarded if it currently has an onboarding token.
1793
	 *
1794
	 * @since 5.8
1795
	 *
1796
	 * @access public
1797
	 * @static
1798
	 *
1799
	 * @return bool True if the site is currently onboarding, false otherwise
1800
	 */
1801
	public static function is_onboarding() {
1802
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1803
	}
1804
1805
	/**
1806
	 * Determines reason for Jetpack offline mode.
1807
	 */
1808
	public static function development_mode_trigger_text() {
1809
		$status = new Status();
1810
1811
		if ( ! $status->is_offline_mode() ) {
1812
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1813
		}
1814
1815
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1816
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1817
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1818
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1819
		} elseif ( $status->is_local_site() ) {
1820
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1821
			/** This filter is documented in packages/status/src/class-status.php */
1822
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1823
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1824
		} else {
1825
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1826
		}
1827
1828
		return $notice;
1829
1830
	}
1831
	/**
1832
	 * Get Jetpack offline mode notice text and notice class.
1833
	 *
1834
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1835
	 */
1836
	public static function show_development_mode_notice() {
1837 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1838
			$notice = sprintf(
1839
				/* translators: %s is a URL */
1840
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1841
				Redirect::get_url( 'jetpack-support-development-mode' )
1842
			);
1843
1844
			$notice .= ' ' . self::development_mode_trigger_text();
1845
1846
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1847
		}
1848
1849
		// Throw up a notice if using a development version and as for feedback.
1850
		if ( self::is_development_version() ) {
1851
			/* translators: %s is a URL */
1852
			$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' ) );
1853
1854
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1855
		}
1856
		// Throw up a notice if using staging mode
1857 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1858
			/* translators: %s is a URL */
1859
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1860
1861
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1862
		}
1863
	}
1864
1865
	/**
1866
	 * Whether Jetpack's version maps to a public release, or a development version.
1867
	 */
1868
	public static function is_development_version() {
1869
		/**
1870
		 * Allows filtering whether this is a development version of Jetpack.
1871
		 *
1872
		 * This filter is especially useful for tests.
1873
		 *
1874
		 * @since 4.3.0
1875
		 *
1876
		 * @param bool $development_version Is this a develoment version of Jetpack?
1877
		 */
1878
		return (bool) apply_filters(
1879
			'jetpack_development_version',
1880
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1881
		);
1882
	}
1883
1884
	/**
1885
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1886
	 */
1887
	public static function is_user_connected( $user_id = false ) {
1888
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1889
		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...
1890
	}
1891
1892
	/**
1893
	 * Get the wpcom user data of the current|specified connected user.
1894
	 */
1895
	public static function get_connected_user_data( $user_id = null ) {
1896
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1897
		return self::connection()->get_connected_user_data( $user_id );
1898
	}
1899
1900
	/**
1901
	 * Get the wpcom email of the current|specified connected user.
1902
	 */
1903
	public static function get_connected_user_email( $user_id = null ) {
1904
		if ( ! $user_id ) {
1905
			$user_id = get_current_user_id();
1906
		}
1907
1908
		$xml = new Jetpack_IXR_Client(
1909
			array(
1910
				'user_id' => $user_id,
1911
			)
1912
		);
1913
		$xml->query( 'wpcom.getUserEmail' );
1914
		if ( ! $xml->isError() ) {
1915
			return $xml->getResponse();
1916
		}
1917
		return false;
1918
	}
1919
1920
	/**
1921
	 * Get the wpcom email of the master user.
1922
	 */
1923
	public static function get_master_user_email() {
1924
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1925
		if ( $master_user_id ) {
1926
			return self::get_connected_user_email( $master_user_id );
1927
		}
1928
		return '';
1929
	}
1930
1931
	/**
1932
	 * Whether the current user is the connection owner.
1933
	 *
1934
	 * @deprecated since 7.7
1935
	 *
1936
	 * @return bool Whether the current user is the connection owner.
1937
	 */
1938
	public function current_user_is_connection_owner() {
1939
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1940
		return self::connection()->is_connection_owner();
1941
	}
1942
1943
	/**
1944
	 * Gets current user IP address.
1945
	 *
1946
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1947
	 *
1948
	 * @return string                  Current user IP address.
1949
	 */
1950
	public static function current_user_ip( $check_all_headers = false ) {
1951
		if ( $check_all_headers ) {
1952
			foreach ( array(
1953
				'HTTP_CF_CONNECTING_IP',
1954
				'HTTP_CLIENT_IP',
1955
				'HTTP_X_FORWARDED_FOR',
1956
				'HTTP_X_FORWARDED',
1957
				'HTTP_X_CLUSTER_CLIENT_IP',
1958
				'HTTP_FORWARDED_FOR',
1959
				'HTTP_FORWARDED',
1960
				'HTTP_VIA',
1961
			) as $key ) {
1962
				if ( ! empty( $_SERVER[ $key ] ) ) {
1963
					return $_SERVER[ $key ];
1964
				}
1965
			}
1966
		}
1967
1968
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1969
	}
1970
1971
	/**
1972
	 * Synchronize connected user role changes
1973
	 */
1974
	function user_role_change( $user_id ) {
1975
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1976
		Users::user_role_change( $user_id );
1977
	}
1978
1979
	/**
1980
	 * Loads the currently active modules.
1981
	 */
1982
	public static function load_modules() {
1983
		$is_offline_mode = ( new Status() )->is_offline_mode();
1984
		if (
1985
			! self::is_connection_ready()
1986
			&& ! $is_offline_mode
1987
			&& ! self::is_onboarding()
1988
			&& (
1989
				! is_multisite()
1990
				|| ! get_site_option( 'jetpack_protect_active' )
1991
			)
1992
		) {
1993
			return;
1994
		}
1995
1996
		$version = Jetpack_Options::get_option( 'version' );
1997 View Code Duplication
		if ( ! $version ) {
1998
			$version = $old_version = JETPACK__VERSION . ':' . time();
1999
			/** This action is documented in class.jetpack.php */
2000
			do_action( 'updating_jetpack_version', $version, false );
2001
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2002
		}
2003
		list( $version ) = explode( ':', $version );
2004
2005
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
2006
2007
		$modules_data = array();
2008
2009
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
2010
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
2011
			$updated_modules = array();
2012
			foreach ( $modules as $module ) {
2013
				$modules_data[ $module ] = self::get_module( $module );
2014
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
2015
					continue;
2016
				}
2017
2018
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2019
					continue;
2020
				}
2021
2022
				$updated_modules[] = $module;
2023
			}
2024
2025
			$modules = array_diff( $modules, $updated_modules );
2026
		}
2027
2028
		$is_site_connection = self::connection()->is_site_connection();
2029
2030
		foreach ( $modules as $index => $module ) {
2031
			// If we're in offline/site-connection mode, disable modules requiring a connection/user connection.
2032
			if ( $is_offline_mode || $is_site_connection ) {
2033
				// Prime the pump if we need to
2034
				if ( empty( $modules_data[ $module ] ) ) {
2035
					$modules_data[ $module ] = self::get_module( $module );
2036
				}
2037
				// If the module requires a connection, but we're in local mode, don't include it.
2038
				if ( $is_offline_mode && $modules_data[ $module ]['requires_connection'] ) {
2039
					continue;
2040
				}
2041
2042
				if ( $is_site_connection && $modules_data[ $module ]['requires_user_connection'] ) {
2043
					continue;
2044
				}
2045
			}
2046
2047
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2048
				continue;
2049
			}
2050
2051
			if ( ! include_once self::get_module_path( $module ) ) {
2052
				unset( $modules[ $index ] );
2053
				self::update_active_modules( array_values( $modules ) );
2054
				continue;
2055
			}
2056
2057
			/**
2058
			 * Fires when a specific module is loaded.
2059
			 * The dynamic part of the hook, $module, is the module slug.
2060
			 *
2061
			 * @since 1.1.0
2062
			 */
2063
			do_action( 'jetpack_module_loaded_' . $module );
2064
		}
2065
2066
		/**
2067
		 * Fires when all the modules are loaded.
2068
		 *
2069
		 * @since 1.1.0
2070
		 */
2071
		do_action( 'jetpack_modules_loaded' );
2072
2073
		// 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.
2074
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2075
	}
2076
2077
	/**
2078
	 * Check if Jetpack's REST API compat file should be included
2079
	 *
2080
	 * @action plugins_loaded
2081
	 * @return null
2082
	 */
2083
	public function check_rest_api_compat() {
2084
		/**
2085
		 * Filters the list of REST API compat files to be included.
2086
		 *
2087
		 * @since 2.2.5
2088
		 *
2089
		 * @param array $args Array of REST API compat files to include.
2090
		 */
2091
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2092
2093
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2094
			require_once $_jetpack_rest_api_compat_include;
2095
		}
2096
	}
2097
2098
	/**
2099
	 * Gets all plugins currently active in values, regardless of whether they're
2100
	 * traditionally activated or network activated.
2101
	 *
2102
	 * @todo Store the result in core's object cache maybe?
2103
	 */
2104
	public static function get_active_plugins() {
2105
		$active_plugins = (array) get_option( 'active_plugins', array() );
2106
2107
		if ( is_multisite() ) {
2108
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2109
			// whereas active_plugins stores them in the values.
2110
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2111
			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...
2112
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2113
			}
2114
		}
2115
2116
		sort( $active_plugins );
2117
2118
		return array_unique( $active_plugins );
2119
	}
2120
2121
	/**
2122
	 * Gets and parses additional plugin data to send with the heartbeat data
2123
	 *
2124
	 * @since 3.8.1
2125
	 *
2126
	 * @return array Array of plugin data
2127
	 */
2128
	public static function get_parsed_plugin_data() {
2129
		if ( ! function_exists( 'get_plugins' ) ) {
2130
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2131
		}
2132
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2133
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2134
		$active_plugins = self::get_active_plugins();
2135
2136
		$plugins = array();
2137
		foreach ( $all_plugins as $path => $plugin_data ) {
2138
			$plugins[ $path ] = array(
2139
				'is_active' => in_array( $path, $active_plugins ),
2140
				'file'      => $path,
2141
				'name'      => $plugin_data['Name'],
2142
				'version'   => $plugin_data['Version'],
2143
				'author'    => $plugin_data['Author'],
2144
			);
2145
		}
2146
2147
		return $plugins;
2148
	}
2149
2150
	/**
2151
	 * Gets and parses theme data to send with the heartbeat data
2152
	 *
2153
	 * @since 3.8.1
2154
	 *
2155
	 * @return array Array of theme data
2156
	 */
2157
	public static function get_parsed_theme_data() {
2158
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2159
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2160
2161
		$themes = array();
2162
		foreach ( $all_themes as $slug => $theme_data ) {
2163
			$theme_headers = array();
2164
			foreach ( $header_keys as $header_key ) {
2165
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2166
			}
2167
2168
			$themes[ $slug ] = array(
2169
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2170
				'slug'            => $slug,
2171
				'theme_root'      => $theme_data->get_theme_root_uri(),
2172
				'parent'          => $theme_data->parent(),
2173
				'headers'         => $theme_headers,
2174
			);
2175
		}
2176
2177
		return $themes;
2178
	}
2179
2180
	/**
2181
	 * Checks whether a specific plugin is active.
2182
	 *
2183
	 * We don't want to store these in a static variable, in case
2184
	 * there are switch_to_blog() calls involved.
2185
	 */
2186
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2187
		return in_array( $plugin, self::get_active_plugins() );
2188
	}
2189
2190
	/**
2191
	 * Check if Jetpack's Open Graph tags should be used.
2192
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2193
	 *
2194
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2195
	 * @action plugins_loaded
2196
	 * @return null
2197
	 */
2198
	public function check_open_graph() {
2199
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2200
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2201
		}
2202
2203
		$active_plugins = self::get_active_plugins();
2204
2205
		if ( ! empty( $active_plugins ) ) {
2206
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2207
				if ( in_array( $plugin, $active_plugins ) ) {
2208
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2209
					break;
2210
				}
2211
			}
2212
		}
2213
2214
		/**
2215
		 * Allow the addition of Open Graph Meta Tags to all pages.
2216
		 *
2217
		 * @since 2.0.3
2218
		 *
2219
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2220
		 */
2221
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2222
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2223
		}
2224
	}
2225
2226
	/**
2227
	 * Check if Jetpack's Twitter tags should be used.
2228
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2229
	 *
2230
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2231
	 * @action plugins_loaded
2232
	 * @return null
2233
	 */
2234
	public function check_twitter_tags() {
2235
2236
		$active_plugins = self::get_active_plugins();
2237
2238
		if ( ! empty( $active_plugins ) ) {
2239
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2240
				if ( in_array( $plugin, $active_plugins ) ) {
2241
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2242
					break;
2243
				}
2244
			}
2245
		}
2246
2247
		/**
2248
		 * Allow Twitter Card Meta tags to be disabled.
2249
		 *
2250
		 * @since 2.6.0
2251
		 *
2252
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2253
		 */
2254
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2255
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2256
		}
2257
	}
2258
2259
	/**
2260
	 * Allows plugins to submit security reports.
2261
	 *
2262
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2263
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2264
	 * @param array  $args         See definitions above
2265
	 */
2266
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2267
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2268
	}
2269
2270
	/* Jetpack Options API */
2271
2272
	public static function get_option_names( $type = 'compact' ) {
2273
		return Jetpack_Options::get_option_names( $type );
2274
	}
2275
2276
	/**
2277
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2278
	 *
2279
	 * @param string $name    Option name
2280
	 * @param mixed  $default (optional)
2281
	 */
2282
	public static function get_option( $name, $default = false ) {
2283
		return Jetpack_Options::get_option( $name, $default );
2284
	}
2285
2286
	/**
2287
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2288
	 *
2289
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2290
	 * @param string $name  Option name
2291
	 * @param mixed  $value Option value
2292
	 */
2293
	public static function update_option( $name, $value ) {
2294
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2295
		return Jetpack_Options::update_option( $name, $value );
2296
	}
2297
2298
	/**
2299
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2300
	 *
2301
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2302
	 * @param array $array array( option name => option value, ... )
2303
	 */
2304
	public static function update_options( $array ) {
2305
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2306
		return Jetpack_Options::update_options( $array );
2307
	}
2308
2309
	/**
2310
	 * Deletes the given option.  May be passed multiple option names as an array.
2311
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2312
	 *
2313
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2314
	 * @param string|array $names
2315
	 */
2316
	public static function delete_option( $names ) {
2317
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2318
		return Jetpack_Options::delete_option( $names );
2319
	}
2320
2321
	/**
2322
	 * Enters a user token into the user_tokens option
2323
	 *
2324
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2325
	 *
2326
	 * @param int    $user_id The user id.
2327
	 * @param string $token The user token.
2328
	 * @param bool   $is_master_user Whether the user is the master user.
2329
	 * @return bool
2330
	 */
2331
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2332
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2333
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2334
	}
2335
2336
	/**
2337
	 * Returns an array of all PHP files in the specified absolute path.
2338
	 * Equivalent to glob( "$absolute_path/*.php" ).
2339
	 *
2340
	 * @param string $absolute_path The absolute path of the directory to search.
2341
	 * @return array Array of absolute paths to the PHP files.
2342
	 */
2343
	public static function glob_php( $absolute_path ) {
2344
		if ( function_exists( 'glob' ) ) {
2345
			return glob( "$absolute_path/*.php" );
2346
		}
2347
2348
		$absolute_path = untrailingslashit( $absolute_path );
2349
		$files         = array();
2350
		if ( ! $dir = @opendir( $absolute_path ) ) {
2351
			return $files;
2352
		}
2353
2354
		while ( false !== $file = readdir( $dir ) ) {
2355
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2356
				continue;
2357
			}
2358
2359
			$file = "$absolute_path/$file";
2360
2361
			if ( ! is_file( $file ) ) {
2362
				continue;
2363
			}
2364
2365
			$files[] = $file;
2366
		}
2367
2368
		closedir( $dir );
2369
2370
		return $files;
2371
	}
2372
2373
	public static function activate_new_modules( $redirect = false ) {
2374
		if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2375
			return;
2376
		}
2377
2378
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2379 View Code Duplication
		if ( ! $jetpack_old_version ) {
2380
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2381
			/** This action is documented in class.jetpack.php */
2382
			do_action( 'updating_jetpack_version', $version, false );
2383
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2384
		}
2385
2386
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2387
2388
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2389
			return;
2390
		}
2391
2392
		$active_modules     = self::get_active_modules();
2393
		$reactivate_modules = array();
2394
		foreach ( $active_modules as $active_module ) {
2395
			$module = self::get_module( $active_module );
2396
			if ( ! isset( $module['changed'] ) ) {
2397
				continue;
2398
			}
2399
2400
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2401
				continue;
2402
			}
2403
2404
			$reactivate_modules[] = $active_module;
2405
			self::deactivate_module( $active_module );
2406
		}
2407
2408
		$new_version = JETPACK__VERSION . ':' . time();
2409
		/** This action is documented in class.jetpack.php */
2410
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2411
		Jetpack_Options::update_options(
2412
			array(
2413
				'version'     => $new_version,
2414
				'old_version' => $jetpack_old_version,
2415
			)
2416
		);
2417
2418
		self::state( 'message', 'modules_activated' );
2419
2420
		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...
2421
2422
		if ( $redirect ) {
2423
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2424
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2425
				$page = $_GET['page'];
2426
			}
2427
2428
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2429
			exit;
2430
		}
2431
	}
2432
2433
	/**
2434
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2435
	 * Make sure to tuck away module "library" files in a sub-directory.
2436
	 *
2437
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2438
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2439
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2440
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2441
	 *
2442
	 * @return array $modules Array of module slugs
2443
	 */
2444
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2445
		static $modules = null;
2446
2447
		if ( ! isset( $modules ) ) {
2448
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2449
			// Use the cache if we're on the front-end and it's available...
2450
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2451
				$modules = $available_modules_option[ JETPACK__VERSION ];
2452
			} else {
2453
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2454
2455
				$modules = array();
2456
2457
				foreach ( $files as $file ) {
2458
					if ( ! $headers = self::get_module( $file ) ) {
2459
						continue;
2460
					}
2461
2462
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2463
				}
2464
2465
				Jetpack_Options::update_option(
2466
					'available_modules',
2467
					array(
2468
						JETPACK__VERSION => $modules,
2469
					)
2470
				);
2471
			}
2472
		}
2473
2474
		/**
2475
		 * Filters the array of modules available to be activated.
2476
		 *
2477
		 * @since 2.4.0
2478
		 *
2479
		 * @param array $modules Array of available modules.
2480
		 * @param string $min_version Minimum version number required to use modules.
2481
		 * @param string $max_version Maximum version number required to use modules.
2482
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2483
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2484
		 */
2485
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version, $requires_connection, $requires_user_connection );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

Loading history...
2486
2487
		if ( ! $min_version && ! $max_version && is_null( $requires_connection ) && is_null( $requires_user_connection ) ) {
2488
			return array_keys( $mods );
2489
		}
2490
2491
		$r = array();
2492
		foreach ( $mods as $slug => $introduced ) {
2493
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2494
				continue;
2495
			}
2496
2497
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2498
				continue;
2499
			}
2500
2501
			$mod_details = self::get_module( $slug );
2502
2503
			if ( null !== $requires_connection && (bool) $requires_connection !== $mod_details['requires_connection'] ) {
2504
				continue;
2505
			}
2506
2507
			if ( null !== $requires_user_connection && (bool) $requires_user_connection !== $mod_details['requires_user_connection'] ) {
2508
				continue;
2509
			}
2510
2511
			$r[] = $slug;
2512
		}
2513
2514
		return $r;
2515
	}
2516
2517
	/**
2518
	 * Get default modules loaded on activation.
2519
	 *
2520
	 * @param bool|string $min_version Onlu return modules introduced in this version or later. Default is false, do not filter.
2521
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2522
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2523
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2524
	 *
2525
	 * @return array $modules Array of module slugs
2526
	 */
2527
	public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2528
		$return = array();
2529
2530
		foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2531
			$module_data = self::get_module( $module );
2532
2533
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2534
				case 'yes':
2535
					$return[] = $module;
2536
					break;
2537
				case 'public':
2538
					if ( Jetpack_Options::get_option( 'public' ) ) {
2539
						$return[] = $module;
2540
					}
2541
					break;
2542
				case 'no':
2543
				default:
2544
					break;
2545
			}
2546
		}
2547
		/**
2548
		 * Filters the array of default modules.
2549
		 *
2550
		 * @since 2.5.0
2551
		 *
2552
		 * @param array $return Array of default modules.
2553
		 * @param string $min_version Minimum version number required to use modules.
2554
		 * @param string $max_version Maximum version number required to use modules.
2555
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2556
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2557
		 */
2558
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version, $requires_connection, $requires_user_connection );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

Loading history...
2559
	}
2560
2561
	/**
2562
	 * Checks activated modules during auto-activation to determine
2563
	 * if any of those modules are being deprecated.  If so, close
2564
	 * them out, and add any replacement modules.
2565
	 *
2566
	 * Runs at priority 99 by default.
2567
	 *
2568
	 * This is run late, so that it can still activate a module if
2569
	 * the new module is a replacement for another that the user
2570
	 * currently has active, even if something at the normal priority
2571
	 * would kibosh everything.
2572
	 *
2573
	 * @since 2.6
2574
	 * @uses jetpack_get_default_modules filter
2575
	 * @param array $modules
2576
	 * @return array
2577
	 */
2578
	function handle_deprecated_modules( $modules ) {
2579
		$deprecated_modules = array(
2580
			'debug'            => null,  // Closed out and moved to the debugger library.
2581
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2582
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2583
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2584
		);
2585
2586
		// Don't activate SSO if they never completed activating WPCC.
2587
		if ( self::is_module_active( 'wpcc' ) ) {
2588
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2589
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2590
				$deprecated_modules['wpcc'] = null;
2591
			}
2592
		}
2593
2594
		foreach ( $deprecated_modules as $module => $replacement ) {
2595
			if ( self::is_module_active( $module ) ) {
2596
				self::deactivate_module( $module );
2597
				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...
2598
					$modules[] = $replacement;
2599
				}
2600
			}
2601
		}
2602
2603
		return array_unique( $modules );
2604
	}
2605
2606
	/**
2607
	 * Checks activated plugins during auto-activation to determine
2608
	 * if any of those plugins are in the list with a corresponding module
2609
	 * that is not compatible with the plugin. The module will not be allowed
2610
	 * to auto-activate.
2611
	 *
2612
	 * @since 2.6
2613
	 * @uses jetpack_get_default_modules filter
2614
	 * @param array $modules
2615
	 * @return array
2616
	 */
2617
	function filter_default_modules( $modules ) {
2618
2619
		$active_plugins = self::get_active_plugins();
2620
2621
		if ( ! empty( $active_plugins ) ) {
2622
2623
			// For each module we'd like to auto-activate...
2624
			foreach ( $modules as $key => $module ) {
2625
				// If there are potential conflicts for it...
2626
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2627
					// For each potential conflict...
2628
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2629
						// If that conflicting plugin is active...
2630
						if ( in_array( $plugin, $active_plugins ) ) {
2631
							// Remove that item from being auto-activated.
2632
							unset( $modules[ $key ] );
2633
						}
2634
					}
2635
				}
2636
			}
2637
		}
2638
2639
		return $modules;
2640
	}
2641
2642
	/**
2643
	 * Extract a module's slug from its full path.
2644
	 */
2645
	public static function get_module_slug( $file ) {
2646
		return str_replace( '.php', '', basename( $file ) );
2647
	}
2648
2649
	/**
2650
	 * Generate a module's path from its slug.
2651
	 */
2652
	public static function get_module_path( $slug ) {
2653
		/**
2654
		 * Filters the path of a modules.
2655
		 *
2656
		 * @since 7.4.0
2657
		 *
2658
		 * @param array $return The absolute path to a module's root php file
2659
		 * @param string $slug The module slug
2660
		 */
2661
		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...
2662
	}
2663
2664
	/**
2665
	 * Load module data from module file. Headers differ from WordPress
2666
	 * plugin headers to avoid them being identified as standalone
2667
	 * plugins on the WordPress plugins page.
2668
	 */
2669
	public static function get_module( $module ) {
2670
		$headers = array(
2671
			'name'                      => 'Module Name',
2672
			'description'               => 'Module Description',
2673
			'sort'                      => 'Sort Order',
2674
			'recommendation_order'      => 'Recommendation Order',
2675
			'introduced'                => 'First Introduced',
2676
			'changed'                   => 'Major Changes In',
2677
			'deactivate'                => 'Deactivate',
2678
			'free'                      => 'Free',
2679
			'requires_connection'       => 'Requires Connection',
2680
			'requires_user_connection'  => 'Requires User Connection',
2681
			'auto_activate'             => 'Auto Activate',
2682
			'module_tags'               => 'Module Tags',
2683
			'feature'                   => 'Feature',
2684
			'additional_search_queries' => 'Additional Search Queries',
2685
			'plan_classes'              => 'Plans',
2686
		);
2687
2688
		static $modules_details;
2689
		$file = self::get_module_path( self::get_module_slug( $module ) );
2690
2691
		if ( isset( $modules_details[ $module ] ) ) {
2692
			$mod = $modules_details[ $module ];
2693
		} else {
2694
2695
			$mod = self::get_file_data( $file, $headers );
2696
			if ( empty( $mod['name'] ) ) {
2697
				return false;
2698
			}
2699
2700
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2701
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2702
			$mod['deactivate']               = empty( $mod['deactivate'] );
2703
			$mod['free']                     = empty( $mod['free'] );
2704
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2705
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2706
2707
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2708
				$mod['auto_activate'] = 'No';
2709
			} else {
2710
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2711
			}
2712
2713
			if ( $mod['module_tags'] ) {
2714
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2715
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2716
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2717
			} else {
2718
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2719
			}
2720
2721 View Code Duplication
			if ( $mod['plan_classes'] ) {
2722
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2723
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2724
			} else {
2725
				$mod['plan_classes'] = array( 'free' );
2726
			}
2727
2728 View Code Duplication
			if ( $mod['feature'] ) {
2729
				$mod['feature'] = explode( ',', $mod['feature'] );
2730
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2731
			} else {
2732
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2733
			}
2734
2735
			$modules_details[ $module ] = $mod;
2736
2737
		}
2738
2739
		/**
2740
		 * Filters the feature array on a module.
2741
		 *
2742
		 * This filter allows you to control where each module is filtered: Recommended,
2743
		 * and the default "Other" listing.
2744
		 *
2745
		 * @since 3.5.0
2746
		 *
2747
		 * @param array   $mod['feature'] The areas to feature this module:
2748
		 *     'Recommended' shows on the main Jetpack admin screen.
2749
		 *     'Other' should be the default if no other value is in the array.
2750
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2751
		 * @param array   $mod All the currently assembled module data.
2752
		 */
2753
		$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...
2754
2755
		/**
2756
		 * Filter the returned data about a module.
2757
		 *
2758
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2759
		 * so please be careful.
2760
		 *
2761
		 * @since 3.6.0
2762
		 *
2763
		 * @param array   $mod    The details of the requested module.
2764
		 * @param string  $module The slug of the module, e.g. sharedaddy
2765
		 * @param string  $file   The path to the module source file.
2766
		 */
2767
		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...
2768
	}
2769
2770
	/**
2771
	 * Like core's get_file_data implementation, but caches the result.
2772
	 */
2773
	public static function get_file_data( $file, $headers ) {
2774
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2775
		$file_name = basename( $file );
2776
2777
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2778
2779
		$file_data_option = get_transient( $cache_key );
2780
2781
		if ( ! is_array( $file_data_option ) ) {
2782
			delete_transient( $cache_key );
2783
			$file_data_option = false;
2784
		}
2785
2786
		if ( false === $file_data_option ) {
2787
			$file_data_option = array();
2788
		}
2789
2790
		$key           = md5( $file_name . serialize( $headers ) );
2791
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2792
2793
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2794
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2795
			return $file_data_option[ $key ];
2796
		}
2797
2798
		$data = get_file_data( $file, $headers );
2799
2800
		$file_data_option[ $key ] = $data;
2801
2802
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2803
2804
		return $data;
2805
	}
2806
2807
	/**
2808
	 * Return translated module tag.
2809
	 *
2810
	 * @param string $tag Tag as it appears in each module heading.
2811
	 *
2812
	 * @return mixed
2813
	 */
2814
	public static function translate_module_tag( $tag ) {
2815
		return jetpack_get_module_i18n_tag( $tag );
2816
	}
2817
2818
	/**
2819
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2820
	 *
2821
	 * @since 3.9.2
2822
	 *
2823
	 * @param array $modules
2824
	 *
2825
	 * @return string|void
2826
	 */
2827
	public static function get_translated_modules( $modules ) {
2828
		foreach ( $modules as $index => $module ) {
2829
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2830
			if ( isset( $module['name'] ) ) {
2831
				$modules[ $index ]['name'] = $i18n_module['name'];
2832
			}
2833
			if ( isset( $module['description'] ) ) {
2834
				$modules[ $index ]['description']       = $i18n_module['description'];
2835
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2836
			}
2837
		}
2838
		return $modules;
2839
	}
2840
2841
	/**
2842
	 * Get a list of activated modules as an array of module slugs.
2843
	 */
2844
	public static function get_active_modules() {
2845
		$active = Jetpack_Options::get_option( 'active_modules' );
2846
2847
		if ( ! is_array( $active ) ) {
2848
			$active = array();
2849
		}
2850
2851
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2852
			$active[] = 'vaultpress';
2853
		} else {
2854
			$active = array_diff( $active, array( 'vaultpress' ) );
2855
		}
2856
2857
		// If protect is active on the main site of a multisite, it should be active on all sites.
2858
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2859
			$active[] = 'protect';
2860
		}
2861
2862
		/**
2863
		 * Allow filtering of the active modules.
2864
		 *
2865
		 * Gives theme and plugin developers the power to alter the modules that
2866
		 * are activated on the fly.
2867
		 *
2868
		 * @since 5.8.0
2869
		 *
2870
		 * @param array $active Array of active module slugs.
2871
		 */
2872
		$active = apply_filters( 'jetpack_active_modules', $active );
2873
2874
		return array_unique( $active );
2875
	}
2876
2877
	/**
2878
	 * Check whether or not a Jetpack module is active.
2879
	 *
2880
	 * @param string $module The slug of a Jetpack module.
2881
	 * @return bool
2882
	 *
2883
	 * @static
2884
	 */
2885
	public static function is_module_active( $module ) {
2886
		return in_array( $module, self::get_active_modules() );
2887
	}
2888
2889
	public static function is_module( $module ) {
2890
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2891
	}
2892
2893
	/**
2894
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2895
	 *
2896
	 * @param bool $catch True to start catching, False to stop.
2897
	 *
2898
	 * @static
2899
	 */
2900
	public static function catch_errors( $catch ) {
2901
		static $display_errors, $error_reporting;
2902
2903
		if ( $catch ) {
2904
			$display_errors  = @ini_set( 'display_errors', 1 );
2905
			$error_reporting = @error_reporting( E_ALL );
2906
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2907
		} else {
2908
			@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...
2909
			@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...
2910
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2911
		}
2912
	}
2913
2914
	/**
2915
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2916
	 */
2917
	public static function catch_errors_on_shutdown() {
2918
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2919
	}
2920
2921
	/**
2922
	 * Rewrite any string to make paths easier to read.
2923
	 *
2924
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2925
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2926
	 *
2927
	 * @param $string
2928
	 * @return mixed
2929
	 */
2930
	public static function alias_directories( $string ) {
2931
		// ABSPATH has a trailing slash.
2932
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2933
		// WP_CONTENT_DIR does not have a trailing slash.
2934
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2935
2936
		return $string;
2937
	}
2938
2939
	public static function activate_default_modules(
2940
		$min_version = false,
2941
		$max_version = false,
2942
		$other_modules = array(),
2943
		$redirect = null,
2944
		$send_state_messages = null,
2945
		$requires_connection = null,
2946
		$requires_user_connection = null
2947
	) {
2948
		$jetpack = self::init();
2949
2950
		if ( is_null( $redirect ) ) {
2951
			if (
2952
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2953
			||
2954
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2955
			||
2956
				( defined( 'WP_CLI' ) && WP_CLI )
2957
			||
2958
				( defined( 'DOING_CRON' ) && DOING_CRON )
2959
			||
2960
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2961
			) {
2962
				$redirect = false;
2963
			} elseif ( is_admin() ) {
2964
				$redirect = true;
2965
			} else {
2966
				$redirect = false;
2967
			}
2968
		}
2969
2970
		if ( is_null( $send_state_messages ) ) {
2971
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2972
		}
2973
2974
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2975
		$modules = array_merge( $other_modules, $modules );
2976
2977
		// Look for standalone plugins and disable if active.
2978
2979
		$to_deactivate = array();
2980
		foreach ( $modules as $module ) {
2981
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2982
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2983
			}
2984
		}
2985
2986
		$deactivated = array();
2987
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2988
			list( $probable_file, $probable_title ) = $deactivate_me;
2989
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2990
				$deactivated[] = $module;
2991
			}
2992
		}
2993
2994
		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...
2995
			if ( $send_state_messages ) {
2996
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2997
			}
2998
2999
			if ( $redirect ) {
3000
				$url = add_query_arg(
3001
					array(
3002
						'action'   => 'activate_default_modules',
3003
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
3004
					),
3005
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
3006
				);
3007
				wp_safe_redirect( $url );
3008
				exit;
3009
			}
3010
		}
3011
3012
		/**
3013
		 * Fires before default modules are activated.
3014
		 *
3015
		 * @since 1.9.0
3016
		 *
3017
		 * @param string    $min_version Minimum version number required to use modules.
3018
		 * @param string    $max_version Maximum version number required to use modules.
3019
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3020
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3021
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3022
		 */
3023
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3024
3025
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3026
		if ( $send_state_messages ) {
3027
			self::restate();
3028
			self::catch_errors( true );
3029
		}
3030
3031
		$active = self::get_active_modules();
3032
3033
		foreach ( $modules as $module ) {
3034
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3035
				$active[] = $module;
3036
				self::update_active_modules( $active );
3037
				continue;
3038
			}
3039
3040
			if ( $send_state_messages && in_array( $module, $active ) ) {
3041
				$module_info = self::get_module( $module );
3042 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3043
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3044
					if ( $active_state = self::state( $state ) ) {
3045
						$active_state = explode( ',', $active_state );
3046
					} else {
3047
						$active_state = array();
3048
					}
3049
					$active_state[] = $module;
3050
					self::state( $state, implode( ',', $active_state ) );
3051
				}
3052
				continue;
3053
			}
3054
3055
			$file = self::get_module_path( $module );
3056
			if ( ! file_exists( $file ) ) {
3057
				continue;
3058
			}
3059
3060
			// we'll override this later if the plugin can be included without fatal error
3061
			if ( $redirect ) {
3062
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3063
			}
3064
3065
			if ( $send_state_messages ) {
3066
				self::state( 'error', 'module_activation_failed' );
3067
				self::state( 'module', $module );
3068
			}
3069
3070
			ob_start();
3071
			require_once $file;
3072
3073
			$active[] = $module;
3074
3075 View Code Duplication
			if ( $send_state_messages ) {
3076
3077
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3078
				if ( $active_state = self::state( $state ) ) {
3079
					$active_state = explode( ',', $active_state );
3080
				} else {
3081
					$active_state = array();
3082
				}
3083
				$active_state[] = $module;
3084
				self::state( $state, implode( ',', $active_state ) );
3085
			}
3086
3087
			self::update_active_modules( $active );
3088
3089
			ob_end_clean();
3090
		}
3091
3092
		if ( $send_state_messages ) {
3093
			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...
3094
			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...
3095
		}
3096
3097
		self::catch_errors( false );
3098
		/**
3099
		 * Fires when default modules are activated.
3100
		 *
3101
		 * @since 1.9.0
3102
		 *
3103
		 * @param string    $min_version Minimum version number required to use modules.
3104
		 * @param string    $max_version Maximum version number required to use modules.
3105
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3106
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3107
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3108
		 */
3109
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3110
	}
3111
3112
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3113
		/**
3114
		 * Fires before a module is activated.
3115
		 *
3116
		 * @since 2.6.0
3117
		 *
3118
		 * @param string $module Module slug.
3119
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3120
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3121
		 */
3122
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3123
3124
		$jetpack = self::init();
3125
3126
		if ( ! strlen( $module ) ) {
3127
			return false;
3128
		}
3129
3130
		if ( ! self::is_module( $module ) ) {
3131
			return false;
3132
		}
3133
3134
		// If it's already active, then don't do it again
3135
		$active = self::get_active_modules();
3136
		foreach ( $active as $act ) {
3137
			if ( $act == $module ) {
3138
				return true;
3139
			}
3140
		}
3141
3142
		$module_data = self::get_module( $module );
3143
3144
		$is_offline_mode = ( new Status() )->is_offline_mode();
3145
		if ( ! self::is_connection_ready() ) {
3146
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3147
				return false;
3148
			}
3149
3150
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3151
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3152
				return false;
3153
			}
3154
		}
3155
3156
		// Check and see if the old plugin is active
3157
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3158
			// Deactivate the old plugin
3159
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3160
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3161
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3162
				self::state( 'deactivated_plugins', $module );
3163
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3164
				exit;
3165
			}
3166
		}
3167
3168
		// Protect won't work with mis-configured IPs
3169
		if ( 'protect' === $module ) {
3170
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3171
			if ( ! jetpack_protect_get_ip() ) {
3172
				self::state( 'message', 'protect_misconfigured_ip' );
3173
				return false;
3174
			}
3175
		}
3176
3177
		if ( ! Jetpack_Plan::supports( $module ) ) {
3178
			return false;
3179
		}
3180
3181
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3182
		self::state( 'module', $module );
3183
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3184
3185
		self::catch_errors( true );
3186
		ob_start();
3187
		require self::get_module_path( $module );
3188
		/** This action is documented in class.jetpack.php */
3189
		do_action( 'jetpack_activate_module', $module );
3190
		$active[] = $module;
3191
		self::update_active_modules( $active );
3192
3193
		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...
3194
		ob_end_clean();
3195
		self::catch_errors( false );
3196
3197
		if ( $redirect ) {
3198
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3199
		}
3200
		if ( $exit ) {
3201
			exit;
3202
		}
3203
		return true;
3204
	}
3205
3206
	function activate_module_actions( $module ) {
3207
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3208
	}
3209
3210
	public static function deactivate_module( $module ) {
3211
		/**
3212
		 * Fires when a module is deactivated.
3213
		 *
3214
		 * @since 1.9.0
3215
		 *
3216
		 * @param string $module Module slug.
3217
		 */
3218
		do_action( 'jetpack_pre_deactivate_module', $module );
3219
3220
		$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...
3221
3222
		$active = self::get_active_modules();
3223
		$new    = array_filter( array_diff( $active, (array) $module ) );
3224
3225
		return self::update_active_modules( $new );
3226
	}
3227
3228
	public static function enable_module_configurable( $module ) {
3229
		$module = self::get_module_slug( $module );
3230
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3231
	}
3232
3233
	/**
3234
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3235
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3236
	 *
3237
	 * @param string $module Module slug
3238
	 * @return string $url module configuration URL
3239
	 */
3240
	public static function module_configuration_url( $module ) {
3241
		$module      = self::get_module_slug( $module );
3242
		$default_url = self::admin_url() . "#/settings?term=$module";
3243
		/**
3244
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3245
		 *
3246
		 * @since 6.9.0
3247
		 *
3248
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3249
		 */
3250
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3251
3252
		return $url;
3253
	}
3254
3255
	/* Installation */
3256
	public static function bail_on_activation( $message, $deactivate = true ) {
3257
		?>
3258
<!doctype html>
3259
<html>
3260
<head>
3261
<meta charset="<?php bloginfo( 'charset' ); ?>">
3262
<style>
3263
* {
3264
	text-align: center;
3265
	margin: 0;
3266
	padding: 0;
3267
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3268
}
3269
p {
3270
	margin-top: 1em;
3271
	font-size: 18px;
3272
}
3273
</style>
3274
<body>
3275
<p><?php echo esc_html( $message ); ?></p>
3276
</body>
3277
</html>
3278
		<?php
3279
		if ( $deactivate ) {
3280
			$plugins = get_option( 'active_plugins' );
3281
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3282
			$update  = false;
3283
			foreach ( $plugins as $i => $plugin ) {
3284
				if ( $plugin === $jetpack ) {
3285
					$plugins[ $i ] = false;
3286
					$update        = true;
3287
				}
3288
			}
3289
3290
			if ( $update ) {
3291
				update_option( 'active_plugins', array_filter( $plugins ) );
3292
			}
3293
		}
3294
		exit;
3295
	}
3296
3297
	/**
3298
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3299
	 *
3300
	 * @static
3301
	 */
3302
	public static function plugin_activation( $network_wide ) {
3303
		Jetpack_Options::update_option( 'activated', 1 );
3304
3305
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3306
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3307
		}
3308
3309
		if ( $network_wide ) {
3310
			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...
3311
		}
3312
3313
		// For firing one-off events (notices) immediately after activation
3314
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3315
3316
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3317
3318
		Health::on_jetpack_activated();
3319
3320
		self::plugin_initialize();
3321
	}
3322
3323
	public static function get_activation_source( $referer_url ) {
3324
3325
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3326
			return array( 'wp-cli', null );
3327
		}
3328
3329
		$referer = wp_parse_url( $referer_url );
3330
3331
		$source_type  = 'unknown';
3332
		$source_query = null;
3333
3334
		if ( ! is_array( $referer ) ) {
3335
			return array( $source_type, $source_query );
3336
		}
3337
3338
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3339
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3340
3341
		if ( isset( $referer['query'] ) ) {
3342
			parse_str( $referer['query'], $query_parts );
3343
		} else {
3344
			$query_parts = array();
3345
		}
3346
3347
		if ( $plugins_path === $referer['path'] ) {
3348
			$source_type = 'list';
3349
		} elseif ( $plugins_install_path === $referer['path'] ) {
3350
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3351
			switch ( $tab ) {
3352
				case 'popular':
3353
					$source_type = 'popular';
3354
					break;
3355
				case 'recommended':
3356
					$source_type = 'recommended';
3357
					break;
3358
				case 'favorites':
3359
					$source_type = 'favorites';
3360
					break;
3361
				case 'search':
3362
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3363
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3364
					break;
3365
				default:
3366
					$source_type = 'featured';
3367
			}
3368
		}
3369
3370
		return array( $source_type, $source_query );
3371
	}
3372
3373
	/**
3374
	 * Runs before bumping version numbers up to a new version
3375
	 *
3376
	 * @param string $version    Version:timestamp.
3377
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3378
	 */
3379
	public static function do_version_bump( $version, $old_version ) {
3380
		if ( $old_version ) { // For existing Jetpack installations.
3381
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3382
3383
			// If a front end page is visited after the update, the 'wp' action will fire.
3384
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3385
3386
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3387
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3388
		}
3389
	}
3390
3391
	/**
3392
	 * Sets the display_update_modal state.
3393
	 */
3394
	public static function set_update_modal_display() {
3395
		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...
3396
3397
	}
3398
3399
	/**
3400
	 * Enqueues the block library styles.
3401
	 *
3402
	 * @param string $hook The current admin page.
3403
	 */
3404
	public static function enqueue_block_style( $hook ) {
3405
		if ( 'toplevel_page_jetpack' === $hook ) {
3406
			wp_enqueue_style( 'wp-block-library' );
3407
		}
3408
	}
3409
3410
	/**
3411
	 * Sets the internal version number and activation state.
3412
	 *
3413
	 * @static
3414
	 */
3415
	public static function plugin_initialize() {
3416
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3417
			Jetpack_Options::update_option( 'activated', 2 );
3418
		}
3419
3420 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3421
			$version = $old_version = JETPACK__VERSION . ':' . time();
3422
			/** This action is documented in class.jetpack.php */
3423
			do_action( 'updating_jetpack_version', $version, false );
3424
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3425
		}
3426
3427
		self::load_modules();
3428
3429
		Jetpack_Options::delete_option( 'do_activate' );
3430
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3431
	}
3432
3433
	/**
3434
	 * Removes all connection options
3435
	 *
3436
	 * @static
3437
	 */
3438
	public static function plugin_deactivation() {
3439
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3440
		$tracking = new Tracking();
3441
		$tracking->record_user_event( 'deactivate_plugin', array() );
3442
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3443
			Jetpack_Network::init()->deactivate();
3444
		} else {
3445
			self::disconnect( false );
3446
			// Jetpack_Heartbeat::init()->deactivate();
3447
		}
3448
	}
3449
3450
	/**
3451
	 * Set activated option to 4 on jetpack_idc_disconnect action.
3452
	 */
3453
	public static function on_idc_disconnect() {
3454
		\Jetpack_Options::update_option( 'activated', 4 );
3455
	}
3456
3457
	/**
3458
	 * Disconnects from the Jetpack servers.
3459
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3460
	 *
3461
	 * @static
3462
	 */
3463
	public static function disconnect( $update_activated_state = true ) {
3464
3465
		$connection = self::connection();
3466
3467
		// If the site is in an IDC because sync is not allowed,
3468
		// let's make sure to not disconnect the production site.
3469
		$connection->disconnect_site( ! Identity_Crisis::validate_sync_error_idc_option() );
3470
3471
		Identity_Crisis::clear_all_idc_options();
3472
3473
		if ( $update_activated_state ) {
3474
			Jetpack_Options::update_option( 'activated', 4 );
3475
		}
3476
3477
		// Delete all the sync related data. Since it could be taking up space.
3478
		Sender::get_instance()->uninstall();
3479
	}
3480
3481
	/**
3482
	 * Disconnects the user
3483
	 *
3484
	 * @param int $user_id The user ID to disconnect.
3485
	 */
3486
	public function disconnect_user( $user_id ) {
3487
		$this->connection_manager->disconnect_user( $user_id );
3488
	}
3489
3490
	/**
3491
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3492
	 *
3493
	 * @deprecated since Jetpack 9.7.0
3494
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
3495
	 *
3496
	 * @return bool|WP_Error
3497
	 */
3498
	public static function try_registration() {
3499
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
3500
		return static::connection()->try_registration();
3501
	}
3502
3503
	/**
3504
	 * Checking the domain names in beta versions.
3505
	 * If this is a development version, before attempting to connect, let's make sure that the domains are viable.
3506
	 *
3507
	 * @param null|\WP_Error $error The domain validation error, or `null` if everything's fine.
3508
	 *
3509
	 * @return null|\WP_Error The domain validation error, or `null` if everything's fine.
3510
	 */
3511
	public static function registration_check_domains( $error ) {
3512
		if ( static::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3513
			$domains_to_check = array_unique(
3514
				array(
3515
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3516
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3517
				)
3518
			);
3519
			foreach ( $domains_to_check as $domain ) {
3520
				$result = static::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3519 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...
3521
				if ( is_wp_error( $result ) ) {
3522
					return $result;
3523
				}
3524
			}
3525
		}
3526
3527
		return $error;
3528
	}
3529
3530
	/**
3531
	 * Tracking an internal event log. Try not to put too much chaff in here.
3532
	 *
3533
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3534
	 */
3535
	public static function log( $code, $data = null ) {
3536
		// only grab the latest 200 entries
3537
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3538
3539
		// Append our event to the log
3540
		$log_entry = array(
3541
			'time'    => time(),
3542
			'user_id' => get_current_user_id(),
3543
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3544
			'code'    => $code,
3545
		);
3546
		// Don't bother storing it unless we've got some.
3547
		if ( ! is_null( $data ) ) {
3548
			$log_entry['data'] = $data;
3549
		}
3550
		$log[] = $log_entry;
3551
3552
		// Try add_option first, to make sure it's not autoloaded.
3553
		// @todo: Add an add_option method to Jetpack_Options
3554
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3555
			Jetpack_Options::update_option( 'log', $log );
3556
		}
3557
3558
		/**
3559
		 * Fires when Jetpack logs an internal event.
3560
		 *
3561
		 * @since 3.0.0
3562
		 *
3563
		 * @param array $log_entry {
3564
		 *  Array of details about the log entry.
3565
		 *
3566
		 *  @param string time Time of the event.
3567
		 *  @param int user_id ID of the user who trigerred the event.
3568
		 *  @param int blog_id Jetpack Blog ID.
3569
		 *  @param string code Unique name for the event.
3570
		 *  @param string data Data about the event.
3571
		 * }
3572
		 */
3573
		do_action( 'jetpack_log_entry', $log_entry );
3574
	}
3575
3576
	/**
3577
	 * Get the internal event log.
3578
	 *
3579
	 * @param $event (string) - only return the specific log events
3580
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3581
	 *
3582
	 * @return array of log events || WP_Error for invalid params
3583
	 */
3584
	public static function get_log( $event = false, $num = false ) {
3585
		if ( $event && ! is_string( $event ) ) {
3586
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

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

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

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

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

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

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

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

Loading history...
3591
		}
3592
3593
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3594
3595
		// If nothing set - act as it did before, otherwise let's start customizing the output
3596
		if ( ! $num && ! $event ) {
3597
			return $entire_log;
3598
		} else {
3599
			$entire_log = array_reverse( $entire_log );
3600
		}
3601
3602
		$custom_log_output = array();
3603
3604
		if ( $event ) {
3605
			foreach ( $entire_log as $log_event ) {
3606
				if ( $event == $log_event['code'] ) {
3607
					$custom_log_output[] = $log_event;
3608
				}
3609
			}
3610
		} else {
3611
			$custom_log_output = $entire_log;
3612
		}
3613
3614
		if ( $num ) {
3615
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3616
		}
3617
3618
		return $custom_log_output;
3619
	}
3620
3621
	/**
3622
	 * Log modification of important settings.
3623
	 */
3624
	public static function log_settings_change( $option, $old_value, $value ) {
3625
		switch ( $option ) {
3626
			case 'jetpack_sync_non_public_post_stati':
3627
				self::log( $option, $value );
3628
				break;
3629
		}
3630
	}
3631
3632
	/**
3633
	 * Return stat data for WPCOM sync
3634
	 */
3635
	public static function get_stat_data( $encode = true, $extended = true ) {
3636
		$data = Jetpack_Heartbeat::generate_stats_array();
3637
3638
		if ( $extended ) {
3639
			$additional_data = self::get_additional_stat_data();
3640
			$data            = array_merge( $data, $additional_data );
3641
		}
3642
3643
		if ( $encode ) {
3644
			return json_encode( $data );
3645
		}
3646
3647
		return $data;
3648
	}
3649
3650
	/**
3651
	 * Get additional stat data to sync to WPCOM
3652
	 */
3653
	public static function get_additional_stat_data( $prefix = '' ) {
3654
		$return[ "{$prefix}themes" ]        = self::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
3655
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3656
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3657
		$return[ "{$prefix}site-count" ]    = 0;
3658
3659
		if ( function_exists( 'get_blog_count' ) ) {
3660
			$return[ "{$prefix}site-count" ] = get_blog_count();
3661
		}
3662
		return $return;
3663
	}
3664
3665
	private static function get_site_user_count() {
3666
		global $wpdb;
3667
3668
		if ( function_exists( 'wp_is_large_network' ) ) {
3669
			if ( wp_is_large_network( 'users' ) ) {
3670
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3671
			}
3672
		}
3673
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3674
			// It wasn't there, so regenerate the data and save the transient
3675
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3676
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3677
		}
3678
		return $user_count;
3679
	}
3680
3681
	/* Admin Pages */
3682
3683
	function admin_init() {
3684
		// If the plugin is not connected, display a connect message.
3685
		if (
3686
			// the plugin was auto-activated and needs its candy
3687
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3688
		||
3689
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3690
			! Jetpack_Options::get_option( 'activated' )
3691
		) {
3692
			self::plugin_initialize();
3693
		}
3694
3695
		$is_offline_mode              = ( new Status() )->is_offline_mode();
3696
		$fallback_no_verify_ssl_certs = Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
3697
		/** Already documented in automattic/jetpack-connection::src/class-client.php */
3698
		$client_verify_ssl_certs = apply_filters( 'jetpack_client_verify_ssl_certs', false );
3699
3700
		if ( ! $is_offline_mode ) {
3701
			Jetpack_Connection_Banner::init();
3702
		}
3703
3704
		if ( ( self::is_connection_ready() || $is_offline_mode ) && false === $fallback_no_verify_ssl_certs && ! $client_verify_ssl_certs ) {
3705
			// Upgrade: 1.1 -> 1.1.1
3706
			// Check and see if host can verify the Jetpack servers' SSL certificate
3707
			$args = array();
3708
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3709
		}
3710
3711
		Jetpack_Recommendations_Banner::init();
3712
3713
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3714
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3715
		}
3716
3717
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3718
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3719
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3720
3721
		if ( isset( $_COOKIE['jetpackState']['display_update_modal'] ) ) {
3722
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3723
		}
3724
3725
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3726
3727
		if ( self::is_connection_ready() || $is_offline_mode ) {
3728
			// Artificially throw errors in certain specific cases during plugin activation.
3729
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3730
		}
3731
3732
		// Add custom column in wp-admin/users.php to show whether user is linked.
3733
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3734
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3735
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3736
	}
3737
3738
	function admin_body_class( $admin_body_class = '' ) {
3739
		$classes = explode( ' ', trim( $admin_body_class ) );
3740
3741
		$classes[] = self::is_connection_ready() ? 'jetpack-connected' : 'jetpack-disconnected';
3742
3743
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3744
		return " $admin_body_class ";
3745
	}
3746
3747
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3748
		return $admin_body_class . ' jetpack-pagestyles ';
3749
	}
3750
3751
	/**
3752
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3753
	 * This function artificially throws errors for such cases (per a specific list).
3754
	 *
3755
	 * @param string $plugin The activated plugin.
3756
	 */
3757
	function throw_error_on_activate_plugin( $plugin ) {
3758
		$active_modules = self::get_active_modules();
3759
3760
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3761
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3762
			$throw = false;
3763
3764
			// Try and make sure it really was the stats plugin
3765
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3766
				if ( 'stats.php' == basename( $plugin ) ) {
3767
					$throw = true;
3768
				}
3769
			} else {
3770
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3771
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3772
					$throw = true;
3773
				}
3774
			}
3775
3776
			if ( $throw ) {
3777
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3778
			}
3779
		}
3780
	}
3781
3782
	function intercept_plugin_error_scrape_init() {
3783
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3784
	}
3785
3786
	function intercept_plugin_error_scrape( $action, $result ) {
3787
		if ( ! $result ) {
3788
			return;
3789
		}
3790
3791
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3792
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3793
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3794
			}
3795
		}
3796
	}
3797
3798
	/**
3799
	 * Register the remote file upload request handlers, if needed.
3800
	 *
3801
	 * @access public
3802
	 */
3803
	public function add_remote_request_handlers() {
3804
		// Remote file uploads are allowed only via AJAX requests.
3805
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3806
			return;
3807
		}
3808
3809
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3810
		$remote_request_actions = array(
3811
			'jetpack_upload_file',
3812
			'jetpack_update_file',
3813
		);
3814
3815
		// phpcs:ignore WordPress.Security.NonceVerification
3816
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3817
			return;
3818
		}
3819
3820
		// Require Jetpack authentication for the remote file upload AJAX requests.
3821
		if ( ! $this->connection_manager ) {
3822
			$this->connection_manager = new Connection_Manager();
3823
		}
3824
3825
		$this->connection_manager->require_jetpack_authentication();
3826
3827
		// Register the remote file upload AJAX handlers.
3828
		foreach ( $remote_request_actions as $action ) {
3829
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3830
		}
3831
	}
3832
3833
	/**
3834
	 * Handler for Jetpack remote file uploads.
3835
	 *
3836
	 * @access public
3837
	 */
3838
	public function remote_request_handlers() {
3839
		$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...
3840
3841
		switch ( current_filter() ) {
3842
			case 'wp_ajax_nopriv_jetpack_upload_file':
3843
				$response = $this->upload_handler();
3844
				break;
3845
3846
			case 'wp_ajax_nopriv_jetpack_update_file':
3847
				$response = $this->upload_handler( true );
3848
				break;
3849
			default:
3850
				$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...
3851
				break;
3852
		}
3853
3854
		if ( ! $response ) {
3855
			$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...
3856
		}
3857
3858
		if ( is_wp_error( $response ) ) {
3859
			$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...
3860
			$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...
3861
			$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...
3862
3863
			if ( ! is_int( $status_code ) ) {
3864
				$status_code = 400;
3865
			}
3866
3867
			status_header( $status_code );
3868
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3869
		}
3870
3871
		status_header( 200 );
3872
		if ( true === $response ) {
3873
			exit;
3874
		}
3875
3876
		die( json_encode( (object) $response ) );
3877
	}
3878
3879
	/**
3880
	 * Uploads a file gotten from the global $_FILES.
3881
	 * If `$update_media_item` is true and `post_id` is defined
3882
	 * the attachment file of the media item (gotten through of the post_id)
3883
	 * will be updated instead of add a new one.
3884
	 *
3885
	 * @param  boolean $update_media_item - update media attachment
3886
	 * @return array - An array describing the uploadind files process
3887
	 */
3888
	function upload_handler( $update_media_item = false ) {
3889
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3890
			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...
3891
		}
3892
3893
		$user = wp_authenticate( '', '' );
3894
		if ( ! $user || is_wp_error( $user ) ) {
3895
			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...
3896
		}
3897
3898
		wp_set_current_user( $user->ID );
3899
3900
		if ( ! current_user_can( 'upload_files' ) ) {
3901
			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...
3902
		}
3903
3904
		if ( empty( $_FILES ) ) {
3905
			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 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...
3906
		}
3907
3908
		foreach ( array_keys( $_FILES ) as $files_key ) {
3909
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3910
				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...
3911
			}
3912
		}
3913
3914
		$media_keys = array_keys( $_FILES['media'] );
3915
3916
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3917
		if ( ! $token || is_wp_error( $token ) ) {
3918
			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...
3919
		}
3920
3921
		$uploaded_files = array();
3922
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3923
		unset( $GLOBALS['post'] );
3924
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3925
			$file = array();
3926
			foreach ( $media_keys as $media_key ) {
3927
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3928
			}
3929
3930
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3931
3932
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3933
			if ( $hmac_provided !== $hmac_file ) {
3934
				$uploaded_files[ $index ] = (object) array(
3935
					'error'             => 'invalid_hmac',
3936
					'error_description' => 'The corresponding HMAC for this file does not match',
3937
				);
3938
				continue;
3939
			}
3940
3941
			$_FILES['.jetpack.upload.'] = $file;
3942
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3943
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3944
				$post_id = 0;
3945
			}
3946
3947
			if ( $update_media_item ) {
3948
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3949
					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...
3950
				}
3951
3952
				$media_array = $_FILES['media'];
3953
3954
				$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...
3955
				$file_array['type']     = $media_array['type'][0];
3956
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3957
				$file_array['error']    = $media_array['error'][0];
3958
				$file_array['size']     = $media_array['size'][0];
3959
3960
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3961
3962
				if ( is_wp_error( $edited_media_item ) ) {
3963
					return $edited_media_item;
3964
				}
3965
3966
				$response = (object) array(
3967
					'id'   => (string) $post_id,
3968
					'file' => (string) $edited_media_item->post_title,
3969
					'url'  => (string) wp_get_attachment_url( $post_id ),
3970
					'type' => (string) $edited_media_item->post_mime_type,
3971
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3972
				);
3973
3974
				return (array) array( $response );
3975
			}
3976
3977
			$attachment_id = media_handle_upload(
3978
				'.jetpack.upload.',
3979
				$post_id,
3980
				array(),
3981
				array(
3982
					'action' => 'jetpack_upload_file',
3983
				)
3984
			);
3985
3986
			if ( ! $attachment_id ) {
3987
				$uploaded_files[ $index ] = (object) array(
3988
					'error'             => 'unknown',
3989
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3990
				);
3991
			} elseif ( is_wp_error( $attachment_id ) ) {
3992
				$uploaded_files[ $index ] = (object) array(
3993
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3994
					'error_description' => $attachment_id->get_error_message(),
3995
				);
3996
			} else {
3997
				$attachment               = get_post( $attachment_id );
3998
				$uploaded_files[ $index ] = (object) array(
3999
					'id'   => (string) $attachment_id,
4000
					'file' => $attachment->post_title,
4001
					'url'  => wp_get_attachment_url( $attachment_id ),
4002
					'type' => $attachment->post_mime_type,
4003
					'meta' => wp_get_attachment_metadata( $attachment_id ),
4004
				);
4005
				// Zip files uploads are not supported unless they are done for installation purposed
4006
				// lets delete them in case something goes wrong in this whole process
4007
				if ( 'application/zip' === $attachment->post_mime_type ) {
4008
					// Schedule a cleanup for 2 hours from now in case of failed install.
4009
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
4010
				}
4011
			}
4012
		}
4013
		if ( ! is_null( $global_post ) ) {
4014
			$GLOBALS['post'] = $global_post;
4015
		}
4016
4017
		return $uploaded_files;
4018
	}
4019
4020
	/**
4021
	 * Add help to the Jetpack page
4022
	 *
4023
	 * @since Jetpack (1.2.3)
4024
	 * @return false if not the Jetpack page
4025
	 */
4026
	function admin_help() {
4027
		$current_screen = get_current_screen();
4028
4029
		// Overview
4030
		$current_screen->add_help_tab(
4031
			array(
4032
				'id'      => 'home',
4033
				'title'   => __( 'Home', 'jetpack' ),
4034
				'content' =>
4035
					'<p><strong>' . __( 'Jetpack', 'jetpack' ) . '</strong></p>' .
4036
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4037
					'<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>',
4038
			)
4039
		);
4040
4041
		// Screen Content
4042
		if ( current_user_can( 'manage_options' ) ) {
4043
			$current_screen->add_help_tab(
4044
				array(
4045
					'id'      => 'settings',
4046
					'title'   => __( 'Settings', 'jetpack' ),
4047
					'content' =>
4048
						'<p><strong>' . __( 'Jetpack', 'jetpack' ) . '</strong></p>' .
4049
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4050
						'<ol>' .
4051
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4052
							'<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>' .
4053
						'</ol>' .
4054
						'<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>',
4055
				)
4056
			);
4057
		}
4058
4059
		// Help Sidebar
4060
		$support_url = Redirect::get_url( 'jetpack-support' );
4061
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4062
		$current_screen->set_help_sidebar(
4063
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4064
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4065
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4066
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4067
		);
4068
	}
4069
4070
	function admin_menu_css() {
4071
		wp_enqueue_style( 'jetpack-icons' );
4072
	}
4073
4074
	function admin_menu_order() {
4075
		return true;
4076
	}
4077
4078
	function jetpack_menu_order( $menu_order ) {
4079
		$jp_menu_order = array();
4080
4081
		foreach ( $menu_order as $index => $item ) {
4082
			if ( $item != 'jetpack' ) {
4083
				$jp_menu_order[] = $item;
4084
			}
4085
4086
			if ( $index == 0 ) {
4087
				$jp_menu_order[] = 'jetpack';
4088
			}
4089
		}
4090
4091
		return $jp_menu_order;
4092
	}
4093
4094
	function admin_banner_styles() {
4095
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4096
4097 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4098
			wp_register_style(
4099
				'jetpack-dops-style',
4100
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4101
				array(),
4102
				JETPACK__VERSION
4103
			);
4104
		}
4105
4106
		wp_enqueue_style(
4107
			'jetpack',
4108
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4109
			array( 'jetpack-dops-style' ),
4110
			JETPACK__VERSION . '-20121016'
4111
		);
4112
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4113
		wp_style_add_data( 'jetpack', 'suffix', $min );
4114
	}
4115
4116
	function plugin_action_links( $actions ) {
4117
4118
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), __( 'My Jetpack', 'jetpack' ) ) );
4119
4120
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
4121
			return array_merge(
4122
				$jetpack_home,
4123
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4124
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4125
				$actions
4126
			);
4127
		}
4128
4129
		return array_merge( $jetpack_home, $actions );
4130
	}
4131
4132
	/**
4133
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4134
	 *
4135
	 * @param string $hook The current admin page.
4136
	 *
4137
	 * @return void
4138
	 */
4139
	public function deactivate_dialog( $hook ) {
4140
		if (
4141
			'plugins.php' === $hook
4142
			&& self::is_connection_ready()
4143
		) {
4144
4145
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4146
4147
			if ( count( $active_plugins_using_connection ) > 1 ) {
4148
4149
				add_thickbox();
4150
4151
				// Register jp-tracks-functions dependency.
4152
				Tracking::register_tracks_functions_scripts();
4153
4154
				wp_enqueue_script(
4155
					'jetpack-deactivate-dialog-js',
4156
					Assets::get_file_url_for_environment(
4157
						'_inc/build/jetpack-deactivate-dialog.min.js',
4158
						'_inc/jetpack-deactivate-dialog.js'
4159
					),
4160
					array( 'jquery', 'jp-tracks-functions' ),
4161
					JETPACK__VERSION,
4162
					true
4163
				);
4164
4165
				wp_localize_script(
4166
					'jetpack-deactivate-dialog-js',
4167
					'deactivate_dialog',
4168
					array(
4169
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4170
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4171
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4172
					)
4173
				);
4174
4175
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4176
4177
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4178
			}
4179
		}
4180
	}
4181
4182
	/**
4183
	 * Outputs the content of the deactivation modal
4184
	 *
4185
	 * @return void
4186
	 */
4187
	public function deactivate_dialog_content() {
4188
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4189
		unset( $active_plugins_using_connection['jetpack'] );
4190
		$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 4188 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...
4191
	}
4192
4193
	/**
4194
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4195
	 *
4196
	 * @param string $login_url The wp-login URL.
4197
	 * @param string $redirect  URL to redirect users after logging in.
4198
	 * @since Jetpack 8.4
4199
	 * @return string
4200
	 */
4201
	public function login_url( $login_url, $redirect ) {
4202
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4203
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4204
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4205
		}
4206
		return $login_url;
4207
	}
4208
4209
	/**
4210
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4211
	 *
4212
	 * @since Jetpack 8.4
4213
	 */
4214
	public function login_init() {
4215
		// phpcs:ignore WordPress.Security.NonceVerification
4216
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4217
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4218
			wp_safe_redirect(
4219
				add_query_arg(
4220
					array(
4221
						'forceInstall' => 1,
4222
						'url'          => rawurlencode( get_site_url() ),
4223
					),
4224
					// @todo provide way to go to specific calypso env.
4225
					self::get_calypso_host() . 'jetpack/connect'
4226
				)
4227
			);
4228
			exit;
4229
		}
4230
	}
4231
4232
	/*
4233
	 * Registration flow:
4234
	 * 1 - ::admin_page_load() action=register
4235
	 * 2 - ::try_registration()
4236
	 * 3 - ::register()
4237
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4238
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4239
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4240
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4241
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4242
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4243
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4244
	 *       jetpack_id, jetpack_secret, jetpack_public
4245
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4246
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4247
	 * 5 - user logs in with WP.com account
4248
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4249
	 *		- Manager::authorize()
4250
	 *		- Manager::get_token()
4251
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4252
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4253
	 *			- which responds with access_token, token_type, scope
4254
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4255
	 *		- Jetpack::activate_default_modules()
4256
	 *     		- Deactivates deprecated plugins
4257
	 *     		- Activates all default modules
4258
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4259
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4260
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4261
	 *     Done!
4262
	 */
4263
4264
	/**
4265
	 * Handles the page load events for the Jetpack admin page
4266
	 */
4267
	function admin_page_load() {
4268
		$error = false;
4269
4270
		// Make sure we have the right body class to hook stylings for subpages off of.
4271
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4272
4273
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4274
			// Should only be used in intermediate redirects to preserve state across redirects
4275
			self::restate();
4276
		}
4277
4278
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4279
			// @todo: Add validation against a known allowed list.
4280
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4281
			// User clicked in the iframe to link their accounts
4282
			if ( ! self::connection()->is_user_connected() ) {
4283
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4284
4285
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4286
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4287
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4288
4289
				if ( isset( $_GET['notes_iframe'] ) ) {
4290
					$connect_url .= '&notes_iframe';
4291
				}
4292
				wp_redirect( $connect_url );
4293
				exit;
4294
			} else {
4295
				if ( ! isset( $_GET['calypso_env'] ) ) {
4296
					self::state( 'message', 'already_authorized' );
4297
					wp_safe_redirect( self::admin_url() );
4298
					exit;
4299
				} else {
4300
					$connect_url  = $this->build_connect_url( true, false, $from );
4301
					$connect_url .= '&already_authorized=true';
4302
					wp_redirect( $connect_url );
4303
					exit;
4304
				}
4305
			}
4306
		}
4307
4308
		if ( isset( $_GET['action'] ) ) {
4309
			switch ( $_GET['action'] ) {
4310
				case 'authorize_redirect':
4311
					self::log( 'authorize_redirect' );
4312
4313
					add_filter(
4314
						'allowed_redirect_hosts',
4315
						function ( $domains ) {
4316
							$domains[] = 'jetpack.com';
4317
							$domains[] = 'jetpack.wordpress.com';
4318
							$domains[] = 'wordpress.com';
4319
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4320
							return array_unique( $domains );
4321
						}
4322
					);
4323
4324
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4325
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4326
4327
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4328
						// The destination URL is missing or invalid, nothing to do here.
4329
						exit;
4330
					}
4331
4332
					if ( static::connection()->is_connected() && static::connection()->is_user_connected() ) {
4333
						// The user is either already connected, or finished the connection process.
4334
						wp_safe_redirect( $dest_url );
4335
						exit;
4336
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4337
						// The user decided not to proceed with setting up the connection.
4338
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4339
						exit;
4340
					}
4341
4342
					$redirect_args = array(
4343
						'page'     => 'jetpack',
4344
						'action'   => 'authorize_redirect',
4345
						'dest_url' => rawurlencode( $dest_url ),
4346
						'done'     => '1',
4347
					);
4348
4349
					if ( ! empty( $_GET['from'] ) && 'jetpack_site_only_checkout' === $_GET['from'] ) {
4350
						$redirect_args['from'] = 'jetpack_site_only_checkout';
4351
					}
4352
4353
					wp_safe_redirect( static::build_authorize_url( self::admin_url( $redirect_args ) ) );
0 ignored issues
show
Documentation introduced by
self::admin_url($redirect_args) is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4354
					exit;
4355
				case 'authorize':
4356
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4357
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4358
					exit;
4359
				case 'register':
4360
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4361
						$error = 'cheatin';
4362
						break;
4363
					}
4364
					check_admin_referer( 'jetpack-register' );
4365
					self::log( 'register' );
4366
					self::maybe_set_version_option();
4367
					$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4368
					if ( $from ) {
4369
						static::connection()->add_register_request_param( 'from', (string) $from );
4370
					}
4371
					$registered = static::connection()->try_registration();
4372
					if ( is_wp_error( $registered ) ) {
4373
						$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...
4374
						self::state( 'error', $error );
4375
						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...
4376
4377
						/**
4378
						 * Jetpack registration Error.
4379
						 *
4380
						 * @since 7.5.0
4381
						 *
4382
						 * @param string|int $error The error code.
4383
						 * @param \WP_Error $registered The error object.
4384
						 */
4385
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4386
						break;
4387
					}
4388
4389
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4390
4391
					/**
4392
					 * Jetpack registration Success.
4393
					 *
4394
					 * @since 7.5.0
4395
					 *
4396
					 * @param string $from 'from' GET parameter;
4397
					 */
4398
					do_action( 'jetpack_connection_register_success', $from );
4399
4400
					$url = $this->build_connect_url( true, $redirect, $from );
4401
4402
					if ( ! empty( $_GET['onboarding'] ) ) {
4403
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4404
					}
4405
4406
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4407
						$url = add_query_arg( 'auth_approved', 'true', $url );
4408
					}
4409
4410
					wp_redirect( $url );
4411
					exit;
4412
				case 'activate':
4413
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4414
						$error = 'cheatin';
4415
						break;
4416
					}
4417
4418
					$module = stripslashes( $_GET['module'] );
4419
					check_admin_referer( "jetpack_activate-$module" );
4420
					self::log( 'activate', $module );
4421
					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...
4422
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4423
					}
4424
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4425
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4426
					exit;
4427
				case 'activate_default_modules':
4428
					check_admin_referer( 'activate_default_modules' );
4429
					self::log( 'activate_default_modules' );
4430
					self::restate();
4431
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4432
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4433
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4434
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4435
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4436
					exit;
4437 View Code Duplication
				case 'disconnect':
4438
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4439
						$error = 'cheatin';
4440
						break;
4441
					}
4442
4443
					check_admin_referer( 'jetpack-disconnect' );
4444
					self::log( 'disconnect' );
4445
					self::disconnect();
4446
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4447
					exit;
4448 View Code Duplication
				case 'reconnect':
4449
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4450
						$error = 'cheatin';
4451
						break;
4452
					}
4453
4454
					check_admin_referer( 'jetpack-reconnect' );
4455
					self::log( 'reconnect' );
4456
					self::disconnect();
4457
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4458
					exit;
4459 View Code Duplication
				case 'deactivate':
4460
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4461
						$error = 'cheatin';
4462
						break;
4463
					}
4464
4465
					$modules = stripslashes( $_GET['module'] );
4466
					check_admin_referer( "jetpack_deactivate-$modules" );
4467
					foreach ( explode( ',', $modules ) as $module ) {
4468
						self::log( 'deactivate', $module );
4469
						self::deactivate_module( $module );
4470
						self::state( 'message', 'module_deactivated' );
4471
					}
4472
					self::state( 'module', $modules );
4473
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4474
					exit;
4475
				case 'unlink':
4476
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4477
					check_admin_referer( 'jetpack-unlink' );
4478
					self::log( 'unlink' );
4479
					$this->connection_manager->disconnect_user();
4480
					self::state( 'message', 'unlinked' );
4481
					if ( 'sub-unlink' == $redirect ) {
4482
						wp_safe_redirect( admin_url() );
4483
					} else {
4484
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4485
					}
4486
					exit;
4487
				case 'onboard':
4488
					if ( ! current_user_can( 'manage_options' ) ) {
4489
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4490
					} else {
4491
						self::create_onboarding_token();
4492
						$url = $this->build_connect_url( true );
4493
4494
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4495
							$url = add_query_arg( 'onboarding', $token, $url );
4496
						}
4497
4498
						$calypso_env = $this->get_calypso_env();
4499
						if ( ! empty( $calypso_env ) ) {
4500
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4501
						}
4502
4503
						wp_redirect( $url );
4504
						exit;
4505
					}
4506
					exit;
4507
				default:
4508
					/**
4509
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4510
					 *
4511
					 * @since 2.6.0
4512
					 *
4513
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4514
					 */
4515
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4516
			}
4517
		}
4518
4519
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4520
			self::activate_new_modules( true );
4521
		}
4522
4523
		$message_code = self::state( 'message' );
4524
		if ( self::state( 'optin-manage' ) ) {
4525
			$activated_manage = $message_code;
4526
			$message_code     = 'jetpack-manage';
4527
		}
4528
4529
		switch ( $message_code ) {
4530
			case 'jetpack-manage':
4531
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4532
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4533
				$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>';
4534
				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...
4535
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4536
				}
4537
				break;
4538
4539
		}
4540
4541
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4542
4543
		if ( ! empty( $deactivated_plugins ) ) {
4544
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4545
			$deactivated_titles  = array();
4546
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4547
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4548
					continue;
4549
				}
4550
4551
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4552
			}
4553
4554
			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...
4555
				if ( $this->message ) {
4556
					$this->message .= "<br /><br />\n";
4557
				}
4558
4559
				$this->message .= wp_sprintf(
4560
					_n(
4561
						'Jetpack contains the most recent version of the old %l plugin.',
4562
						'Jetpack contains the most recent versions of the old %l plugins.',
4563
						count( $deactivated_titles ),
4564
						'jetpack'
4565
					),
4566
					$deactivated_titles
4567
				);
4568
4569
				$this->message .= "<br />\n";
4570
4571
				$this->message .= _n(
4572
					'The old version has been deactivated and can be removed from your site.',
4573
					'The old versions have been deactivated and can be removed from your site.',
4574
					count( $deactivated_titles ),
4575
					'jetpack'
4576
				);
4577
			}
4578
		}
4579
4580
		$this->privacy_checks = self::state( 'privacy_checks' );
4581
4582
		if ( $this->message || $this->error || $this->privacy_checks ) {
4583
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4584
		}
4585
4586
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4587
	}
4588
4589
	function admin_notices() {
4590
4591
		if ( $this->error ) {
4592
			?>
4593
<div id="message" class="jetpack-message jetpack-err">
4594
	<div class="squeezer">
4595
		<h2>
4596
			<?php
4597
			echo wp_kses(
4598
				$this->error,
4599
				array(
4600
					'a'      => array( 'href' => array() ),
4601
					'small'  => true,
4602
					'code'   => true,
4603
					'strong' => true,
4604
					'br'     => true,
4605
					'b'      => true,
4606
				)
4607
			);
4608
			?>
4609
			</h2>
4610
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4611
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4612
<?php	endif; ?>
4613
	</div>
4614
</div>
4615
			<?php
4616
		}
4617
4618
		if ( $this->message ) {
4619
			?>
4620
<div id="message" class="jetpack-message">
4621
	<div class="squeezer">
4622
		<h2>
4623
			<?php
4624
			echo wp_kses(
4625
				$this->message,
4626
				array(
4627
					'strong' => array(),
4628
					'a'      => array( 'href' => true ),
4629
					'br'     => true,
4630
				)
4631
			);
4632
			?>
4633
			</h2>
4634
	</div>
4635
</div>
4636
			<?php
4637
		}
4638
4639
		if ( $this->privacy_checks ) :
4640
			$module_names = $module_slugs = array();
4641
4642
			$privacy_checks = explode( ',', $this->privacy_checks );
4643
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4644
			foreach ( $privacy_checks as $module_slug ) {
4645
				$module = self::get_module( $module_slug );
4646
				if ( ! $module ) {
4647
					continue;
4648
				}
4649
4650
				$module_slugs[] = $module_slug;
4651
				$module_names[] = "<strong>{$module['name']}</strong>";
4652
			}
4653
4654
			$module_slugs = join( ',', $module_slugs );
4655
			?>
4656
<div id="message" class="jetpack-message jetpack-err">
4657
	<div class="squeezer">
4658
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4659
		<p>
4660
			<?php
4661
			echo wp_kses(
4662
				wptexturize(
4663
					wp_sprintf(
4664
						_nx(
4665
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4666
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4667
							count( $privacy_checks ),
4668
							'%l = list of Jetpack module/feature names',
4669
							'jetpack'
4670
						),
4671
						$module_names
4672
					)
4673
				),
4674
				array( 'strong' => true )
4675
			);
4676
4677
			echo "\n<br />\n";
4678
4679
			echo wp_kses(
4680
				sprintf(
4681
					_nx(
4682
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4683
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4684
						count( $privacy_checks ),
4685
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4686
						'jetpack'
4687
					),
4688
					wp_nonce_url(
4689
						self::admin_url(
4690
							array(
4691
								'page'   => 'jetpack',
4692
								'action' => 'deactivate',
4693
								'module' => urlencode( $module_slugs ),
4694
							)
4695
						),
4696
						"jetpack_deactivate-$module_slugs"
4697
					),
4698
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4699
				),
4700
				array(
4701
					'a' => array(
4702
						'href'  => true,
4703
						'title' => true,
4704
					),
4705
				)
4706
			);
4707
			?>
4708
		</p>
4709
	</div>
4710
</div>
4711
			<?php
4712
endif;
4713
	}
4714
4715
	/**
4716
	 * We can't always respond to a signed XML-RPC request with a
4717
	 * helpful error message. In some circumstances, doing so could
4718
	 * leak information.
4719
	 *
4720
	 * Instead, track that the error occurred via a Jetpack_Option,
4721
	 * and send that data back in the heartbeat.
4722
	 * All this does is increment a number, but it's enough to find
4723
	 * trends.
4724
	 *
4725
	 * @param WP_Error $xmlrpc_error The error produced during
4726
	 *                               signature validation.
4727
	 */
4728
	function track_xmlrpc_error( $xmlrpc_error ) {
4729
		$code = is_wp_error( $xmlrpc_error )
4730
			? $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...
4731
			: 'should-not-happen';
4732
4733
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4734
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4735
			// No need to update the option if we already have
4736
			// this code stored.
4737
			return;
4738
		}
4739
		$xmlrpc_errors[ $code ] = true;
4740
4741
		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...
4742
	}
4743
4744
	/**
4745
	 * Initialize the jetpack stats instance only when needed
4746
	 *
4747
	 * @return void
4748
	 */
4749
	private function initialize_stats() {
4750
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4751
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4752
		}
4753
	}
4754
4755
	/**
4756
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4757
	 */
4758
	function stat( $group, $detail ) {
4759
		$this->initialize_stats();
4760
		$this->a8c_mc_stats_instance->add( $group, $detail );
4761
4762
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4763
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4764
	}
4765
4766
	/**
4767
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4768
	 */
4769
	function do_stats( $method = '' ) {
4770
		$this->initialize_stats();
4771
		if ( 'server_side' === $method ) {
4772
			$this->a8c_mc_stats_instance->do_server_side_stats();
4773
		} else {
4774
			$this->a8c_mc_stats_instance->do_stats();
4775
		}
4776
4777
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4778
		$this->stats = array();
4779
	}
4780
4781
	/**
4782
	 * Runs stats code for a one-off, server-side.
4783
	 *
4784
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4785
	 *
4786
	 * @return bool If it worked.
4787
	 */
4788
	static function do_server_side_stat( $args ) {
4789
		$url                   = self::build_stats_url( $args );
4790
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4791
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4792
	}
4793
4794
	/**
4795
	 * Builds the stats url.
4796
	 *
4797
	 * @param $args array|string The arguments to append to the URL.
4798
	 *
4799
	 * @return string The URL to be pinged.
4800
	 */
4801
	static function build_stats_url( $args ) {
4802
4803
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4804
		return $a8c_mc_stats_instance->build_stats_url( $args );
4805
4806
	}
4807
4808
	/**
4809
	 * Builds a URL to the Jetpack connection auth page
4810
	 *
4811
	 * @since 3.9.5
4812
	 *
4813
	 * @param bool        $raw If true, URL will not be escaped.
4814
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4815
	 *                              If string, will be a custom redirect.
4816
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4817
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4818
	 *
4819
	 * @return string Connect URL
4820
	 */
4821
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4822
		$site_id    = Jetpack_Options::get_option( 'id' );
4823
		$blog_token = ( new Tokens() )->get_access_token();
4824
4825
		if ( $register || ! $blog_token || ! $site_id ) {
4826
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4827
4828
			if ( ! empty( $redirect ) ) {
4829
				$url = add_query_arg(
4830
					'redirect',
4831
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4832
					$url
4833
				);
4834
			}
4835
4836
			if ( is_network_admin() ) {
4837
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4838
			}
4839
4840
			$calypso_env = self::get_calypso_env();
4841
4842
			if ( ! empty( $calypso_env ) ) {
4843
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4844
			}
4845
		} else {
4846
4847
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4848
			// because otherwise this logic can get us in to a loop.
4849
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4850
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4851
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4852
4853
				$response = Client::wpcom_json_api_request_as_blog(
4854
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4855
					'1.1'
4856
				);
4857
4858
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4859
4860
					// Generating a register URL instead to refresh the existing token
4861
					return $this->build_connect_url( $raw, $redirect, $from, true );
4862
				}
4863
			}
4864
4865
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4821 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...
4866
		}
4867
4868
		if ( $from ) {
4869
			$url = add_query_arg( 'from', $from, $url );
4870
		}
4871
4872
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4873
		/**
4874
		 * Filter the URL used when connecting a user to a WordPress.com account.
4875
		 *
4876
		 * @since 8.1.0
4877
		 *
4878
		 * @param string $url Connection URL.
4879
		 * @param bool   $raw If true, URL will not be escaped.
4880
		 */
4881
		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...
4882
	}
4883
4884
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4885
4886
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4887
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4888
4889
		if ( $iframe ) {
4890
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4891
		}
4892
4893
		$c8n = self::connection();
4894
		$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...
4895
4896
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4897
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4898
4899
		if ( $iframe ) {
4900
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4901
		}
4902
4903
		/**
4904
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4905
		 *
4906
		 * @since 8.9.0
4907
		 *
4908
		 * @param string $url Connection URL.
4909
		 */
4910
		return apply_filters( 'jetpack_build_authorize_url', $url );
4911
	}
4912
4913
	/**
4914
	 * Filters the connection URL parameter array.
4915
	 *
4916
	 * @param array $args default URL parameters used by the package.
4917
	 * @return array the modified URL arguments array.
4918
	 */
4919
	public static function filter_connect_request_body( $args ) {
4920
		if (
4921
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4922
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4923
		) {
4924
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4925
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4926
				? $gp_locale->slug
4927
				: '';
4928
		}
4929
4930
		$tracking        = new Tracking();
4931
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4932
4933
		$args = array_merge(
4934
			$args,
4935
			array(
4936
				'_ui' => $tracks_identity['_ui'],
4937
				'_ut' => $tracks_identity['_ut'],
4938
			)
4939
		);
4940
4941
		$calypso_env = self::get_calypso_env();
4942
4943
		if ( ! empty( $calypso_env ) ) {
4944
			$args['calypso_env'] = $calypso_env;
4945
		}
4946
4947
		return $args;
4948
	}
4949
4950
	/**
4951
	 * Filters the URL that will process the connection data. It can be different from the URL
4952
	 * that we send the user to after everything is done.
4953
	 *
4954
	 * @param String $processing_url the default redirect URL used by the package.
4955
	 * @return String the modified URL.
4956
	 *
4957
	 * @deprecated since Jetpack 9.5.0
4958
	 */
4959
	public static function filter_connect_processing_url( $processing_url ) {
4960
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4961
4962
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4963
		return $processing_url;
4964
	}
4965
4966
	/**
4967
	 * Filters the redirection URL that is used for connect requests. The redirect
4968
	 * URL should return the user back to the Jetpack console.
4969
	 *
4970
	 * @param String $redirect the default redirect URL used by the package.
4971
	 * @return String the modified URL.
4972
	 */
4973
	public static function filter_connect_redirect_url( $redirect ) {
4974
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4975
		$redirect           = $redirect
4976
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4977
			: $jetpack_admin_page;
4978
4979
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4980
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4981
		}
4982
4983
		return $redirect;
4984
	}
4985
4986
	/**
4987
	 * This action fires at the beginning of the Manager::authorize method.
4988
	 */
4989
	public static function authorize_starting() {
4990
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4991
		// Checking if site has been active/connected previously before recording unique connection.
4992
		if ( ! $jetpack_unique_connection ) {
4993
			// jetpack_unique_connection option has never been set.
4994
			$jetpack_unique_connection = array(
4995
				'connected'    => 0,
4996
				'disconnected' => 0,
4997
				'version'      => '3.6.1',
4998
			);
4999
5000
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
5001
5002
			// Track unique connection.
5003
			$jetpack = self::init();
5004
5005
			$jetpack->stat( 'connections', 'unique-connection' );
5006
			$jetpack->do_stats( 'server_side' );
5007
		}
5008
5009
		// Increment number of times connected.
5010
		$jetpack_unique_connection['connected'] += 1;
5011
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5012
	}
5013
5014
	/**
5015
	 * This action fires when the site is registered (connected at a site level).
5016
	 */
5017
	public function handle_unique_registrations_stats() {
5018
		$jetpack_unique_registrations = Jetpack_Options::get_option( 'unique_registrations' );
5019
		// Checking if site has been registered previously before recording unique connection.
5020
		if ( ! $jetpack_unique_registrations ) {
5021
5022
			$jetpack_unique_registrations = 0;
5023
5024
			$this->stat( 'connections', 'unique-registrations' );
5025
			$this->do_stats( 'server_side' );
5026
		}
5027
5028
		// Increment number of times connected.
5029
		$jetpack_unique_registrations ++;
5030
		Jetpack_Options::update_option( 'unique_registrations', $jetpack_unique_registrations );
5031
	}
5032
5033
	/**
5034
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5035
	 * linked.
5036
	 */
5037
	public static function authorize_ending_linked() {
5038
		// Don't activate anything since we are just connecting a user.
5039
		self::state( 'message', 'linked' );
5040
	}
5041
5042
	/**
5043
	 * This action fires at the end of the Manager::authorize method when the master user is
5044
	 * authorized.
5045
	 *
5046
	 * @param array $data The request data.
5047
	 */
5048
	public static function authorize_ending_authorized( $data ) {
5049
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5050
		self::invalidate_onboarding_token();
5051
5052
		// If redirect_uri is SSO, ensure SSO module is enabled.
5053
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5054
5055
		/** This filter is documented in class.jetpack-cli.php */
5056
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5057
5058
		$activate_sso = (
5059
			isset( $redirect_options['action'] ) &&
5060
			'jetpack-sso' === $redirect_options['action'] &&
5061
			$jetpack_start_enable_sso
5062
		);
5063
5064
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5065
5066
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5067
	}
5068
5069
	/**
5070
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5071
	 */
5072
	public static function activate_default_modules_on_site_register() {
5073
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5074
		if ( $active_modules ) {
5075
			self::delete_active_modules();
5076
5077
			// If there was previously activated modules (a reconnection), re-activate them all including those that require a user, and do not re-activate those that have been deactivated.
5078
			self::activate_default_modules( 999, 1, $active_modules, false );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
5079
		} else {
5080
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5081
			self::activate_default_modules( false, false, array(), false, null, null, false );
5082
		}
5083
5084
		// Since this is a fresh connection, be sure to clear out IDC options.
5085
		Identity_Crisis::clear_all_idc_options();
5086
	}
5087
5088
	/**
5089
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5090
	 * reconnect process is completed.
5091
	 * Note that this currently only happens when we don't need the user to re-authorize
5092
	 * their WP.com account, eg in cases where we are restoring a connection with
5093
	 * unhealthy blog token.
5094
	 */
5095
	public static function reconnection_completed() {
5096
		self::state( 'message', 'reconnection_completed' );
5097
	}
5098
5099
	/**
5100
	 * Get our assumed site creation date.
5101
	 * Calculated based on the earlier date of either:
5102
	 * - Earliest admin user registration date.
5103
	 * - Earliest date of post of any post type.
5104
	 *
5105
	 * @since 7.2.0
5106
	 * @deprecated since 7.8.0
5107
	 *
5108
	 * @return string Assumed site creation date and time.
5109
	 */
5110
	public static function get_assumed_site_creation_date() {
5111
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5112
		return self::connection()->get_assumed_site_creation_date();
5113
	}
5114
5115 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5116
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5117
5118
		if ( $activation_source_name ) {
5119
			$args['_as'] = urlencode( $activation_source_name );
5120
		}
5121
5122
		if ( $activation_source_keyword ) {
5123
			$args['_ak'] = urlencode( $activation_source_keyword );
5124
		}
5125
	}
5126
5127
	function build_reconnect_url( $raw = false ) {
5128
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5129
		return $raw ? $url : esc_url( $url );
5130
	}
5131
5132
	public static function admin_url( $args = null ) {
5133
		$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...
5134
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5135
		return $url;
5136
	}
5137
5138
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5139
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5140
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5141
	}
5142
5143
	function dismiss_jetpack_notice() {
5144
5145
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5146
			return;
5147
		}
5148
5149
		switch ( $_GET['jetpack-notice'] ) {
5150
			case 'dismiss':
5151
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5152
5153
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5154
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5155
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5156
				}
5157
				break;
5158
		}
5159
	}
5160
5161
	public static function sort_modules( $a, $b ) {
5162
		if ( $a['sort'] == $b['sort'] ) {
5163
			return 0;
5164
		}
5165
5166
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5167
	}
5168
5169
	function ajax_recheck_ssl() {
5170
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5171
		$result = self::permit_ssl( true );
5172
		wp_send_json(
5173
			array(
5174
				'enabled' => $result,
5175
				'message' => get_transient( 'jetpack_https_test_message' ),
5176
			)
5177
		);
5178
	}
5179
5180
	/* Client API */
5181
5182
	/**
5183
	 * Returns the requested Jetpack API URL
5184
	 *
5185
	 * @deprecated since 7.7
5186
	 * @return string
5187
	 */
5188
	public static function api_url( $relative_url ) {
5189
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5190
		$connection = self::connection();
5191
		return $connection->api_url( $relative_url );
5192
	}
5193
5194
	/**
5195
	 * @deprecated 8.0
5196
	 *
5197
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5198
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5199
	 */
5200
	public static function fix_url_for_bad_hosts( $url ) {
5201
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5202
		return $url;
5203
	}
5204
5205
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5206
		// Default to a blog token.
5207
		$token_type = 'blog';
5208
5209
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5210
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5211
			if ( ! empty( $_GET['onboarding'] ) ) {
5212
				$jpo = $_GET;
5213
			} else {
5214
				$jpo = json_decode( $request_data, true );
5215
			}
5216
5217
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5218
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5219
5220
			if (
5221
				isset( $jpo_user )
5222
				&& isset( $jpo_token )
5223
				&& is_email( $jpo_user )
5224
				&& ctype_alnum( $jpo_token )
5225
				&& isset( $_GET['rest_route'] )
5226
				&& self::validate_onboarding_token_action(
5227
					$jpo_token,
5228
					$_GET['rest_route']
5229
				)
5230
			) {
5231
				$jp_user = get_user_by( 'email', $jpo_user );
5232
				if ( is_a( $jp_user, 'WP_User' ) ) {
5233
					wp_set_current_user( $jp_user->ID );
5234
					$user_can = is_multisite()
5235
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5236
						: current_user_can( 'manage_options' );
5237
					if ( $user_can ) {
5238
						$token_type              = 'user';
5239
						$token->external_user_id = $jp_user->ID;
5240
					}
5241
				}
5242
			}
5243
5244
			$token_data['type']    = $token_type;
5245
			$token_data['user_id'] = $token->external_user_id;
5246
		}
5247
5248
		return $token_data;
5249
	}
5250
5251
	/**
5252
	 * Create a random secret for validating onboarding payload
5253
	 *
5254
	 * @return string Secret token
5255
	 */
5256
	public static function create_onboarding_token() {
5257
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5258
			$token = wp_generate_password( 32, false );
5259
			Jetpack_Options::update_option( 'onboarding', $token );
5260
		}
5261
5262
		return $token;
5263
	}
5264
5265
	/**
5266
	 * Remove the onboarding token
5267
	 *
5268
	 * @return bool True on success, false on failure
5269
	 */
5270
	public static function invalidate_onboarding_token() {
5271
		return Jetpack_Options::delete_option( 'onboarding' );
5272
	}
5273
5274
	/**
5275
	 * Validate an onboarding token for a specific action
5276
	 *
5277
	 * @return boolean True if token/action pair is accepted, false if not
5278
	 */
5279
	public static function validate_onboarding_token_action( $token, $action ) {
5280
		// Compare tokens, bail if tokens do not match
5281
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5282
			return false;
5283
		}
5284
5285
		// List of valid actions we can take
5286
		$valid_actions = array(
5287
			'/jetpack/v4/settings',
5288
		);
5289
5290
		// Only allow valid actions.
5291
		if ( ! in_array( $action, $valid_actions ) ) {
5292
			return false;
5293
		}
5294
5295
		return true;
5296
	}
5297
5298
	/**
5299
	 * Checks to see if the URL is using SSL to connect with Jetpack
5300
	 *
5301
	 * @since 2.3.3
5302
	 * @return boolean
5303
	 */
5304
	public static function permit_ssl( $force_recheck = false ) {
5305
		// Do some fancy tests to see if ssl is being supported
5306
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5307
			$message = '';
5308
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5309
				$ssl = 0;
5310
			} else {
5311
				$ssl = 1;
5312
5313
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5314
					$ssl     = 0;
5315
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5316
				} else {
5317
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5318
					if ( is_wp_error( $response ) ) {
5319
						$ssl     = 0;
5320
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5321
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5322
						$ssl     = 0;
5323
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5324
					}
5325
				}
5326
			}
5327
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5328
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5329
		}
5330
5331
		return (bool) $ssl;
5332
	}
5333
5334
	/*
5335
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5336
	 */
5337
	public function alert_auto_ssl_fail() {
5338
		if ( ! current_user_can( 'manage_options' ) ) {
5339
			return;
5340
		}
5341
5342
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5343
		?>
5344
5345
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5346
			<div class="jp-banner__content">
5347
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5348
				<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>
5349
				<p>
5350
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5351
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5352
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5353
				</p>
5354
				<p>
5355
					<?php
5356
					printf(
5357
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5358
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5359
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5360
					);
5361
					?>
5362
				</p>
5363
			</div>
5364
		</div>
5365
		<style>
5366
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5367
		</style>
5368
		<script type="text/javascript">
5369
			jQuery( document ).ready( function( $ ) {
5370
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5371
					var $this = $( this );
5372
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5373
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5374
					e.preventDefault();
5375
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5376
					$.post( ajaxurl, data )
5377
					  .done( function( response ) {
5378
						  if ( response.enabled ) {
5379
							  $( '#jetpack-ssl-warning' ).hide();
5380
						  } else {
5381
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5382
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5383
						  }
5384
					  }.bind( $this ) );
5385
				} );
5386
			} );
5387
		</script>
5388
5389
		<?php
5390
	}
5391
5392
	/**
5393
	 * Returns the Jetpack XML-RPC API
5394
	 *
5395
	 * @deprecated 8.0 Use Connection_Manager instead.
5396
	 * @return string
5397
	 */
5398
	public static function xmlrpc_api_url() {
5399
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5400
		return self::connection()->xmlrpc_api_url();
5401
	}
5402
5403
	/**
5404
	 * Returns the connection manager object.
5405
	 *
5406
	 * @return Automattic\Jetpack\Connection\Manager
5407
	 */
5408
	public static function connection() {
5409
		$jetpack = static::init();
5410
5411
		// If the connection manager hasn't been instantiated, do that now.
5412
		if ( ! $jetpack->connection_manager ) {
5413
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5414
		}
5415
5416
		return $jetpack->connection_manager;
5417
	}
5418
5419
	/**
5420
	 * Creates two secret tokens and the end of life timestamp for them.
5421
	 *
5422
	 * Note these tokens are unique per call, NOT static per site for connecting.
5423
	 *
5424
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5425
	 *
5426
	 * @since 2.6
5427
	 * @param String  $action  The action name.
5428
	 * @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...
5429
	 * @param Integer $exp     Expiration time in seconds.
5430
	 * @return array
5431
	 */
5432
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5433
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5434
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5435
	}
5436
5437
	public static function get_secrets( $action, $user_id ) {
5438
		$secrets = ( new Secrets() )->get( $action, $user_id );
5439
5440
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5441
			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...
5442
		}
5443
5444
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5445
			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...
5446
		}
5447
5448
		return $secrets;
5449
	}
5450
5451
	/**
5452
	 * Builds the timeout limit for queries talking with the wpcom servers.
5453
	 *
5454
	 * Based on local php max_execution_time in php.ini
5455
	 *
5456
	 * @since 2.6
5457
	 * @return int
5458
	 * @deprecated
5459
	 **/
5460
	public function get_remote_query_timeout_limit() {
5461
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5462
		return self::get_max_execution_time();
5463
	}
5464
5465
	/**
5466
	 * Builds the timeout limit for queries talking with the wpcom servers.
5467
	 *
5468
	 * Based on local php max_execution_time in php.ini
5469
	 *
5470
	 * @since 5.4
5471
	 * @return int
5472
	 **/
5473
	public static function get_max_execution_time() {
5474
		$timeout = (int) ini_get( 'max_execution_time' );
5475
5476
		// Ensure exec time set in php.ini
5477
		if ( ! $timeout ) {
5478
			$timeout = 30;
5479
		}
5480
		return $timeout;
5481
	}
5482
5483
	/**
5484
	 * Sets a minimum request timeout, and returns the current timeout
5485
	 *
5486
	 * @since 5.4
5487
	 **/
5488 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5489
		$timeout = self::get_max_execution_time();
5490
		if ( $timeout < $min_timeout ) {
5491
			$timeout = $min_timeout;
5492
			set_time_limit( $timeout );
5493
		}
5494
		return $timeout;
5495
	}
5496
5497
	/**
5498
	 * Takes the response from the Jetpack register new site endpoint and
5499
	 * verifies it worked properly.
5500
	 *
5501
	 * @since 2.6
5502
	 * @deprecated since 7.7.0
5503
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5504
	 **/
5505
	public function validate_remote_register_response() {
5506
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5507
	}
5508
5509
	/**
5510
	 * @deprecated since Jetpack 9.7.0
5511
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
5512
	 *
5513
	 * @return bool|WP_Error
5514
	 */
5515
	public static function register() {
5516
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
5517
		return static::connection()->try_registration( false );
5518
	}
5519
5520
	/**
5521
	 * Filters the registration request body to include tracking properties.
5522
	 *
5523
	 * @deprecated since Jetpack 9.7.0
5524
	 * @see Automattic\Jetpack\Connection\Utils::filter_register_request_body()
5525
	 *
5526
	 * @param array $properties
5527
	 * @return array amended properties.
5528
	 */
5529
	public static function filter_register_request_body( $properties ) {
5530
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Utils::filter_register_request_body' );
5531
		return Connection_Utils::filter_register_request_body( $properties );
5532
	}
5533
5534
	/**
5535
	 * Filters the token request body to include tracking properties.
5536
	 *
5537
	 * @param array $properties
5538
	 * @return array amended properties.
5539
	 */
5540 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5541
		$tracking        = new Tracking();
5542
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5543
5544
		return array_merge(
5545
			$properties,
5546
			array(
5547
				'_ui' => $tracks_identity['_ui'],
5548
				'_ut' => $tracks_identity['_ut'],
5549
			)
5550
		);
5551
	}
5552
5553
	/**
5554
	 * If the db version is showing something other that what we've got now, bump it to current.
5555
	 *
5556
	 * @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...
5557
	 */
5558
	public static function maybe_set_version_option() {
5559
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5560
		if ( JETPACK__VERSION != $version ) {
5561
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5562
5563
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5564
				/** This action is documented in class.jetpack.php */
5565
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5566
			}
5567
5568
			return true;
5569
		}
5570
		return false;
5571
	}
5572
5573
	/* Client Server API */
5574
5575
	/**
5576
	 * Loads the Jetpack XML-RPC client.
5577
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5578
	 *
5579
	 * @deprecated since 7.7.0
5580
	 */
5581
	public static function load_xml_rpc_client() {
5582
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5583
	}
5584
5585
	/**
5586
	 * Resets the saved authentication state in between testing requests.
5587
	 *
5588
	 * @deprecated since 8.9.0
5589
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5590
	 */
5591
	public function reset_saved_auth_state() {
5592
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5593
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5594
	}
5595
5596
	/**
5597
	 * Verifies the signature of the current request.
5598
	 *
5599
	 * @deprecated since 7.7.0
5600
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5601
	 *
5602
	 * @return false|array
5603
	 */
5604
	public function verify_xml_rpc_signature() {
5605
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5606
		return self::connection()->verify_xml_rpc_signature();
5607
	}
5608
5609
	/**
5610
	 * Verifies the signature of the current request.
5611
	 *
5612
	 * This function has side effects and should not be used. Instead,
5613
	 * use the memoized version `->verify_xml_rpc_signature()`.
5614
	 *
5615
	 * @deprecated since 7.7.0
5616
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5617
	 * @internal
5618
	 */
5619
	private function internal_verify_xml_rpc_signature() {
5620
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5621
	}
5622
5623
	/**
5624
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5625
	 *
5626
	 * @deprecated since 7.7.0
5627
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5628
	 *
5629
	 * @param \WP_User|mixed $user     User object if authenticated.
5630
	 * @param string         $username Username.
5631
	 * @param string         $password Password string.
5632
	 * @return \WP_User|mixed Authenticated user or error.
5633
	 */
5634 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5635
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5636
5637
		if ( ! $this->connection_manager ) {
5638
			$this->connection_manager = new Connection_Manager();
5639
		}
5640
5641
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5642
	}
5643
5644
	/**
5645
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5646
	 * Uses the existing XMLRPC request signing implementation.
5647
	 *
5648
	 * @deprecated since 8.9.0
5649
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5650
	 */
5651
	function wp_rest_authenticate( $user ) {
5652
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5653
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5654
	}
5655
5656
	/**
5657
	 * Report authentication status to the WP REST API.
5658
	 *
5659
	 * @deprecated since 8.9.0
5660
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5661
	 *
5662
	 * @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...
5663
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5664
	 */
5665
	public function wp_rest_authentication_errors( $value ) {
5666
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5667
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5668
	}
5669
5670
	/**
5671
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5672
	 * Capture it here so we can verify the signature later.
5673
	 *
5674
	 * @deprecated since 7.7.0
5675
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5676
	 *
5677
	 * @param array $methods XMLRPC methods.
5678
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5679
	 */
5680 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5681
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5682
5683
		if ( ! $this->connection_manager ) {
5684
			$this->connection_manager = new Connection_Manager();
5685
		}
5686
5687
		return $this->connection_manager->xmlrpc_methods( $methods );
5688
	}
5689
5690
	/**
5691
	 * Register additional public XMLRPC methods.
5692
	 *
5693
	 * @deprecated since 7.7.0
5694
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5695
	 *
5696
	 * @param array $methods Public XMLRPC methods.
5697
	 * @return array Public XMLRPC methods, with the getOptions one.
5698
	 */
5699 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5700
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5701
5702
		if ( ! $this->connection_manager ) {
5703
			$this->connection_manager = new Connection_Manager();
5704
		}
5705
5706
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5707
	}
5708
5709
	/**
5710
	 * Handles a getOptions XMLRPC method call.
5711
	 *
5712
	 * @deprecated since 7.7.0
5713
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5714
	 *
5715
	 * @param array $args method call arguments.
5716
	 * @return array an amended XMLRPC server options array.
5717
	 */
5718 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5719
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5720
5721
		if ( ! $this->connection_manager ) {
5722
			$this->connection_manager = new Connection_Manager();
5723
		}
5724
5725
		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...
5726
	}
5727
5728
	/**
5729
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5730
	 *
5731
	 * @deprecated since 7.7.0
5732
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5733
	 *
5734
	 * @param array $options Standard Core options.
5735
	 * @return array Amended options.
5736
	 */
5737 View Code Duplication
	public function xmlrpc_options( $options ) {
5738
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5739
5740
		if ( ! $this->connection_manager ) {
5741
			$this->connection_manager = new Connection_Manager();
5742
		}
5743
5744
		return $this->connection_manager->xmlrpc_options( $options );
5745
	}
5746
5747
	/**
5748
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5749
	 * SET: state( $key, $value );
5750
	 * GET: $value = state( $key );
5751
	 *
5752
	 * @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...
5753
	 * @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...
5754
	 * @param bool   $restate private
5755
	 */
5756
	public static function state( $key = null, $value = null, $restate = false ) {
5757
		static $state = array();
5758
		static $path, $domain;
5759
		if ( ! isset( $path ) ) {
5760
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5761
			$admin_url = self::admin_url();
5762
			$bits      = wp_parse_url( $admin_url );
5763
5764
			if ( is_array( $bits ) ) {
5765
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5766
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5767
			} else {
5768
				$path = $domain = null;
5769
			}
5770
		}
5771
5772
		// Extract state from cookies and delete cookies
5773
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5774
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5775
			unset( $_COOKIE['jetpackState'] );
5776
			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...
5777
				if ( strlen( $v ) ) {
5778
					$state[ $k ] = $v;
5779
				}
5780
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5781
			}
5782
		}
5783
5784
		if ( $restate ) {
5785
			foreach ( $state as $k => $v ) {
5786
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5787
			}
5788
			return;
5789
		}
5790
5791
		// Get a state variable.
5792
		if ( isset( $key ) && ! isset( $value ) ) {
5793
			if ( array_key_exists( $key, $state ) ) {
5794
				return $state[ $key ];
5795
			}
5796
			return null;
5797
		}
5798
5799
		// Set a state variable.
5800
		if ( isset( $key ) && isset( $value ) ) {
5801
			if ( is_array( $value ) && isset( $value[0] ) ) {
5802
				$value = $value[0];
5803
			}
5804
			$state[ $key ] = $value;
5805
			if ( ! headers_sent() ) {
5806
				if ( self::should_set_cookie( $key ) ) {
5807
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5808
				}
5809
			}
5810
		}
5811
	}
5812
5813
	public static function restate() {
5814
		self::state( null, null, true );
5815
	}
5816
5817
	/**
5818
	 * Determines whether the jetpackState[$key] value should be added to the
5819
	 * cookie.
5820
	 *
5821
	 * @param string $key The state key.
5822
	 *
5823
	 * @return boolean Whether the value should be added to the cookie.
5824
	 */
5825
	public static function should_set_cookie( $key ) {
5826
		global $current_screen;
5827
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5828
5829
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5830
			return false;
5831
		}
5832
5833
		return true;
5834
	}
5835
5836
	public static function check_privacy( $file ) {
5837
		static $is_site_publicly_accessible = null;
5838
5839
		if ( is_null( $is_site_publicly_accessible ) ) {
5840
			$is_site_publicly_accessible = false;
5841
5842
			$rpc = new Jetpack_IXR_Client();
5843
5844
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5845
			if ( $success ) {
5846
				$response = $rpc->getResponse();
5847
				if ( $response ) {
5848
					$is_site_publicly_accessible = true;
5849
				}
5850
			}
5851
5852
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5853
		}
5854
5855
		if ( $is_site_publicly_accessible ) {
5856
			return;
5857
		}
5858
5859
		$module_slug = self::get_module_slug( $file );
5860
5861
		$privacy_checks = self::state( 'privacy_checks' );
5862
		if ( ! $privacy_checks ) {
5863
			$privacy_checks = $module_slug;
5864
		} else {
5865
			$privacy_checks .= ",$module_slug";
5866
		}
5867
5868
		self::state( 'privacy_checks', $privacy_checks );
5869
	}
5870
5871
	/**
5872
	 * Helper method for multicall XMLRPC.
5873
	 *
5874
	 * @deprecated since 8.9.0
5875
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5876
	 *
5877
	 * @param ...$args Args for the async_call.
5878
	 */
5879
	public static function xmlrpc_async_call( ...$args ) {
5880
5881
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5882
5883
		global $blog_id;
5884
		static $clients = array();
5885
5886
		$client_blog_id = is_multisite() ? $blog_id : 0;
5887
5888
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5889
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5890
			if ( function_exists( 'ignore_user_abort' ) ) {
5891
				ignore_user_abort( true );
5892
			}
5893
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5894
		}
5895
5896
		if ( ! empty( $args[0] ) ) {
5897
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5898
		} elseif ( is_multisite() ) {
5899
			foreach ( $clients as $client_blog_id => $client ) {
5900
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5901
					continue;
5902
				}
5903
5904
				$switch_success = switch_to_blog( $client_blog_id, true );
5905
				if ( ! $switch_success ) {
5906
					continue;
5907
				}
5908
5909
				flush();
5910
				$client->query();
5911
5912
				restore_current_blog();
5913
			}
5914
		} else {
5915
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5916
				flush();
5917
				$clients[0]->query();
5918
			}
5919
		}
5920
	}
5921
5922
	/**
5923
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5924
	 *
5925
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5926
	 *
5927
	 * @param string $url WordPress.com static resource URL.
5928
	 */
5929
	public static function staticize_subdomain( $url ) {
5930
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5931
		return Assets::staticize_subdomain( $url );
5932
	}
5933
5934
	/* JSON API Authorization */
5935
5936
	/**
5937
	 * Handles the login action for Authorizing the JSON API
5938
	 */
5939
	function login_form_json_api_authorization() {
5940
		$this->verify_json_api_authorization_request();
5941
5942
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5943
5944
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5945
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5946
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5947
	}
5948
5949
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5950
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5951
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5952
			return $url;
5953
		}
5954
5955
		$parsed_url = wp_parse_url( $url );
5956
		$url        = strtok( $url, '?' );
5957
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5958
		if ( ! empty( $parsed_url['query'] ) ) {
5959
			$url .= "&{$parsed_url['query']}";
5960
		}
5961
5962
		return $url;
5963
	}
5964
5965
	// Make sure the POSTed request is handled by the same action
5966
	function preserve_action_in_login_form_for_json_api_authorization() {
5967
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5968
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5969
	}
5970
5971
	// If someone logs in to approve API access, store the Access Code in usermeta
5972
	function store_json_api_authorization_token( $user_login, $user ) {
5973
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5974
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5975
		$token = wp_generate_password( 32, false );
5976
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5977
	}
5978
5979
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5980
	function allow_wpcom_public_api_domain( $domains ) {
5981
		$domains[] = 'public-api.wordpress.com';
5982
		return $domains;
5983
	}
5984
5985
	static function is_redirect_encoded( $redirect_url ) {
5986
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5987
	}
5988
5989
	// Add all wordpress.com environments to the safe redirect allowed list.
5990
	function allow_wpcom_environments( $domains ) {
5991
		$domains[] = 'wordpress.com';
5992
		$domains[] = 'wpcalypso.wordpress.com';
5993
		$domains[] = 'horizon.wordpress.com';
5994
		$domains[] = 'calypso.localhost';
5995
		return $domains;
5996
	}
5997
5998
	// Add the Access Code details to the public-api.wordpress.com redirect
5999
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6000
		return add_query_arg(
6001
			urlencode_deep(
6002
				array(
6003
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6004
					'jetpack-user-id' => (int) $user->ID,
6005
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6006
				)
6007
			),
6008
			$redirect_to
6009
		);
6010
	}
6011
6012
	/**
6013
	 * Verifies the request by checking the signature
6014
	 *
6015
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6016
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6017
	 *
6018
	 * @param null|array $environment
6019
	 */
6020
	function verify_json_api_authorization_request( $environment = null ) {
6021
		$environment = is_null( $environment )
6022
			? $_REQUEST
6023
			: $environment;
6024
6025
		list( $env_token,, $env_user_id ) = explode( ':', $environment['token'] );
6026
		$token                            = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
6027
		if ( ! $token || empty( $token->secret ) ) {
6028
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6029
		}
6030
6031
		$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' );
6032
6033
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6034
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6035
			/**
6036
			 * Jetpack authorisation request Error.
6037
			 *
6038
			 * @since 7.5.0
6039
			 */
6040
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6041
			$die_error = sprintf(
6042
				/* translators: %s is a URL */
6043
				__( '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' ),
6044
				Redirect::get_url( 'jetpack-support-double-encoding' )
6045
			);
6046
		}
6047
6048
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6049
6050
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6051
			$signature = $jetpack_signature->sign_request(
6052
				$environment['token'],
6053
				$environment['timestamp'],
6054
				$environment['nonce'],
6055
				'',
6056
				'GET',
6057
				$environment['jetpack_json_api_original_query'],
6058
				null,
6059
				true
6060
			);
6061
		} else {
6062
			$signature = $jetpack_signature->sign_current_request(
6063
				array(
6064
					'body'   => null,
6065
					'method' => 'GET',
6066
				)
6067
			);
6068
		}
6069
6070
		if ( ! $signature ) {
6071
			wp_die( $die_error );
6072
		} elseif ( is_wp_error( $signature ) ) {
6073
			wp_die( $die_error );
6074
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6075
			if ( is_ssl() ) {
6076
				// 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
6077
				$signature = $jetpack_signature->sign_current_request(
6078
					array(
6079
						'scheme' => 'http',
6080
						'body'   => null,
6081
						'method' => 'GET',
6082
					)
6083
				);
6084
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6085
					wp_die( $die_error );
6086
				}
6087
			} else {
6088
				wp_die( $die_error );
6089
			}
6090
		}
6091
6092
		$timestamp = (int) $environment['timestamp'];
6093
		$nonce     = stripslashes( (string) $environment['nonce'] );
6094
6095
		if ( ! $this->connection_manager ) {
6096
			$this->connection_manager = new Connection_Manager();
6097
		}
6098
6099
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
6100
			// De-nonce the nonce, at least for 5 minutes.
6101
			// 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)
6102
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6103
			if ( $old_nonce_time < time() - 300 ) {
6104
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6105
			}
6106
		}
6107
6108
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6109
		$data_filters = array(
6110
			'state'        => 'opaque',
6111
			'client_id'    => 'int',
6112
			'client_title' => 'string',
6113
			'client_image' => 'url',
6114
		);
6115
6116
		foreach ( $data_filters as $key => $sanitation ) {
6117
			if ( ! isset( $data->$key ) ) {
6118
				wp_die( $die_error );
6119
			}
6120
6121
			switch ( $sanitation ) {
6122
				case 'int':
6123
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6124
					break;
6125
				case 'opaque':
6126
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6127
					break;
6128
				case 'string':
6129
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6130
					break;
6131
				case 'url':
6132
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6133
					break;
6134
			}
6135
		}
6136
6137
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6138
			wp_die( $die_error );
6139
		}
6140
	}
6141
6142
	function login_message_json_api_authorization( $message ) {
6143
		return '<p class="message">' . sprintf(
6144
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6145
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6146
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6147
	}
6148
6149
	/**
6150
	 * Get $content_width, but with a <s>twist</s> filter.
6151
	 */
6152
	public static function get_content_width() {
6153
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6154
			? $GLOBALS['content_width']
6155
			: false;
6156
		/**
6157
		 * Filter the Content Width value.
6158
		 *
6159
		 * @since 2.2.3
6160
		 *
6161
		 * @param string $content_width Content Width value.
6162
		 */
6163
		return apply_filters( 'jetpack_content_width', $content_width );
6164
	}
6165
6166
	/**
6167
	 * Pings the WordPress.com Mirror Site for the specified options.
6168
	 *
6169
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6170
	 *
6171
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6172
	 */
6173
	public function get_cloud_site_options( $option_names ) {
6174
		$option_names = array_filter( (array) $option_names, 'is_string' );
6175
6176
		$xml = new Jetpack_IXR_Client();
6177
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6178
		if ( $xml->isError() ) {
6179
			return array(
6180
				'error_code' => $xml->getErrorCode(),
6181
				'error_msg'  => $xml->getErrorMessage(),
6182
			);
6183
		}
6184
		$cloud_site_options = $xml->getResponse();
6185
6186
		return $cloud_site_options;
6187
	}
6188
6189
	/**
6190
	 * Checks if the site is currently in an identity crisis.
6191
	 *
6192
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6193
	 */
6194
	public static function check_identity_crisis() {
6195
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() || ! Identity_Crisis::validate_sync_error_idc_option() ) {
6196
			return false;
6197
		}
6198
6199
		return Jetpack_Options::get_option( 'sync_error_idc' );
6200
	}
6201
6202
	/**
6203
	 * Checks whether the home and siteurl specifically are allowed.
6204
	 * Written so that we don't have re-check $key and $value params every time
6205
	 * we want to check if this site is allowed, for example in footer.php
6206
	 *
6207
	 * @since  3.8.0
6208
	 * @return bool True = already allowed False = not on the allowed list.
6209
	 */
6210
	public static function is_staging_site() {
6211
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6212
		return ( new Status() )->is_staging_site();
6213
	}
6214
6215
	/**
6216
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6217
	 *
6218
	 * @since 4.4.0
6219
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6220
	 *
6221
	 * @return bool
6222
	 */
6223
	public static function validate_sync_error_idc_option() {
6224
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::validate_sync_error_idc_option' );
6225
		return Identity_Crisis::validate_sync_error_idc_option();
6226
	}
6227
6228
	/**
6229
	 * Normalizes a url by doing three things:
6230
	 *  - Strips protocol
6231
	 *  - Strips www
6232
	 *  - Adds a trailing slash
6233
	 *
6234
	 * @since 4.4.0
6235
	 * @param string $url
6236
	 * @return WP_Error|string
6237
	 */
6238 View Code Duplication
	public static function normalize_url_protocol_agnostic( $url ) {
6239
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6240
		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...
6241
			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...
6242
		}
6243
6244
		// Strip www and protocols
6245
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6246
		return $url;
6247
	}
6248
6249
	/**
6250
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6251
	 *
6252
	 * @since 4.4.0
6253
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6254
	 *
6255
	 * @param array $response
6256
	 * @return array Array of the local urls, wpcom urls, and error code
6257
	 */
6258
	public static function get_sync_error_idc_option( $response = array() ) {
6259
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::get_sync_error_idc_option' );
6260
		return Identity_Crisis::get_sync_error_idc_option( $response );
6261
	}
6262
6263
	/**
6264
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6265
	 * If set to true, the site will be put into staging mode.
6266
	 *
6267
	 * @since 4.3.2
6268
	 * @return bool
6269
	 */
6270
	public static function sync_idc_optin() {
6271
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::sync_idc_optin' );
6272
		return Identity_Crisis::sync_idc_optin();
6273
	}
6274
6275
	/**
6276
	 * Maybe Use a .min.css stylesheet, maybe not.
6277
	 *
6278
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6279
	 */
6280
	public static function maybe_min_asset( $url, $path, $plugin ) {
6281
		// Short out on things trying to find actual paths.
6282
		if ( ! $path || empty( $plugin ) ) {
6283
			return $url;
6284
		}
6285
6286
		$path = ltrim( $path, '/' );
6287
6288
		// Strip out the abspath.
6289
		$base = dirname( plugin_basename( $plugin ) );
6290
6291
		// Short out on non-Jetpack assets.
6292
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6293
			return $url;
6294
		}
6295
6296
		// File name parsing.
6297
		$file              = "{$base}/{$path}";
6298
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6299
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6300
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6301
		$extension         = array_shift( $file_name_parts_r );
6302
6303
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6304
			// Already pointing at the minified version.
6305
			if ( 'min' === $file_name_parts_r[0] ) {
6306
				return $url;
6307
			}
6308
6309
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6310
			if ( file_exists( $min_full_path ) ) {
6311
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6312
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6313
				if ( 'css' === $extension ) {
6314
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6315
					self::$min_assets[ $key ] = $path;
6316
				}
6317
			}
6318
		}
6319
6320
		return $url;
6321
	}
6322
6323
	/**
6324
	 * If the asset is minified, let's flag .min as the suffix.
6325
	 *
6326
	 * Attached to `style_loader_src` filter.
6327
	 *
6328
	 * @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...
6329
	 * @param string $handle The registered handle of the script in question.
6330
	 * @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...
6331
	 */
6332
	public static function set_suffix_on_min( $src, $handle ) {
6333
		if ( false === strpos( $src, '.min.css' ) ) {
6334
			return $src;
6335
		}
6336
6337
		if ( ! empty( self::$min_assets ) ) {
6338
			foreach ( self::$min_assets as $file => $path ) {
6339
				if ( false !== strpos( $src, $file ) ) {
6340
					wp_style_add_data( $handle, 'suffix', '.min' );
6341
					return $src;
6342
				}
6343
			}
6344
		}
6345
6346
		return $src;
6347
	}
6348
6349
	/**
6350
	 * Maybe inlines a stylesheet.
6351
	 *
6352
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6353
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6354
	 *
6355
	 * Attached to `style_loader_tag` filter.
6356
	 *
6357
	 * @param string $tag The tag that would link to the external asset.
6358
	 * @param string $handle The registered handle of the script in question.
6359
	 *
6360
	 * @return string
6361
	 */
6362
	public static function maybe_inline_style( $tag, $handle ) {
6363
		global $wp_styles;
6364
		$item = $wp_styles->registered[ $handle ];
6365
6366
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6367
			return $tag;
6368
		}
6369
6370
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6371
			$href = $matches[1];
6372
			// Strip off query string
6373
			if ( $pos = strpos( $href, '?' ) ) {
6374
				$href = substr( $href, 0, $pos );
6375
			}
6376
			// Strip off fragment
6377
			if ( $pos = strpos( $href, '#' ) ) {
6378
				$href = substr( $href, 0, $pos );
6379
			}
6380
		} else {
6381
			return $tag;
6382
		}
6383
6384
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6385
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6386
			return $tag;
6387
		}
6388
6389
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6390
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6391
			// And this isn't the pass that actually deals with the RTL version...
6392
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6393
				// Short out, as the RTL version will deal with it in a moment.
6394
				return $tag;
6395
			}
6396
		}
6397
6398
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6399
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6400
		if ( $css ) {
6401
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6402
			if ( empty( $item->extra['after'] ) ) {
6403
				wp_add_inline_style( $handle, $css );
6404
			} else {
6405
				array_unshift( $item->extra['after'], $css );
6406
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6407
			}
6408
		}
6409
6410
		return $tag;
6411
	}
6412
6413
	/**
6414
	 * Loads a view file from the views
6415
	 *
6416
	 * Data passed in with the $data parameter will be available in the
6417
	 * template file as $data['value']
6418
	 *
6419
	 * @param string $template - Template file to load
6420
	 * @param array  $data - Any data to pass along to the template
6421
	 * @return boolean - If template file was found
6422
	 **/
6423
	public function load_view( $template, $data = array() ) {
6424
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6425
6426
		if ( file_exists( $views_dir . $template ) ) {
6427
			require_once $views_dir . $template;
6428
			return true;
6429
		}
6430
6431
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6432
		return false;
6433
	}
6434
6435
	/**
6436
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6437
	 */
6438
	public function deprecated_hooks() {
6439
		$filter_deprecated_list = array(
6440
			'jetpack_bail_on_shortcode'                    => array(
6441
				'replacement' => 'jetpack_shortcodes_to_include',
6442
				'version'     => 'jetpack-3.1.0',
6443
			),
6444
			'wpl_sharing_2014_1'                           => array(
6445
				'replacement' => null,
6446
				'version'     => 'jetpack-3.6.0',
6447
			),
6448
			'jetpack-tools-to-include'                     => array(
6449
				'replacement' => 'jetpack_tools_to_include',
6450
				'version'     => 'jetpack-3.9.0',
6451
			),
6452
			'jetpack_identity_crisis_options_to_check'     => array(
6453
				'replacement' => null,
6454
				'version'     => 'jetpack-4.0.0',
6455
			),
6456
			'update_option_jetpack_single_user_site'       => array(
6457
				'replacement' => null,
6458
				'version'     => 'jetpack-4.3.0',
6459
			),
6460
			'audio_player_default_colors'                  => array(
6461
				'replacement' => null,
6462
				'version'     => 'jetpack-4.3.0',
6463
			),
6464
			'add_option_jetpack_featured_images_enabled'   => array(
6465
				'replacement' => null,
6466
				'version'     => 'jetpack-4.3.0',
6467
			),
6468
			'add_option_jetpack_update_details'            => array(
6469
				'replacement' => null,
6470
				'version'     => 'jetpack-4.3.0',
6471
			),
6472
			'add_option_jetpack_updates'                   => array(
6473
				'replacement' => null,
6474
				'version'     => 'jetpack-4.3.0',
6475
			),
6476
			'add_option_jetpack_network_name'              => array(
6477
				'replacement' => null,
6478
				'version'     => 'jetpack-4.3.0',
6479
			),
6480
			'add_option_jetpack_network_allow_new_registrations' => array(
6481
				'replacement' => null,
6482
				'version'     => 'jetpack-4.3.0',
6483
			),
6484
			'add_option_jetpack_network_add_new_users'     => array(
6485
				'replacement' => null,
6486
				'version'     => 'jetpack-4.3.0',
6487
			),
6488
			'add_option_jetpack_network_site_upload_space' => array(
6489
				'replacement' => null,
6490
				'version'     => 'jetpack-4.3.0',
6491
			),
6492
			'add_option_jetpack_network_upload_file_types' => array(
6493
				'replacement' => null,
6494
				'version'     => 'jetpack-4.3.0',
6495
			),
6496
			'add_option_jetpack_network_enable_administration_menus' => array(
6497
				'replacement' => null,
6498
				'version'     => 'jetpack-4.3.0',
6499
			),
6500
			'add_option_jetpack_is_multi_site'             => array(
6501
				'replacement' => null,
6502
				'version'     => 'jetpack-4.3.0',
6503
			),
6504
			'add_option_jetpack_is_main_network'           => array(
6505
				'replacement' => null,
6506
				'version'     => 'jetpack-4.3.0',
6507
			),
6508
			'add_option_jetpack_main_network_site'         => array(
6509
				'replacement' => null,
6510
				'version'     => 'jetpack-4.3.0',
6511
			),
6512
			'jetpack_sync_all_registered_options'          => array(
6513
				'replacement' => null,
6514
				'version'     => 'jetpack-4.3.0',
6515
			),
6516
			'jetpack_has_identity_crisis'                  => array(
6517
				'replacement' => 'jetpack_sync_error_idc_validation',
6518
				'version'     => 'jetpack-4.4.0',
6519
			),
6520
			'jetpack_is_post_mailable'                     => array(
6521
				'replacement' => null,
6522
				'version'     => 'jetpack-4.4.0',
6523
			),
6524
			'jetpack_seo_site_host'                        => array(
6525
				'replacement' => null,
6526
				'version'     => 'jetpack-5.1.0',
6527
			),
6528
			'jetpack_installed_plugin'                     => array(
6529
				'replacement' => 'jetpack_plugin_installed',
6530
				'version'     => 'jetpack-6.0.0',
6531
			),
6532
			'jetpack_holiday_snow_option_name'             => array(
6533
				'replacement' => null,
6534
				'version'     => 'jetpack-6.0.0',
6535
			),
6536
			'jetpack_holiday_chance_of_snow'               => array(
6537
				'replacement' => null,
6538
				'version'     => 'jetpack-6.0.0',
6539
			),
6540
			'jetpack_holiday_snow_js_url'                  => array(
6541
				'replacement' => null,
6542
				'version'     => 'jetpack-6.0.0',
6543
			),
6544
			'jetpack_is_holiday_snow_season'               => array(
6545
				'replacement' => null,
6546
				'version'     => 'jetpack-6.0.0',
6547
			),
6548
			'jetpack_holiday_snow_option_updated'          => array(
6549
				'replacement' => null,
6550
				'version'     => 'jetpack-6.0.0',
6551
			),
6552
			'jetpack_holiday_snowing'                      => array(
6553
				'replacement' => null,
6554
				'version'     => 'jetpack-6.0.0',
6555
			),
6556
			'jetpack_sso_auth_cookie_expirtation'          => array(
6557
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6558
				'version'     => 'jetpack-6.1.0',
6559
			),
6560
			'jetpack_cache_plans'                          => array(
6561
				'replacement' => null,
6562
				'version'     => 'jetpack-6.1.0',
6563
			),
6564
6565
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6566
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6567
				'version'     => 'jetpack-6.5.0',
6568
			),
6569
			'jetpack_enable_site_verification'             => array(
6570
				'replacement' => null,
6571
				'version'     => 'jetpack-6.5.0',
6572
			),
6573
			'can_display_jetpack_manage_notice'            => array(
6574
				'replacement' => null,
6575
				'version'     => 'jetpack-7.3.0',
6576
			),
6577
			'atd_http_post_timeout'                        => array(
6578
				'replacement' => null,
6579
				'version'     => 'jetpack-7.3.0',
6580
			),
6581
			'atd_service_domain'                           => array(
6582
				'replacement' => null,
6583
				'version'     => 'jetpack-7.3.0',
6584
			),
6585
			'atd_load_scripts'                             => array(
6586
				'replacement' => null,
6587
				'version'     => 'jetpack-7.3.0',
6588
			),
6589
			'jetpack_widget_authors_exclude'               => array(
6590
				'replacement' => 'jetpack_widget_authors_params',
6591
				'version'     => 'jetpack-7.7.0',
6592
			),
6593
			// Removed in Jetpack 7.9.0
6594
			'jetpack_pwa_manifest'                         => array(
6595
				'replacement' => null,
6596
				'version'     => 'jetpack-7.9.0',
6597
			),
6598
			'jetpack_pwa_background_color'                 => array(
6599
				'replacement' => null,
6600
				'version'     => 'jetpack-7.9.0',
6601
			),
6602
			'jetpack_check_mobile'                         => array(
6603
				'replacement' => null,
6604
				'version'     => 'jetpack-8.3.0',
6605
			),
6606
			'jetpack_mobile_stylesheet'                    => array(
6607
				'replacement' => null,
6608
				'version'     => 'jetpack-8.3.0',
6609
			),
6610
			'jetpack_mobile_template'                      => array(
6611
				'replacement' => null,
6612
				'version'     => 'jetpack-8.3.0',
6613
			),
6614
			'jetpack_mobile_theme_menu'                    => array(
6615
				'replacement' => null,
6616
				'version'     => 'jetpack-8.3.0',
6617
			),
6618
			'minileven_show_featured_images'               => array(
6619
				'replacement' => null,
6620
				'version'     => 'jetpack-8.3.0',
6621
			),
6622
			'minileven_attachment_size'                    => array(
6623
				'replacement' => null,
6624
				'version'     => 'jetpack-8.3.0',
6625
			),
6626
			'instagram_cache_oembed_api_response_body'     => array(
6627
				'replacement' => null,
6628
				'version'     => 'jetpack-9.1.0',
6629
			),
6630
			'jetpack_can_make_outbound_https'              => array(
6631
				'replacement' => null,
6632
				'version'     => 'jetpack-9.1.0',
6633
			),
6634
		);
6635
6636
		foreach ( $filter_deprecated_list as $tag => $args ) {
6637
			if ( has_filter( $tag ) ) {
6638
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6639
			}
6640
		}
6641
6642
		$action_deprecated_list = array(
6643
			'jetpack_updated_theme'        => array(
6644
				'replacement' => 'jetpack_updated_themes',
6645
				'version'     => 'jetpack-6.2.0',
6646
			),
6647
			'atd_http_post_error'          => array(
6648
				'replacement' => null,
6649
				'version'     => 'jetpack-7.3.0',
6650
			),
6651
			'mobile_reject_mobile'         => array(
6652
				'replacement' => null,
6653
				'version'     => 'jetpack-8.3.0',
6654
			),
6655
			'mobile_force_mobile'          => array(
6656
				'replacement' => null,
6657
				'version'     => 'jetpack-8.3.0',
6658
			),
6659
			'mobile_app_promo_download'    => array(
6660
				'replacement' => null,
6661
				'version'     => 'jetpack-8.3.0',
6662
			),
6663
			'mobile_setup'                 => array(
6664
				'replacement' => null,
6665
				'version'     => 'jetpack-8.3.0',
6666
			),
6667
			'jetpack_mobile_footer_before' => array(
6668
				'replacement' => null,
6669
				'version'     => 'jetpack-8.3.0',
6670
			),
6671
			'wp_mobile_theme_footer'       => array(
6672
				'replacement' => null,
6673
				'version'     => 'jetpack-8.3.0',
6674
			),
6675
			'minileven_credits'            => array(
6676
				'replacement' => null,
6677
				'version'     => 'jetpack-8.3.0',
6678
			),
6679
			'jetpack_mobile_header_before' => array(
6680
				'replacement' => null,
6681
				'version'     => 'jetpack-8.3.0',
6682
			),
6683
			'jetpack_mobile_header_after'  => array(
6684
				'replacement' => null,
6685
				'version'     => 'jetpack-8.3.0',
6686
			),
6687
		);
6688
6689
		foreach ( $action_deprecated_list as $tag => $args ) {
6690
			if ( has_action( $tag ) ) {
6691
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6692
			}
6693
		}
6694
	}
6695
6696
	/**
6697
	 * Converts any url in a stylesheet, to the correct absolute url.
6698
	 *
6699
	 * Considerations:
6700
	 *  - Normal, relative URLs     `feh.png`
6701
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6702
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6703
	 *  - Absolute URLs             `http://domain.com/feh.png`
6704
	 *  - Domain root relative URLs `/feh.png`
6705
	 *
6706
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6707
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6708
	 *
6709
	 * @return mixed|string
6710
	 */
6711
	public static function absolutize_css_urls( $css, $css_file_url ) {
6712
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6713
		$css_dir = dirname( $css_file_url );
6714
		$p       = wp_parse_url( $css_dir );
6715
		$domain  = sprintf(
6716
			'%1$s//%2$s%3$s%4$s',
6717
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6718
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6719
			$p['host'],
6720
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6721
		);
6722
6723
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6724
			$find = $replace = array();
6725
			foreach ( $matches as $match ) {
6726
				$url = trim( $match['path'], "'\" \t" );
6727
6728
				// If this is a data url, we don't want to mess with it.
6729
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6730
					continue;
6731
				}
6732
6733
				// If this is an absolute or protocol-agnostic url,
6734
				// we don't want to mess with it.
6735
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6736
					continue;
6737
				}
6738
6739
				switch ( substr( $url, 0, 1 ) ) {
6740
					case '/':
6741
						$absolute = $domain . $url;
6742
						break;
6743
					default:
6744
						$absolute = $css_dir . '/' . $url;
6745
				}
6746
6747
				$find[]    = $match[0];
6748
				$replace[] = sprintf( 'url("%s")', $absolute );
6749
			}
6750
			$css = str_replace( $find, $replace, $css );
6751
		}
6752
6753
		return $css;
6754
	}
6755
6756
	/**
6757
	 * This methods removes all of the registered css files on the front end
6758
	 * from Jetpack in favor of using a single file. In effect "imploding"
6759
	 * all the files into one file.
6760
	 *
6761
	 * Pros:
6762
	 * - Uses only ONE css asset connection instead of 15
6763
	 * - Saves a minimum of 56k
6764
	 * - Reduces server load
6765
	 * - Reduces time to first painted byte
6766
	 *
6767
	 * Cons:
6768
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6769
	 *      should not cause any issues with themes.
6770
	 * - Plugins/themes dequeuing styles no longer do anything. See
6771
	 *      jetpack_implode_frontend_css filter for a workaround
6772
	 *
6773
	 * For some situations developers may wish to disable css imploding and
6774
	 * instead operate in legacy mode where each file loads seperately and
6775
	 * can be edited individually or dequeued. This can be accomplished with
6776
	 * the following line:
6777
	 *
6778
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6779
	 *
6780
	 * @since 3.2
6781
	 **/
6782
	public function implode_frontend_css( $travis_test = false ) {
6783
		$do_implode = true;
6784
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6785
			$do_implode = false;
6786
		}
6787
6788
		// Do not implode CSS when the page loads via the AMP plugin.
6789
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6790
			$do_implode = false;
6791
		}
6792
6793
		/**
6794
		 * Allow CSS to be concatenated into a single jetpack.css file.
6795
		 *
6796
		 * @since 3.2.0
6797
		 *
6798
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6799
		 */
6800
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6801
6802
		// Do not use the imploded file when default behavior was altered through the filter
6803
		if ( ! $do_implode ) {
6804
			return;
6805
		}
6806
6807
		// We do not want to use the imploded file in dev mode, or if not connected
6808
		if ( ( new Status() )->is_offline_mode() || ! self::is_connection_ready() ) {
6809
			if ( ! $travis_test ) {
6810
				return;
6811
			}
6812
		}
6813
6814
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6815
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6816
			return;
6817
		}
6818
6819
		/*
6820
		 * Now we assume Jetpack is connected and able to serve the single
6821
		 * file.
6822
		 *
6823
		 * In the future there will be a check here to serve the file locally
6824
		 * or potentially from the Jetpack CDN
6825
		 *
6826
		 * For now:
6827
		 * - Enqueue a single imploded css file
6828
		 * - Zero out the style_loader_tag for the bundled ones
6829
		 * - Be happy, drink scotch
6830
		 */
6831
6832
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6833
6834
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6835
6836
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6837
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6838
	}
6839
6840
	function concat_remove_style_loader_tag( $tag, $handle ) {
6841
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6842
			$tag = '';
6843
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6844
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6845
			}
6846
		}
6847
6848
		return $tag;
6849
	}
6850
6851
	/**
6852
	 * @deprecated
6853
	 * @see Automattic\Jetpack\Assets\add_aync_script
6854
	 */
6855
	public function script_add_async( $tag, $handle, $src ) {
6856
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6857
	}
6858
6859
	/*
6860
	 * Check the heartbeat data
6861
	 *
6862
	 * Organizes the heartbeat data by severity.  For example, if the site
6863
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6864
	 *
6865
	 * Data will be added to "caution" array, if it either:
6866
	 *  - Out of date Jetpack version
6867
	 *  - Out of date WP version
6868
	 *  - Out of date PHP version
6869
	 *
6870
	 * $return array $filtered_data
6871
	 */
6872
	public static function jetpack_check_heartbeat_data() {
6873
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6874
6875
		$good    = array();
6876
		$caution = array();
6877
		$bad     = array();
6878
6879
		foreach ( $raw_data as $stat => $value ) {
6880
6881
			// Check jetpack version
6882
			if ( 'version' == $stat ) {
6883
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6884
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6885
					continue;
6886
				}
6887
			}
6888
6889
			// Check WP version
6890
			if ( 'wp-version' == $stat ) {
6891
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6892
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6893
					continue;
6894
				}
6895
			}
6896
6897
			// Check PHP version
6898
			if ( 'php-version' == $stat ) {
6899
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6900
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6901
					continue;
6902
				}
6903
			}
6904
6905
			// Check ID crisis
6906
			if ( 'identitycrisis' == $stat ) {
6907
				if ( 'yes' == $value ) {
6908
					$bad[ $stat ] = $value;
6909
					continue;
6910
				}
6911
			}
6912
6913
			// The rest are good :)
6914
			$good[ $stat ] = $value;
6915
		}
6916
6917
		$filtered_data = array(
6918
			'good'    => $good,
6919
			'caution' => $caution,
6920
			'bad'     => $bad,
6921
		);
6922
6923
		return $filtered_data;
6924
	}
6925
6926
	/*
6927
	 * This method is used to organize all options that can be reset
6928
	 * without disconnecting Jetpack.
6929
	 *
6930
	 * It is used in class.jetpack-cli.php to reset options
6931
	 *
6932
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6933
	 *
6934
	 * @return array of options to delete.
6935
	 */
6936
	public static function get_jetpack_options_for_reset() {
6937
		return Jetpack_Options::get_options_for_reset();
6938
	}
6939
6940
	/*
6941
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6942
	 * so we can bring them directly to their site in calypso.
6943
	 *
6944
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
6945
	 *
6946
	 * @param string | url
6947
	 * @return string | url without the guff
6948
	 */
6949
	public static function build_raw_urls( $url ) {
6950
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
6951
6952
		return ( new Status() )->get_site_suffix( $url );
6953
	}
6954
6955
	/**
6956
	 * Stores and prints out domains to prefetch for page speed optimization.
6957
	 *
6958
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
6959
	 *
6960
	 * @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...
6961
	 */
6962
	public static function dns_prefetch( $urls = null ) {
6963
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
6964
		if ( $urls ) {
6965
			Assets::add_resource_hint( $urls );
6966
		}
6967
	}
6968
6969
	public function wp_dashboard_setup() {
6970
		if ( self::is_connection_ready() ) {
6971
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6972
		}
6973
6974
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6975
			$jetpack_logo = new Jetpack_Logo();
6976
			$widget_title = sprintf(
6977
				/* translators: Placeholder is a Jetpack logo. */
6978
				__( 'Stats by %s', 'jetpack' ),
6979
				$jetpack_logo->get_jp_emblem( true )
6980
			);
6981
6982
			// Wrap title in span so Logo can be properly styled.
6983
			$widget_title = sprintf(
6984
				'<span>%s</span>',
6985
				$widget_title
6986
			);
6987
6988
			wp_add_dashboard_widget(
6989
				'jetpack_summary_widget',
6990
				$widget_title,
6991
				array( __CLASS__, 'dashboard_widget' )
6992
			);
6993
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6994
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6995
6996
			// If we're inactive and not in offline mode, sort our box to the top.
6997
			if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
6998
				global $wp_meta_boxes;
6999
7000
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7001
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7002
7003
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7004
			}
7005
		}
7006
	}
7007
7008
	/**
7009
	 * @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...
7010
	 * @return mixed
7011
	 */
7012
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7013
		if ( ! is_array( $sorted ) ) {
7014
			return $sorted;
7015
		}
7016
7017
		foreach ( $sorted as $box_context => $ids ) {
7018
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7019
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7020
				continue;
7021
			}
7022
7023
			$ids_array = explode( ',', $ids );
7024
			$key       = array_search( 'dashboard_stats', $ids_array );
7025
7026
			if ( false !== $key ) {
7027
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7028
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7029
				$sorted[ $box_context ] = implode( ',', $ids_array );
7030
				// We've found it, stop searching, and just return.
7031
				break;
7032
			}
7033
		}
7034
7035
		return $sorted;
7036
	}
7037
7038
	public static function dashboard_widget() {
7039
		/**
7040
		 * Fires when the dashboard is loaded.
7041
		 *
7042
		 * @since 3.4.0
7043
		 */
7044
		do_action( 'jetpack_dashboard_widget' );
7045
	}
7046
7047
	public static function dashboard_widget_footer() {
7048
		?>
7049
		<footer>
7050
7051
		<div class="protect">
7052
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7053
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7054
				<p class="blocked-count">
7055
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7056
				</p>
7057
				<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>
7058
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7059
				<a href="
7060
				<?php
7061
				echo esc_url(
7062
					wp_nonce_url(
7063
						self::admin_url(
7064
							array(
7065
								'action' => 'activate',
7066
								'module' => 'protect',
7067
							)
7068
						),
7069
						'jetpack_activate-protect'
7070
					)
7071
				);
7072
				?>
7073
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7074
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7075
				</a>
7076
			<?php else : ?>
7077
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7078
			<?php endif; ?>
7079
		</div>
7080
7081
		<div class="akismet">
7082
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7083
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7084
				<p class="blocked-count">
7085
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7086
				</p>
7087
				<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>
7088
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7089
				<a href="
7090
				<?php
7091
				echo esc_url(
7092
					wp_nonce_url(
7093
						add_query_arg(
7094
							array(
7095
								'action' => 'activate',
7096
								'plugin' => 'akismet/akismet.php',
7097
							),
7098
							admin_url( 'plugins.php' )
7099
						),
7100
						'activate-plugin_akismet/akismet.php'
7101
					)
7102
				);
7103
				?>
7104
							" class="button button-jetpack">
7105
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7106
				</a>
7107
			<?php else : ?>
7108
				<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>
7109
			<?php endif; ?>
7110
		</div>
7111
7112
		</footer>
7113
		<?php
7114
	}
7115
7116
	/*
7117
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7118
	 */
7119
	function jetpack_icon_user_connected( $columns ) {
7120
		$columns['user_jetpack'] = '';
7121
		return $columns;
7122
	}
7123
7124
	/*
7125
	 * Show Jetpack icon if the user is linked.
7126
	 */
7127
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7128
		if ( 'user_jetpack' === $col && self::connection()->is_user_connected( $user_id ) ) {
7129
			$jetpack_logo = new Jetpack_Logo();
7130
			$emblem_html  = sprintf(
7131
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7132
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7133
				$jetpack_logo->get_jp_emblem()
7134
			);
7135
			return $emblem_html;
7136
		}
7137
7138
		return $val;
7139
	}
7140
7141
	/*
7142
	 * Style the Jetpack user column
7143
	 */
7144
	function jetpack_user_col_style() {
7145
		global $current_screen;
7146
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7147
			?>
7148
			<style>
7149
				.fixed .column-user_jetpack {
7150
					width: 21px;
7151
				}
7152
				.jp-emblem-user-admin svg {
7153
					width: 20px;
7154
					height: 20px;
7155
				}
7156
				.jp-emblem-user-admin path {
7157
					fill: #00BE28;
7158
				}
7159
			</style>
7160
			<?php
7161
		}
7162
	}
7163
7164
	/**
7165
	 * Checks if Akismet is active and working.
7166
	 *
7167
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7168
	 * that implied usage of methods present since more recent version.
7169
	 * See https://github.com/Automattic/jetpack/pull/9585
7170
	 *
7171
	 * @since  5.1.0
7172
	 *
7173
	 * @return bool True = Akismet available. False = Aksimet not available.
7174
	 */
7175
	public static function is_akismet_active() {
7176
		static $status = null;
7177
7178
		if ( ! is_null( $status ) ) {
7179
			return $status;
7180
		}
7181
7182
		// Check if a modern version of Akismet is active.
7183
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7184
			$status = false;
7185
			return $status;
7186
		}
7187
7188
		// Make sure there is a key known to Akismet at all before verifying key.
7189
		$akismet_key = Akismet::get_api_key();
7190
		if ( ! $akismet_key ) {
7191
			$status = false;
7192
			return $status;
7193
		}
7194
7195
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7196
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7197
7198
		// 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.
7199
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7200
		// We cache the result of the Akismet key verification for ten minutes.
7201
		if ( ! $akismet_key_state || $recheck ) {
7202
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7203
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7204
		}
7205
7206
		$status = 'valid' === $akismet_key_state;
7207
7208
		return $status;
7209
	}
7210
7211
	/**
7212
	 * @deprecated
7213
	 *
7214
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7215
	 */
7216
	public static function is_function_in_backtrace() {
7217
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7218
	}
7219
7220
	/**
7221
	 * Given a minified path, and a non-minified path, will return
7222
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7223
	 *
7224
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7225
	 * root Jetpack directory.
7226
	 *
7227
	 * @since 5.6.0
7228
	 *
7229
	 * @param string $min_path
7230
	 * @param string $non_min_path
7231
	 * @return string The URL to the file
7232
	 */
7233
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7234
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7235
	}
7236
7237
	/**
7238
	 * Checks for whether Jetpack Backup is enabled.
7239
	 * Will return true if the state of Backup is anything except "unavailable".
7240
	 *
7241
	 * @return bool|int|mixed
7242
	 */
7243
	public static function is_rewind_enabled() {
7244
		// Rewind is a paid feature, therefore requires a user-level connection.
7245
		if ( ! static::connection()->has_connected_owner() ) {
7246
			return false;
7247
		}
7248
7249
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7250
		if ( false === $rewind_enabled ) {
7251
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7252
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7253
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7254
				&& ! empty( $rewind_data['state'] )
7255
				&& 'active' === $rewind_data['state'] )
7256
				? 1
7257
				: 0;
7258
7259
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7260
		}
7261
		return $rewind_enabled;
7262
	}
7263
7264
	/**
7265
	 * Return Calypso environment value; used for developing Jetpack and pairing
7266
	 * it with different Calypso enrionments, such as localhost.
7267
	 *
7268
	 * @since 7.4.0
7269
	 *
7270
	 * @return string Calypso environment
7271
	 */
7272
	public static function get_calypso_env() {
7273
		if ( isset( $_GET['calypso_env'] ) ) {
7274
			return sanitize_key( $_GET['calypso_env'] );
7275
		}
7276
7277
		if ( getenv( 'CALYPSO_ENV' ) ) {
7278
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7279
		}
7280
7281
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7282
			return sanitize_key( CALYPSO_ENV );
7283
		}
7284
7285
		return '';
7286
	}
7287
7288
	/**
7289
	 * Returns the hostname with protocol for Calypso.
7290
	 * Used for developing Jetpack with Calypso.
7291
	 *
7292
	 * @since 8.4.0
7293
	 *
7294
	 * @return string Calypso host.
7295
	 */
7296
	public static function get_calypso_host() {
7297
		$calypso_env = self::get_calypso_env();
7298
		switch ( $calypso_env ) {
7299
			case 'development':
7300
				return 'http://calypso.localhost:3000/';
7301
			case 'wpcalypso':
7302
				return 'https://wpcalypso.wordpress.com/';
7303
			case 'horizon':
7304
				return 'https://horizon.wordpress.com/';
7305
			default:
7306
				return 'https://wordpress.com/';
7307
		}
7308
	}
7309
7310
	/**
7311
	 * Handles activating default modules as well general cleanup for the new connection.
7312
	 *
7313
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7314
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7315
	 * @param boolean $send_state_messages          Whether to send state messages.
7316
	 * @return void
7317
	 */
7318
	public static function handle_post_authorization_actions(
7319
		$activate_sso = false,
7320
		$redirect_on_activation_error = false,
7321
		$send_state_messages = true
7322
	) {
7323
		$other_modules = $activate_sso
7324
			? array( 'sso' )
7325
			: array();
7326
7327
		if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
7328
			$active_modules = Jetpack_Options::get_option( 'active_modules' );
7329
			self::delete_active_modules();
7330
7331
			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...
7332
		} else {
7333
			// Default modules that don't require a user were already activated on site_register.
7334
			// This time let's activate only those that require a user, this assures we don't reactivate manually deactivated modules while the site was connected only at a site level.
7335
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
7336
			Jetpack_Options::update_option( 'active_modules_initialized', true );
7337
		}
7338
7339
		// Since this is a fresh connection, be sure to clear out IDC options
7340
		Identity_Crisis::clear_all_idc_options();
7341
7342
		if ( $send_state_messages ) {
7343
			self::state( 'message', 'authorized' );
7344
		}
7345
	}
7346
7347
	/**
7348
	 * Returns a boolean for whether backups UI should be displayed or not.
7349
	 *
7350
	 * @return bool Should backups UI be displayed?
7351
	 */
7352
	public static function show_backups_ui() {
7353
		/**
7354
		 * Whether UI for backups should be displayed.
7355
		 *
7356
		 * @since 6.5.0
7357
		 *
7358
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7359
		 */
7360
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7361
	}
7362
7363
	/*
7364
	 * Deprecated manage functions
7365
	 */
7366
	function prepare_manage_jetpack_notice() {
7367
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7368
	}
7369
	function manage_activate_screen() {
7370
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7371
	}
7372
	function admin_jetpack_manage_notice() {
7373
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7374
	}
7375
	function opt_out_jetpack_manage_url() {
7376
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7377
	}
7378
	function opt_in_jetpack_manage_url() {
7379
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7380
	}
7381
	function opt_in_jetpack_manage_notice() {
7382
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7383
	}
7384
	function can_display_jetpack_manage_notice() {
7385
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7386
	}
7387
7388
	/**
7389
	 * Clean leftoveruser meta.
7390
	 *
7391
	 * Delete Jetpack-related user meta when it is no longer needed.
7392
	 *
7393
	 * @since 7.3.0
7394
	 *
7395
	 * @param int $user_id User ID being updated.
7396
	 */
7397
	public static function user_meta_cleanup( $user_id ) {
7398
		$meta_keys = array(
7399
			// AtD removed from Jetpack 7.3
7400
			'AtD_options',
7401
			'AtD_check_when',
7402
			'AtD_guess_lang',
7403
			'AtD_ignored_phrases',
7404
		);
7405
7406
		foreach ( $meta_keys as $meta_key ) {
7407
			if ( get_user_meta( $user_id, $meta_key ) ) {
7408
				delete_user_meta( $user_id, $meta_key );
7409
			}
7410
		}
7411
	}
7412
7413
	/**
7414
	 * Checks if a Jetpack site is both active and not in offline mode.
7415
	 *
7416
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7417
	 *
7418
	 * @deprecated 8.8.0
7419
	 *
7420
	 * @return bool True if Jetpack is active and not in offline mode.
7421
	 */
7422
	public static function is_active_and_not_development_mode() {
7423
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7424
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack::is_active() has been deprecated with message: 9.6.0

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

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

Loading history...
7425
			return false;
7426
		}
7427
		return true;
7428
	}
7429
7430
	/**
7431
	 * Checks if a Jetpack site is both active and not in offline mode.
7432
	 *
7433
	 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
7434
	 *
7435
	 * @since 8.8.0
7436
	 *
7437
	 * @return bool True if Jetpack is active and not in offline mode.
7438
	 */
7439
	public static function is_active_and_not_offline_mode() {
7440
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
7441
			return false;
7442
		}
7443
		return true;
7444
	}
7445
7446
	/**
7447
	 * Returns the list of products that we have available for purchase.
7448
	 */
7449
	public static function get_products_for_purchase() {
7450
		$products = array();
7451
		if ( ! is_multisite() ) {
7452
			$products[] = array(
7453
				'key'               => 'backup',
7454
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7455
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7456
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7457
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7458
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7459
				'options'           => array(
7460
					array(
7461
						'type'        => 'daily',
7462
						'slug'        => 'jetpack-backup-daily',
7463
						'key'         => 'jetpack_backup_daily',
7464
						'name'        => __( 'Daily Backups', 'jetpack' ),
7465
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7466
					),
7467
					array(
7468
						'type'        => 'realtime',
7469
						'slug'        => 'jetpack-backup-realtime',
7470
						'key'         => 'jetpack_backup_realtime',
7471
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7472
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7473
					),
7474
				),
7475
				'default_option'    => 'realtime',
7476
				'show_promotion'    => true,
7477
				'discount_percent'  => 70,
7478
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7479
			);
7480
7481
			$products[] = array(
7482
				'key'               => 'scan',
7483
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7484
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7485
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7486
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7487
				'show_promotion'    => true,
7488
				'discount_percent'  => 30,
7489
				'options'           => array(
7490
					array(
7491
						'type' => 'scan',
7492
						'slug' => 'jetpack-scan',
7493
						'key'  => 'jetpack_scan',
7494
						'name' => __( 'Daily Scan', 'jetpack' ),
7495
					),
7496
				),
7497
				'default_option'    => 'scan',
7498
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7499
			);
7500
		}
7501
7502
		$products[] = array(
7503
			'key'               => 'search',
7504
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7505
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7506
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7507
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7508
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7509
			'options'           => array(
7510
				array(
7511
					'type' => 'search',
7512
					'slug' => 'jetpack-search',
7513
					'key'  => 'jetpack_search',
7514
					'name' => __( 'Search', 'jetpack' ),
7515
				),
7516
			),
7517
			'tears'             => array(),
7518
			'default_option'    => 'search',
7519
			'show_promotion'    => false,
7520
			'included_in_plans' => array( 'search-plan' ),
7521
		);
7522
7523
		$products[] = array(
7524
			'key'               => 'anti-spam',
7525
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7526
			'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' ),
7527
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7528
			'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' ),
7529
			'options'           => array(
7530
				array(
7531
					'type' => 'anti-spam',
7532
					'slug' => 'jetpack-anti-spam',
7533
					'key'  => 'jetpack_anti_spam',
7534
					'name' => __( 'Anti-Spam', 'jetpack' ),
7535
				),
7536
			),
7537
			'default_option'    => 'anti-spam',
7538
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7539
		);
7540
7541
		return $products;
7542
	}
7543
7544
	/**
7545
	 * Determine if the current user is allowed to make Jetpack purchases without
7546
	 * a WordPress.com account
7547
	 *
7548
	 * @return boolean True if the user can make purchases, false if not
7549
	 */
7550
	public static function current_user_can_purchase() {
7551
7552
		// The site must be site-connected to Jetpack (no users connected).
7553
		if ( ! self::connection()->is_site_connection() ) {
7554
			return false;
7555
		}
7556
7557
		// Make sure only administrators can make purchases.
7558
		if ( ! current_user_can( 'manage_options' ) ) {
7559
			return false;
7560
		}
7561
7562
		return true;
7563
	}
7564
7565
}
7566