Completed
Push — fix/paid-upgrades-and-jetpack-... ( 035b27...ac9eb4 )
by
unknown
43:12 queued 33:24
created

Jetpack::disconnect()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 16
nop 1
dl 0
loc 46
rs 8.5559
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\Licensing;
18
use Automattic\Jetpack\Partner;
19
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
20
use Automattic\Jetpack\Redirect;
21
use Automattic\Jetpack\Status;
22
use Automattic\Jetpack\Sync\Functions;
23
use Automattic\Jetpack\Sync\Health;
24
use Automattic\Jetpack\Sync\Sender;
25
use Automattic\Jetpack\Sync\Users;
26
use Automattic\Jetpack\Terms_Of_Service;
27
use Automattic\Jetpack\Tracking;
28
29
/*
30
Options:
31
jetpack_options (array)
32
	An array of options.
33
	@see Jetpack_Options::get_option_names()
34
35
jetpack_register (string)
36
	Temporary verification secrets.
37
38
jetpack_activated (int)
39
	1: the plugin was activated normally
40
	2: the plugin was activated on this site because of a network-wide activation
41
	3: the plugin was auto-installed
42
	4: the plugin was manually disconnected (but is still installed)
43
44
jetpack_active_modules (array)
45
	Array of active module slugs.
46
47
jetpack_do_activate (bool)
48
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
49
*/
50
51
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
52
53
class Jetpack {
54
	public $xmlrpc_server = null;
55
56
	/**
57
	 * @var array The handles of styles that are concatenated into jetpack.css.
58
	 *
59
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
60
	 */
61
	public $concatenated_style_handles = array(
62
		'jetpack-carousel',
63
		'grunion.css',
64
		'the-neverending-homepage',
65
		'jetpack_likes',
66
		'jetpack_related-posts',
67
		'sharedaddy',
68
		'jetpack-slideshow',
69
		'presentations',
70
		'quiz',
71
		'jetpack-subscriptions',
72
		'jetpack-responsive-videos-style',
73
		'jetpack-social-menu',
74
		'tiled-gallery',
75
		'jetpack_display_posts_widget',
76
		'gravatar-profile-widget',
77
		'goodreads-widget',
78
		'jetpack_social_media_icons_widget',
79
		'jetpack-top-posts-widget',
80
		'jetpack_image_widget',
81
		'jetpack-my-community-widget',
82
		'jetpack-authors-widget',
83
		'wordads',
84
		'eu-cookie-law-style',
85
		'flickr-widget-style',
86
		'jetpack-search-widget',
87
		'jetpack-simple-payments-widget-style',
88
		'jetpack-widget-social-icons-styles',
89
		'wpcom_instagram_widget',
90
	);
91
92
	/**
93
	 * Contains all assets that have had their URL rewritten to minified versions.
94
	 *
95
	 * @var array
96
	 */
97
	static $min_assets = array();
98
99
	public $plugins_to_deactivate = array(
100
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
101
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
102
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
103
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
104
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
105
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
106
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
107
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
108
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
109
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
110
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
111
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
112
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
113
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
114
	);
115
116
	/**
117
	 * Map of roles we care about, and their corresponding minimum capabilities.
118
	 *
119
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
120
	 *
121
	 * @access public
122
	 * @static
123
	 *
124
	 * @var array
125
	 */
126
	public static $capability_translations = array(
127
		'administrator' => 'manage_options',
128
		'editor'        => 'edit_others_posts',
129
		'author'        => 'publish_posts',
130
		'contributor'   => 'edit_posts',
131
		'subscriber'    => 'read',
132
	);
133
134
	/**
135
	 * Map of modules that have conflicts with plugins and should not be auto-activated
136
	 * if the plugins are active.  Used by filter_default_modules
137
	 *
138
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
139
	 * change `module-slug` and add this to your plugin:
140
	 *
141
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
142
	 * function my_jetpack_get_default_modules( $modules ) {
143
	 *     return array_diff( $modules, array( 'module-slug' ) );
144
	 * }
145
	 *
146
	 * @var array
147
	 */
148
	private $conflicting_plugins = array(
149
		'comments'           => array(
150
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
151
			'Disqus'                         => 'disqus-comment-system/disqus.php',
152
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
153
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
154
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
155
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
156
		),
157
		'comment-likes'      => array(
158
			'Epoch' => 'epoch/plugincore.php',
159
		),
160
		'contact-form'       => array(
161
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
162
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
163
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
164
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
165
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
166
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
167
		),
168
		'latex'              => array(
169
			'LaTeX for WordPress'     => 'latex/latex.php',
170
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
171
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
172
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
173
			'Enable Latex'            => 'enable-latex/enable-latex.php',
174
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
175
		),
176
		'protect'            => array(
177
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
178
			'Captcha'                           => 'captcha/captcha.php',
179
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
180
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
181
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
182
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
183
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
184
			'Security-protection'               => 'security-protection/security-protection.php',
185
			'Login Security'                    => 'login-security/login-security.php',
186
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
187
			'Wordfence Security'                => 'wordfence/wordfence.php',
188
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
189
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
190
		),
191
		'random-redirect'    => array(
192
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
193
		),
194
		'related-posts'      => array(
195
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
196
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
197
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
198
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
199
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
200
			'outbrain'                    => 'outbrain/outbrain.php',
201
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
202
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
203
		),
204
		'sharedaddy'         => array(
205
			'AddThis'     => 'addthis/addthis_social_widget.php',
206
			'Add To Any'  => 'add-to-any/add-to-any.php',
207
			'ShareThis'   => 'share-this/sharethis.php',
208
			'Shareaholic' => 'shareaholic/shareaholic.php',
209
		),
210
		'seo-tools'          => array(
211
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
212
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
213
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
214
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
215
			'The SEO Framework'              => 'autodescription/autodescription.php',
216
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
217
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
218
		),
219
		'verification-tools' => array(
220
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
221
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
222
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
223
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
224
			'The SEO Framework'              => 'autodescription/autodescription.php',
225
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
226
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
227
		),
228
		'widget-visibility'  => array(
229
			'Widget Logic'    => 'widget-logic/widget_logic.php',
230
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
231
		),
232
		'sitemaps'           => array(
233
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
234
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
235
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
236
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
237
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
238
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
239
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
240
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
241
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
242
			'The SEO Framework'                    => 'autodescription/autodescription.php',
243
			'Sitemap'                              => 'sitemap/sitemap.php',
244
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
245
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
246
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
247
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
248
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
249
			'Slim SEO'                             => 'slim-seo/slim-seo.php',
250
		),
251
		'lazy-images'        => array(
252
			'Lazy Load'              => 'lazy-load/lazy-load.php',
253
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
254
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
255
		),
256
	);
257
258
	/**
259
	 * Plugins for which we turn off our Facebook OG Tags implementation.
260
	 *
261
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
262
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
263
	 *
264
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
265
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
266
	 */
267
	private $open_graph_conflicting_plugins = array(
268
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
269
		// 2 Click Social Media Buttons
270
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
271
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
272
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
273
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
274
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
275
		// Open Graph Meta Tags by Heateor
276
		'facebook/facebook.php',                                 // Facebook (official plugin)
277
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
278
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
279
		// Facebook Featured Image & OG Meta Tags
280
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
281
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
282
		// Facebook Open Graph Meta Tags for WordPress
283
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
284
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
285
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
286
		// Fedmich's Facebook Open Graph Meta
287
		'network-publisher/networkpub.php',                      // Network Publisher
288
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
289
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
290
		// NextScripts SNAP
291
		'og-tags/og-tags.php',                                   // OG Tags
292
		'opengraph/opengraph.php',                               // Open Graph
293
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
294
		// Open Graph Protocol Framework
295
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
296
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
297
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
298
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
299
		'sharepress/sharepress.php',                             // SharePress
300
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
301
		'social-discussions/social-discussions.php',             // Social Discussions
302
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
303
		'socialize/socialize.php',                               // Socialize
304
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
305
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
306
		// Tweet, Like, Google +1 and Share
307
		'wordbooker/wordbooker.php',                             // Wordbooker
308
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
309
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
310
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
311
		// WP Facebook Like Send & Open Graph Meta
312
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
313
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
314
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
315
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
316
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
317
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
318
		'slim-seo/slim-seo.php',                                 // Slim SEO
319
	);
320
321
	/**
322
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
323
	 */
324
	private $twitter_cards_conflicting_plugins = array(
325
		// 'twitter/twitter.php',                       // The official one handles this on its own.
326
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
327
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
328
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
329
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
330
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
331
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
332
		'twitter-cards/twitter-cards.php',           // Twitter Cards
333
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
334
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
335
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
336
		'seo-by-rank-math/rank-math.php',            // Rank Math.
337
		'slim-seo/slim-seo.php',                     // Slim SEO
338
	);
339
340
	/**
341
	 * Message to display in admin_notice
342
	 *
343
	 * @var string
344
	 */
345
	public $message = '';
346
347
	/**
348
	 * Error to display in admin_notice
349
	 *
350
	 * @var string
351
	 */
352
	public $error = '';
353
354
	/**
355
	 * Modules that need more privacy description.
356
	 *
357
	 * @var string
358
	 */
359
	public $privacy_checks = '';
360
361
	/**
362
	 * Stats to record once the page loads
363
	 *
364
	 * @var array
365
	 */
366
	public $stats = array();
367
368
	/**
369
	 * Jetpack_Sync object
370
	 */
371
	public $sync;
372
373
	/**
374
	 * Verified data for JSON authorization request
375
	 */
376
	public $json_api_authorization_request = array();
377
378
	/**
379
	 * @var Automattic\Jetpack\Connection\Manager
380
	 */
381
	protected $connection_manager;
382
383
	/**
384
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
385
	 */
386
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
387
388
	/**
389
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
390
	 *
391
	 * @var Automattic\Jetpack\A8c_Mc_Stats
392
	 */
393
	public $a8c_mc_stats_instance;
394
395
	/**
396
	 * Constant for login redirect key.
397
	 *
398
	 * @var string
399
	 * @since 8.4.0
400
	 */
401
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
402
403
	/**
404
	 * Holds the singleton instance of this class
405
	 *
406
	 * @since 2.3.3
407
	 * @var Jetpack
408
	 */
409
	static $instance = false;
410
411
	/**
412
	 * Singleton
413
	 *
414
	 * @static
415
	 */
416
	public static function init() {
417
		if ( ! self::$instance ) {
418
			self::$instance = new Jetpack();
419
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
420
		}
421
422
		return self::$instance;
423
	}
424
425
	/**
426
	 * Must never be called statically
427
	 */
428
	function plugin_upgrade() {
429
		if ( self::is_connection_ready() ) {
430
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
431
			if ( JETPACK__VERSION != $version ) {
432
				// Prevent multiple upgrades at once - only a single process should trigger
433
				// an upgrade to avoid stampedes
434
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
435
					return;
436
				}
437
438
				// Set a short lock to prevent multiple instances of the upgrade
439
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
440
441
				// check which active modules actually exist and remove others from active_modules list
442
				$unfiltered_modules = self::get_active_modules();
443
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
444
				if ( array_diff( $unfiltered_modules, $modules ) ) {
445
					self::update_active_modules( $modules );
446
				}
447
448
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
449
450
				// Upgrade to 4.3.0
451
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
452
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
453
				}
454
455
				// Make sure Markdown for posts gets turned back on
456
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
457
					update_option( 'wpcom_publish_posts_with_markdown', true );
458
				}
459
460
				/*
461
				 * Minileven deprecation. 8.3.0.
462
				 * Only delete options if not using
463
				 * the replacement standalone Minileven plugin.
464
				 */
465
				if (
466
					! self::is_plugin_active( 'minileven-master/minileven.php' )
467
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
468
				) {
469
					if ( get_option( 'wp_mobile_custom_css' ) ) {
470
						delete_option( 'wp_mobile_custom_css' );
471
					}
472
					if ( get_option( 'wp_mobile_excerpt' ) ) {
473
						delete_option( 'wp_mobile_excerpt' );
474
					}
475
					if ( get_option( 'wp_mobile_featured_images' ) ) {
476
						delete_option( 'wp_mobile_featured_images' );
477
					}
478
					if ( get_option( 'wp_mobile_app_promos' ) ) {
479
						delete_option( 'wp_mobile_app_promos' );
480
					}
481
				}
482
483
				// Upgrade to 8.4.0.
484
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
485
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
486
				}
487
488
				// Update to 8.8.x (WordPress 5.5 Compatibility).
489
				if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
490
					$updated = update_site_option(
491
						'auto_update_plugins',
492
						array_unique(
493
							array_merge(
494
								(array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
495
								(array) get_site_option( 'auto_update_plugins', array() )
496
							)
497
						)
498
					);
499
500
					if ( $updated ) {
501
						Jetpack_Options::delete_option( 'autoupdate_plugins' );
502
					} // Should we have some type of fallback if something fails here?
503
				}
504
505
				if ( did_action( 'wp_loaded' ) ) {
506
					self::upgrade_on_load();
507
				} else {
508
					add_action(
509
						'wp_loaded',
510
						array( __CLASS__, 'upgrade_on_load' )
511
					);
512
				}
513
			}
514
		}
515
	}
516
517
	/**
518
	 * Runs upgrade routines that need to have modules loaded.
519
	 */
520
	static function upgrade_on_load() {
521
522
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
523
		// This can happen in case Jetpack has been just upgraded and is
524
		// being initialized late during the page load. In this case we wait
525
		// until the next proper admin page load with Jetpack active.
526
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
527
			delete_transient( self::$plugin_upgrade_lock_key );
528
529
			return;
530
		}
531
532
		self::maybe_set_version_option();
533
534
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
535
			Jetpack_Widget_Conditions::migrate_post_type_rules();
536
		}
537
538
		if (
539
			class_exists( 'Jetpack_Sitemap_Manager' )
540
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
541
		) {
542
			do_action( 'jetpack_sitemaps_purge_data' );
543
		}
544
545
		// Delete old stats cache
546
		delete_option( 'jetpack_restapi_stats_cache' );
547
548
		delete_transient( self::$plugin_upgrade_lock_key );
549
	}
550
551
	/**
552
	 * Saves all the currently active modules to options.
553
	 * Also fires Action hooks for each newly activated and deactivated module.
554
	 *
555
	 * @param $modules Array Array of active modules to be saved in options.
556
	 *
557
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
Documentation introduced by
The doc-type $success could not be parsed: Unknown type name "$success" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
558
	 */
559
	static function update_active_modules( $modules ) {
560
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
561
		$active_modules       = self::get_active_modules();
562
		$new_active_modules   = array_diff( $modules, $current_modules );
563
		$new_inactive_modules = array_diff( $active_modules, $modules );
564
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
565
		$reindexed_modules    = array_values( $new_current_modules );
566
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
567
568
		foreach ( $new_active_modules as $module ) {
569
			/**
570
			 * Fires when a specific module is activated.
571
			 *
572
			 * @since 1.9.0
573
			 *
574
			 * @param string $module Module slug.
575
			 * @param boolean $success whether the module was activated. @since 4.2
576
			 */
577
			do_action( 'jetpack_activate_module', $module, $success );
578
			/**
579
			 * Fires when a module is activated.
580
			 * The dynamic part of the filter, $module, is the module slug.
581
			 *
582
			 * @since 1.9.0
583
			 *
584
			 * @param string $module Module slug.
585
			 */
586
			do_action( "jetpack_activate_module_$module", $module );
587
		}
588
589
		foreach ( $new_inactive_modules as $module ) {
590
			/**
591
			 * Fired after a module has been deactivated.
592
			 *
593
			 * @since 4.2.0
594
			 *
595
			 * @param string $module Module slug.
596
			 * @param boolean $success whether the module was deactivated.
597
			 */
598
			do_action( 'jetpack_deactivate_module', $module, $success );
599
			/**
600
			 * Fires when a module is deactivated.
601
			 * The dynamic part of the filter, $module, is the module slug.
602
			 *
603
			 * @since 1.9.0
604
			 *
605
			 * @param string $module Module slug.
606
			 */
607
			do_action( "jetpack_deactivate_module_$module", $module );
608
		}
609
610
		return $success;
611
	}
612
613
	static function delete_active_modules() {
614
		self::update_active_modules( array() );
615
	}
616
617
	/**
618
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
619
	 * available.
620
	 */
621
	public function add_configure_hook() {
622
		global $wp_filter;
623
624
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
625
		if ( false !== $current_priority ) {
626
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
627
		}
628
629
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
630
		sort( $taken_priorities );
631
632
		$first_priority = array_shift( $taken_priorities );
633
634
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
635
			$new_priority = - PHP_INT_MAX;
636
		} else {
637
			$new_priority = $first_priority - 1;
638
		}
639
640
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
641
	}
642
643
	/**
644
	 * Constructor.  Initializes WordPress hooks
645
	 */
646
	private function __construct() {
647
		/*
648
		 * Check for and alert any deprecated hooks
649
		 */
650
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
651
652
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
653
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
654
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
655
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
656
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
657
658
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
659
660
		add_filter(
661
			'jetpack_signature_check_token',
662
			array( __CLASS__, 'verify_onboarding_token' ),
663
			10,
664
			3
665
		);
666
667
		/**
668
		 * Prepare Gutenberg Editor functionality
669
		 */
670
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
671
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
672
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
673
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
674
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
675
676
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
677
678
		// Unlink user before deleting the user from WP.com.
679
		add_action( 'deleted_user', array( $this, 'disconnect_user' ), 10, 1 );
680
		add_action( 'remove_user_from_blog', array( $this, 'disconnect_user' ), 10, 1 );
681
682
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
683
684
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
685
		add_action( 'login_init', array( $this, 'login_init' ) );
686
687
		// Set up the REST authentication hooks.
688
		Connection_Rest_Authentication::init();
689
690
		add_action( 'admin_init', array( $this, 'admin_init' ) );
691
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
692
693
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
694
695
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
696
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
697
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
698
699
		// returns HTTPS support status
700
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
701
702
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
703
704
		add_action( 'wp_ajax_jetpack_recommendations_banner', array( 'Jetpack_Recommendations_Banner', 'ajax_callback' ) );
705
706
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
707
708
		/**
709
		 * These actions run checks to load additional files.
710
		 * They check for external files or plugins, so they need to run as late as possible.
711
		 */
712
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
713
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
714
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
715
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
716
717
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
718
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
719
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
720
721
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
722
723
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
724
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
725
726
		require_once JETPACK__PLUGIN_DIR . 'class-jetpack-pre-connection-jitms.php';
727
		$jetpack_jitm_messages = ( new Jetpack_Pre_Connection_JITMs() );
728
		add_filter( 'jetpack_pre_connection_jitms', array( $jetpack_jitm_messages, 'add_pre_connection_jitms' ) );
729
730
		/*
731
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
732
		 * We should make sure to only do this for front end links.
733
		 */
734
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
735
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
736
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
737
738
			/*
739
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
740
			 * so they point moderation links on emails to Calypso.
741
			 */
742
			jetpack_require_lib( 'functions.wp-notify' );
743
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
744
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
745
		}
746
747
		add_action(
748
			'plugins_loaded',
749
			function () {
750
				if ( User_Agent_Info::is_mobile_app() ) {
751
					add_filter( 'get_edit_post_link', '__return_empty_string' );
752
				}
753
			}
754
		);
755
756
		// Update the site's Jetpack plan and products from API on heartbeats.
757
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
758
759
		/**
760
		 * This is the hack to concatenate all css files into one.
761
		 * For description and reasoning see the implode_frontend_css method.
762
		 *
763
		 * Super late priority so we catch all the registered styles.
764
		 */
765
		if ( ! is_admin() ) {
766
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
767
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
768
		}
769
770
		/**
771
		 * These are sync actions that we need to keep track of for jitms
772
		 */
773
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
774
775
		// Actually push the stats on shutdown.
776
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
777
			add_action( 'shutdown', array( $this, 'push_stats' ) );
778
		}
779
780
		// After a successful connection.
781
		add_action( 'jetpack_site_registered', array( $this, 'activate_default_modules_on_site_register' ) );
782
		add_action( 'jetpack_site_registered', array( $this, 'handle_unique_registrations_stats' ) );
783
784
		// Actions for Manager::authorize().
785
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
786
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
787
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
788
789
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
790
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
791
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
792
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
793
794
		// Filters for the Manager::get_token() urls and request body.
795
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
796
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
797
798
		// Actions for successful reconnect.
799
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
800
801
		// Actions for licensing.
802
		Licensing::instance()->initialize();
803
804
		// Filters for Sync Callables.
805
		add_filter( 'jetpack_sync_callable_whitelist', array( $this, 'filter_sync_callable_whitelist' ), 10, 1 );
806
		add_filter( 'jetpack_sync_multisite_callable_whitelist', array( $this, 'filter_sync_multisite_callable_whitelist' ), 10, 1 );
807
808
		// Make resources use static domain when possible.
809
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
810
811
		// Validate the domain names in Jetpack development versions.
812
		add_action( 'jetpack_pre_register', array( get_called_class(), 'registration_check_domains' ) );
813
	}
814
815
	/**
816
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
817
	 * Config object.
818
	 */
819
	public function configure() {
820
		$config = new Config();
821
822
		foreach (
823
			array(
824
				'sync',
825
				'jitm',
826
			)
827
			as $feature
828
		) {
829
			$config->ensure( $feature );
830
		}
831
832
		$config->ensure(
833
			'connection',
834
			array(
835
				'slug' => 'jetpack',
836
				'name' => 'Jetpack',
837
			)
838
		);
839
840
		if ( ! $this->connection_manager ) {
841
			$this->connection_manager = new Connection_Manager( 'jetpack' );
842
843
			/**
844
			 * Filter to activate Jetpack Connection UI.
845
			 * INTERNAL USE ONLY.
846
			 *
847
			 * @since 9.5.0
848
			 *
849
			 * @param bool false Whether to activate the Connection UI.
850
			 */
851
			if ( apply_filters( 'jetpack_connection_ui_active', false ) ) {
852
				Automattic\Jetpack\ConnectionUI\Admin::init();
853
			}
854
		}
855
856
		/*
857
		 * Load things that should only be in Network Admin.
858
		 *
859
		 * For now blow away everything else until a more full
860
		 * understanding of what is needed at the network level is
861
		 * available
862
		 */
863
		if ( is_multisite() ) {
864
			$network = Jetpack_Network::init();
865
			$network->set_connection( $this->connection_manager );
866
		}
867
868
		if ( self::is_connection_ready() ) {
869
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
870
871
			Jetpack_Heartbeat::init();
872
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
873
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
874
				Jetpack_Search_Performance_Logger::init();
875
			}
876
		}
877
878
		// Initialize remote file upload request handlers.
879
		$this->add_remote_request_handlers();
880
881
		/*
882
		 * Enable enhanced handling of previewing sites in Calypso
883
		 */
884
		if ( self::is_connection_ready() ) {
885
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
886
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
887
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
888
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
889
		}
890
891
		if ( ( new Tracking( $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) ) {
0 ignored issues
show
Documentation introduced by
$this->connection_manager is of type object<Automattic\Jetpack\Connection\Manager>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
892
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
893
		} else {
894
			/**
895
			 * Initialize tracking right after the user agrees to the terms of service.
896
			 */
897
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
898
		}
899
	}
900
901
	/**
902
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
903
	 * initialization code.
904
	 *
905
	 * @action plugins_loaded
906
	 */
907
	public function late_initialization() {
908
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
909
910
		Partner::init();
911
912
		/**
913
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
914
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
915
		 *
916
		 * @since 8.1.0
917
		 *
918
		 * @param Jetpack $jetpack the main plugin class object.
919
		 */
920
		do_action( 'jetpack_loaded', $this );
921
922
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
923
	}
924
925
	/**
926
	 * Sets up the XMLRPC request handlers.
927
	 *
928
	 * @deprecated since 7.7.0
929
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
930
	 *
931
	 * @param array                 $request_params Incoming request parameters.
932
	 * @param Boolean               $is_active      Whether the connection is currently active.
933
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
934
	 * @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...
935
	 */
936 View Code Duplication
	public function setup_xmlrpc_handlers(
937
		$request_params,
938
		$is_active,
939
		$is_signed,
940
		Jetpack_XMLRPC_Server $xmlrpc_server = null
941
	) {
942
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
943
944
		if ( ! $this->connection_manager ) {
945
			$this->connection_manager = new Connection_Manager();
946
		}
947
948
		return $this->connection_manager->setup_xmlrpc_handlers(
949
			$request_params,
950
			$is_active,
951
			$is_signed,
952
			$xmlrpc_server
953
		);
954
	}
955
956
	/**
957
	 * Initialize REST API registration connector.
958
	 *
959
	 * @deprecated since 7.7.0
960
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
961
	 */
962 View Code Duplication
	public function initialize_rest_api_registration_connector() {
963
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
964
965
		if ( ! $this->connection_manager ) {
966
			$this->connection_manager = new Connection_Manager();
967
		}
968
969
		$this->connection_manager->initialize_rest_api_registration_connector();
970
	}
971
972
	/**
973
	 * This is ported over from the manage module, which has been deprecated and baked in here.
974
	 *
975
	 * @param $domains
976
	 */
977
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
978
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
979
	}
980
981
	/**
982
	 * Return $domains, with 'wordpress.com' appended.
983
	 * This is ported over from the manage module, which has been deprecated and baked in here.
984
	 *
985
	 * @param $domains
986
	 * @return array
987
	 */
988
	function allow_wpcom_domain( $domains ) {
989
		if ( empty( $domains ) ) {
990
			$domains = array();
991
		}
992
		$domains[] = 'wordpress.com';
993
		return array_unique( $domains );
994
	}
995
996
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
997
		$post = get_post( $post_id );
998
999
		if ( empty( $post ) ) {
1000
			return $default_url;
1001
		}
1002
1003
		$post_type = $post->post_type;
1004
1005
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1006
		// https://en.support.wordpress.com/custom-post-types/
1007
		$allowed_post_types = array(
1008
			'post',
1009
			'page',
1010
			'jetpack-portfolio',
1011
			'jetpack-testimonial',
1012
		);
1013
1014
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1015
			return $default_url;
1016
		}
1017
1018
		return Redirect::get_url(
1019
			'calypso-edit-' . $post_type,
1020
			array(
1021
				'path' => $post_id,
1022
			)
1023
		);
1024
	}
1025
1026
	function point_edit_comment_links_to_calypso( $url ) {
1027
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1028
		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...
1029
1030
		return Redirect::get_url(
1031
			'calypso-edit-comment',
1032
			array(
1033
				'path' => $query_args['amp;c'],
1034
			)
1035
		);
1036
1037
	}
1038
1039
	/**
1040
	 * Extend Sync callables with Jetpack Plugin functions.
1041
	 *
1042
	 * @param array $callables list of callables.
1043
	 *
1044
	 * @return array list of callables.
1045
	 */
1046
	public function filter_sync_callable_whitelist( $callables ) {
1047
1048
		// Jetpack Functions.
1049
		$jetpack_callables = array(
1050
			'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
1051
			'updates'                  => array( 'Jetpack', 'get_updates' ),
1052
			'active_modules'           => array( 'Jetpack', 'get_active_modules' ),
1053
			'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1054
		);
1055
		$callables         = array_merge( $callables, $jetpack_callables );
1056
1057
		// Jetpack_SSO_Helpers.
1058
		if ( include_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' ) {
1059
			$sso_helpers = array(
1060
				'sso_is_two_step_required'      => array( 'Jetpack_SSO_Helpers', 'is_two_step_required' ),
1061
				'sso_should_hide_login_form'    => array( 'Jetpack_SSO_Helpers', 'should_hide_login_form' ),
1062
				'sso_match_by_email'            => array( 'Jetpack_SSO_Helpers', 'match_by_email' ),
1063
				'sso_new_user_override'         => array( 'Jetpack_SSO_Helpers', 'new_user_override' ),
1064
				'sso_bypass_default_login_form' => array( 'Jetpack_SSO_Helpers', 'bypass_login_forward_wpcom' ),
1065
			);
1066
			$callables   = array_merge( $callables, $sso_helpers );
1067
		}
1068
1069
		return $callables;
1070
	}
1071
1072
	/**
1073
	 * Extend Sync multisite callables with Jetpack Plugin functions.
1074
	 *
1075
	 * @param array $callables list of callables.
1076
	 *
1077
	 * @return array list of callables.
1078
	 */
1079
	public function filter_sync_multisite_callable_whitelist( $callables ) {
1080
1081
		// Jetpack Funtions.
1082
		$jetpack_multisite_callables = array(
1083
			'network_name'                        => array( 'Jetpack', 'network_name' ),
1084
			'network_allow_new_registrations'     => array( 'Jetpack', 'network_allow_new_registrations' ),
1085
			'network_add_new_users'               => array( 'Jetpack', 'network_add_new_users' ),
1086
			'network_site_upload_space'           => array( 'Jetpack', 'network_site_upload_space' ),
1087
			'network_upload_file_types'           => array( 'Jetpack', 'network_upload_file_types' ),
1088
			'network_enable_administration_menus' => array( 'Jetpack', 'network_enable_administration_menus' ),
1089
		);
1090
		$callables                   = array_merge( $callables, $jetpack_multisite_callables );
1091
1092
		return $callables;
1093
	}
1094
1095
	function jetpack_track_last_sync_callback( $params ) {
1096
		/**
1097
		 * This filter is documented in the Automattic\Jetpack\JITMS\Post_Connection_JITM class.
1098
		 */
1099
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', true ) ) {
1100
			return $params;
1101
		}
1102
1103
		if ( is_array( $params ) && isset( $params[0] ) ) {
1104
			$option = $params[0];
1105
			if ( 'active_plugins' === $option ) {
1106
				// use the cache if we can, but not terribly important if it gets evicted
1107
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1108
			}
1109
		}
1110
1111
		return $params;
1112
	}
1113
1114
	function jetpack_connection_banner_callback() {
1115
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1116
1117
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1118
		if (
1119
			isset( $_REQUEST['dismissBanner'] ) &&
1120
			! Jetpack_Connection_Banner::force_display()
1121
		) {
1122
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1123
			wp_send_json_success();
1124
		}
1125
1126
		wp_die();
1127
	}
1128
1129
	/**
1130
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1131
	 * Only used in our alternate XML-RPC endpoint, where we want to
1132
	 * ensure that Core and other plugins' methods are not exposed.
1133
	 *
1134
	 * @deprecated since 7.7.0
1135
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1136
	 *
1137
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1138
	 * @return array Filtered $methods
1139
	 */
1140 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1141
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1142
1143
		if ( ! $this->connection_manager ) {
1144
			$this->connection_manager = new Connection_Manager();
1145
		}
1146
1147
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1148
	}
1149
1150
	/**
1151
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1152
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1153
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1154
	 * which is accessible via a different URI. Most of the below is copied directly
1155
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1156
	 *
1157
	 * @deprecated since 7.7.0
1158
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1159
	 */
1160 View Code Duplication
	public function alternate_xmlrpc() {
1161
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1162
1163
		if ( ! $this->connection_manager ) {
1164
			$this->connection_manager = new Connection_Manager();
1165
		}
1166
1167
		$this->connection_manager->alternate_xmlrpc();
1168
	}
1169
1170
	/**
1171
	 * The callback for the JITM ajax requests.
1172
	 *
1173
	 * @deprecated since 7.9.0
1174
	 */
1175
	function jetpack_jitm_ajax_callback() {
1176
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1177
	}
1178
1179
	/**
1180
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1181
	 */
1182
	function push_stats() {
1183
		if ( ! empty( $this->stats ) ) {
1184
			$this->do_stats( 'server_side' );
1185
		}
1186
	}
1187
1188
	/**
1189
	 * Sets the Jetpack custom capabilities.
1190
	 *
1191
	 * @param string[] $caps    Array of the user's capabilities.
1192
	 * @param string   $cap     Capability name.
1193
	 * @param int      $user_id The user ID.
1194
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1195
	 */
1196
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1197
		switch ( $cap ) {
1198
			case 'jetpack_manage_modules':
1199
			case 'jetpack_activate_modules':
1200
			case 'jetpack_deactivate_modules':
1201
				$caps = array( 'manage_options' );
1202
				break;
1203
			case 'jetpack_configure_modules':
1204
				$caps = array( 'manage_options' );
1205
				break;
1206
			case 'jetpack_manage_autoupdates':
1207
				$caps = array(
1208
					'manage_options',
1209
					'update_plugins',
1210
				);
1211
				break;
1212
			case 'jetpack_network_admin_page':
1213
			case 'jetpack_network_settings_page':
1214
				$caps = array( 'manage_network_plugins' );
1215
				break;
1216
			case 'jetpack_network_sites_page':
1217
				$caps = array( 'manage_sites' );
1218
				break;
1219 View Code Duplication
			case 'jetpack_admin_page':
1220
				$is_offline_mode = ( new Status() )->is_offline_mode();
1221
				if ( $is_offline_mode ) {
1222
					$caps = array( 'manage_options' );
1223
					break;
1224
				} else {
1225
					$caps = array( 'read' );
1226
				}
1227
				break;
1228
		}
1229
		return $caps;
1230
	}
1231
1232
	/**
1233
	 * Require a Jetpack authentication.
1234
	 *
1235
	 * @deprecated since 7.7.0
1236
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1237
	 */
1238 View Code Duplication
	public function require_jetpack_authentication() {
1239
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1240
1241
		if ( ! $this->connection_manager ) {
1242
			$this->connection_manager = new Connection_Manager();
1243
		}
1244
1245
		$this->connection_manager->require_jetpack_authentication();
1246
	}
1247
1248
	/**
1249
	 * Register assets for use in various modules and the Jetpack admin page.
1250
	 *
1251
	 * @uses wp_script_is, wp_register_script, plugins_url
1252
	 * @action wp_loaded
1253
	 * @return null
1254
	 */
1255
	public function register_assets() {
1256 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1257
			wp_register_script(
1258
				'jetpack-gallery-settings',
1259
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1260
				array( 'media-views' ),
1261
				'20121225'
1262
			);
1263
		}
1264
1265
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1266
			wp_register_script(
1267
				'jetpack-twitter-timeline',
1268
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1269
				array( 'jquery' ),
1270
				'4.0.0',
1271
				true
1272
			);
1273
		}
1274
1275
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1276
			wp_register_script(
1277
				'jetpack-facebook-embed',
1278
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1279
				array(),
1280
				null,
1281
				true
1282
			);
1283
1284
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1285
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1286
			if ( ! is_numeric( $fb_app_id ) ) {
1287
				$fb_app_id = '';
1288
			}
1289
			wp_localize_script(
1290
				'jetpack-facebook-embed',
1291
				'jpfbembed',
1292
				array(
1293
					'appid'  => $fb_app_id,
1294
					'locale' => $this->get_locale(),
1295
				)
1296
			);
1297
		}
1298
1299
		/**
1300
		 * As jetpack_register_genericons is by default fired off a hook,
1301
		 * the hook may have already fired by this point.
1302
		 * So, let's just trigger it manually.
1303
		 */
1304
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1305
		jetpack_register_genericons();
1306
1307
		/**
1308
		 * Register the social logos
1309
		 */
1310
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1311
		jetpack_register_social_logos();
1312
1313 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1314
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1315
		}
1316
	}
1317
1318
	/**
1319
	 * Guess locale from language code.
1320
	 *
1321
	 * @param string $lang Language code.
1322
	 * @return string|bool
1323
	 */
1324 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1325
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1326
			return 'en_US';
1327
		}
1328
1329
		if ( ! class_exists( 'GP_Locales' ) ) {
1330
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1331
				return false;
1332
			}
1333
1334
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1335
		}
1336
1337
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1338
			// WP.com: get_locale() returns 'it'
1339
			$locale = GP_Locales::by_slug( $lang );
1340
		} else {
1341
			// Jetpack: get_locale() returns 'it_IT';
1342
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1343
		}
1344
1345
		if ( ! $locale ) {
1346
			return false;
1347
		}
1348
1349
		if ( empty( $locale->facebook_locale ) ) {
1350
			if ( empty( $locale->wp_locale ) ) {
1351
				return false;
1352
			} else {
1353
				// Facebook SDK is smart enough to fall back to en_US if a
1354
				// locale isn't supported. Since supported Facebook locales
1355
				// can fall out of sync, we'll attempt to use the known
1356
				// wp_locale value and rely on said fallback.
1357
				return $locale->wp_locale;
1358
			}
1359
		}
1360
1361
		return $locale->facebook_locale;
1362
	}
1363
1364
	/**
1365
	 * Get the locale.
1366
	 *
1367
	 * @return string|bool
1368
	 */
1369
	function get_locale() {
1370
		$locale = $this->guess_locale_from_lang( get_locale() );
1371
1372
		if ( ! $locale ) {
1373
			$locale = 'en_US';
1374
		}
1375
1376
		return $locale;
1377
	}
1378
1379
	/**
1380
	 * Return the network_site_url so that .com knows what network this site is a part of.
1381
	 *
1382
	 * @param  bool $option
1383
	 * @return string
1384
	 */
1385
	public function jetpack_main_network_site_option( $option ) {
1386
		return network_site_url();
1387
	}
1388
	/**
1389
	 * Network Name.
1390
	 */
1391
	static function network_name( $option = null ) {
1392
		global $current_site;
1393
		return $current_site->site_name;
1394
	}
1395
	/**
1396
	 * Does the network allow new user and site registrations.
1397
	 *
1398
	 * @return string
1399
	 */
1400
	static function network_allow_new_registrations( $option = null ) {
1401
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1402
	}
1403
	/**
1404
	 * Does the network allow admins to add new users.
1405
	 *
1406
	 * @return boolian
1407
	 */
1408
	static function network_add_new_users( $option = null ) {
1409
		return (bool) get_site_option( 'add_new_users' );
1410
	}
1411
	/**
1412
	 * File upload psace left per site in MB.
1413
	 *  -1 means NO LIMIT.
1414
	 *
1415
	 * @return number
1416
	 */
1417
	static function network_site_upload_space( $option = null ) {
1418
		// value in MB
1419
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1420
	}
1421
1422
	/**
1423
	 * Network allowed file types.
1424
	 *
1425
	 * @return string
1426
	 */
1427
	static function network_upload_file_types( $option = null ) {
1428
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1429
	}
1430
1431
	/**
1432
	 * Maximum file upload size set by the network.
1433
	 *
1434
	 * @return number
1435
	 */
1436
	static function network_max_upload_file_size( $option = null ) {
1437
		// value in KB
1438
		return get_site_option( 'fileupload_maxk', 300 );
1439
	}
1440
1441
	/**
1442
	 * Lets us know if a site allows admins to manage the network.
1443
	 *
1444
	 * @return array
1445
	 */
1446
	static function network_enable_administration_menus( $option = null ) {
1447
		return get_site_option( 'menu_items' );
1448
	}
1449
1450
	/**
1451
	 * If a user has been promoted to or demoted from admin, we need to clear the
1452
	 * jetpack_other_linked_admins transient.
1453
	 *
1454
	 * @since 4.3.2
1455
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1456
	 *
1457
	 * @param int    $user_id   The user ID whose role changed.
1458
	 * @param string $role      The new role.
1459
	 * @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...
1460
	 */
1461
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1462
		if ( 'administrator' == $role
1463
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1464
			|| is_null( $old_roles )
1465
		) {
1466
			delete_transient( 'jetpack_other_linked_admins' );
1467
		}
1468
	}
1469
1470
	/**
1471
	 * Checks to see if there are any other users available to become primary
1472
	 * Users must both:
1473
	 * - Be linked to wpcom
1474
	 * - Be an admin
1475
	 *
1476
	 * @return mixed False if no other users are linked, Int if there are.
1477
	 */
1478
	static function get_other_linked_admins() {
1479
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1480
1481
		if ( false === $other_linked_users ) {
1482
			$admins = get_users( array( 'role' => 'administrator' ) );
1483
			if ( count( $admins ) > 1 ) {
1484
				$available = array();
1485
				foreach ( $admins as $admin ) {
1486
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1487
						$available[] = $admin->ID;
1488
					}
1489
				}
1490
1491
				$count_connected_admins = count( $available );
1492
				if ( count( $available ) > 1 ) {
1493
					$other_linked_users = $count_connected_admins;
1494
				} else {
1495
					$other_linked_users = 0;
1496
				}
1497
			} else {
1498
				$other_linked_users = 0;
1499
			}
1500
1501
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1502
		}
1503
1504
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1505
	}
1506
1507
	/**
1508
	 * Return whether we are dealing with a multi network setup or not.
1509
	 * The reason we are type casting this is because we want to avoid the situation where
1510
	 * the result is false since when is_main_network_option return false it cases
1511
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1512
	 * database which could be set to anything as opposed to what this function returns.
1513
	 *
1514
	 * @param  bool $option
1515
	 *
1516
	 * @return boolean
1517
	 */
1518
	public function is_main_network_option( $option ) {
1519
		// return '1' or ''
1520
		return (string) (bool) self::is_multi_network();
1521
	}
1522
1523
	/**
1524
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1525
	 *
1526
	 * @param  string $option
1527
	 * @return boolean
1528
	 */
1529
	public function is_multisite( $option ) {
1530
		return (string) (bool) is_multisite();
1531
	}
1532
1533
	/**
1534
	 * Implemented since there is no core is multi network function
1535
	 * Right now there is no way to tell if we which network is the dominant network on the system
1536
	 *
1537
	 * @since  3.3
1538
	 * @return boolean
1539
	 */
1540 View Code Duplication
	public static function is_multi_network() {
1541
		global  $wpdb;
1542
1543
		// if we don't have a multi site setup no need to do any more
1544
		if ( ! is_multisite() ) {
1545
			return false;
1546
		}
1547
1548
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1549
		if ( $num_sites > 1 ) {
1550
			return true;
1551
		} else {
1552
			return false;
1553
		}
1554
	}
1555
1556
	/**
1557
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1558
	 *
1559
	 * @return null
1560
	 */
1561
	function update_jetpack_main_network_site_option() {
1562
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1563
	}
1564
	/**
1565
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1566
	 */
1567
	function update_jetpack_network_settings() {
1568
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1569
		// Only sync this info for the main network site.
1570
	}
1571
1572
	/**
1573
	 * Get back if the current site is single user site.
1574
	 *
1575
	 * @return bool
1576
	 */
1577 View Code Duplication
	public static function is_single_user_site() {
1578
		global $wpdb;
1579
1580
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1581
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1582
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1583
		}
1584
		return 1 === (int) $some_users;
1585
	}
1586
1587
	/**
1588
	 * Returns true if the site has file write access false otherwise.
1589
	 *
1590
	 * @return string ( '1' | '0' )
1591
	 **/
1592
	public static function file_system_write_access() {
1593
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1594
			require_once ABSPATH . 'wp-admin/includes/file.php';
1595
		}
1596
1597
		require_once ABSPATH . 'wp-admin/includes/template.php';
1598
1599
		$filesystem_method = get_filesystem_method();
1600
		if ( $filesystem_method === 'direct' ) {
1601
			return 1;
1602
		}
1603
1604
		ob_start();
1605
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1606
		ob_end_clean();
1607
		if ( $filesystem_credentials_are_stored ) {
1608
			return 1;
1609
		}
1610
		return 0;
1611
	}
1612
1613
	/**
1614
	 * Finds out if a site is using a version control system.
1615
	 *
1616
	 * @return string ( '1' | '0' )
1617
	 **/
1618
	public static function is_version_controlled() {
1619
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1620
		return (string) (int) Functions::is_version_controlled();
1621
	}
1622
1623
	/**
1624
	 * Determines whether the current theme supports featured images or not.
1625
	 *
1626
	 * @return string ( '1' | '0' )
1627
	 */
1628
	public static function featured_images_enabled() {
1629
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1630
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1631
	}
1632
1633
	/**
1634
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1635
	 *
1636
	 * @deprecated 4.7 use get_avatar_url instead.
1637
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1638
	 * @param int               $size Size of the avatar image
1639
	 * @param string            $default URL to a default image to use if no avatar is available
1640
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1641
	 *
1642
	 * @return array
1643
	 */
1644
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1645
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1646
		return get_avatar_url(
1647
			$id_or_email,
1648
			array(
1649
				'size'          => $size,
1650
				'default'       => $default,
1651
				'force_default' => $force_display,
1652
			)
1653
		);
1654
	}
1655
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1656
	/**
1657
	 * jetpack_updates is saved in the following schema:
1658
	 *
1659
	 * array (
1660
	 *      'plugins'                       => (int) Number of plugin updates available.
1661
	 *      'themes'                        => (int) Number of theme updates available.
1662
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1663
	 *      'translations'                  => (int) Number of translation updates available.
1664
	 *      'total'                         => (int) Total of all available updates.
1665
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1666
	 * )
1667
	 *
1668
	 * @return array
1669
	 */
1670
	public static function get_updates() {
1671
		$update_data = wp_get_update_data();
1672
1673
		// Stores the individual update counts as well as the total count.
1674
		if ( isset( $update_data['counts'] ) ) {
1675
			$updates = $update_data['counts'];
1676
		}
1677
1678
		// If we need to update WordPress core, let's find the latest version number.
1679 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1680
			$cur = get_preferred_from_update_core();
1681
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1682
				$updates['wp_update_version'] = $cur->current;
1683
			}
1684
		}
1685
		return isset( $updates ) ? $updates : array();
1686
	}
1687
	// phpcs:enable
1688
1689
	public static function get_update_details() {
1690
		$update_details = array(
1691
			'update_core'    => get_site_transient( 'update_core' ),
1692
			'update_plugins' => get_site_transient( 'update_plugins' ),
1693
			'update_themes'  => get_site_transient( 'update_themes' ),
1694
		);
1695
		return $update_details;
1696
	}
1697
1698
	public static function refresh_update_data() {
1699
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1700
1701
	}
1702
1703
	public static function refresh_theme_data() {
1704
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1705
	}
1706
1707
	/**
1708
	 * Is Jetpack active?
1709
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1710
	 *
1711
	 * This method is deprecated since 9.6.0. Please use one of the methods provided by the Manager class in the Connection package,
1712
	 * or Jetpack::is_connection_ready if you want to know when the Jetpack plugin starts considering the connection ready to be used.
1713
	 *
1714
	 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
1715
	 *
1716
	 * @deprecated 9.6.0
1717
	 *
1718
	 * @return bool
1719
	 */
1720
	public static function is_active() {
1721
		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...
1722
	}
1723
1724
	/**
1725
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1726
	 *
1727
	 * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1728
	 * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1729
	 * users and this option will be available by default for everybody.
1730
	 *
1731
	 * @since 9.6.0
1732
	 * @since 9.7.0 returns is_connected in all cases and adds filter to the returned value
1733
	 *
1734
	 * @return bool is the site connection ready to be used?
1735
	 */
1736
	public static function is_connection_ready() {
1737
		/**
1738
		 * Allows filtering whether the connection is ready to be used. If true, this will enable the Jetpack UI and modules
1739
		 *
1740
		 * Modules will be enabled depending on the connection status and if the module requires a connection or user connection.
1741
		 *
1742
		 * @since 9.7.0
1743
		 *
1744
		 * @param bool                                  $is_connection_ready Is the connection ready?
1745
		 * @param Automattic\Jetpack\Connection\Manager $connection_manager Instance of the Manager class, can be used to check the connection status.
1746
		 */
1747
		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...
1748
	}
1749
1750
	/**
1751
	 * Make an API call to WordPress.com for plan status
1752
	 *
1753
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1754
	 *
1755
	 * @return bool True if plan is updated, false if no update
1756
	 */
1757
	public static function refresh_active_plan_from_wpcom() {
1758
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1759
		return Jetpack_Plan::refresh_from_wpcom();
1760
	}
1761
1762
	/**
1763
	 * Get the plan that this Jetpack site is currently using
1764
	 *
1765
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1766
	 * @return array Active Jetpack plan details.
1767
	 */
1768
	public static function get_active_plan() {
1769
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1770
		return Jetpack_Plan::get();
1771
	}
1772
1773
	/**
1774
	 * Determine whether the active plan supports a particular feature
1775
	 *
1776
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1777
	 * @return bool True if plan supports feature, false if not.
1778
	 */
1779
	public static function active_plan_supports( $feature ) {
1780
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1781
		return Jetpack_Plan::supports( $feature );
1782
	}
1783
1784
	/**
1785
	 * Deprecated: Is Jetpack in development (offline) mode?
1786
	 *
1787
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1788
	 * and themes still use it, and we do not want to flood them with notices.
1789
	 *
1790
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1791
	 *
1792
	 * @deprecated since 8.0.
1793
	 */
1794
	public static function is_development_mode() {
1795
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1796
		return ( new Status() )->is_offline_mode();
1797
	}
1798
1799
	/**
1800
	 * Whether the site is currently onboarding or not.
1801
	 * A site is considered as being onboarded if it currently has an onboarding token.
1802
	 *
1803
	 * @since 5.8
1804
	 *
1805
	 * @access public
1806
	 * @static
1807
	 *
1808
	 * @return bool True if the site is currently onboarding, false otherwise
1809
	 */
1810
	public static function is_onboarding() {
1811
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1812
	}
1813
1814
	/**
1815
	 * Determines reason for Jetpack offline mode.
1816
	 */
1817
	public static function development_mode_trigger_text() {
1818
		$status = new Status();
1819
1820
		if ( ! $status->is_offline_mode() ) {
1821
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1822
		}
1823
1824
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1825
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1826
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1827
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1828
		} elseif ( $status->is_local_site() ) {
1829
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1830
			/** This filter is documented in packages/status/src/class-status.php */
1831
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1832
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1833
		} else {
1834
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1835
		}
1836
1837
		return $notice;
1838
1839
	}
1840
	/**
1841
	 * Get Jetpack offline mode notice text and notice class.
1842
	 *
1843
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1844
	 */
1845
	public static function show_development_mode_notice() {
1846 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1847
			$notice = sprintf(
1848
				/* translators: %s is a URL */
1849
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1850
				Redirect::get_url( 'jetpack-support-development-mode' )
1851
			);
1852
1853
			$notice .= ' ' . self::development_mode_trigger_text();
1854
1855
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1856
		}
1857
1858
		// Throw up a notice if using a development version and as for feedback.
1859
		if ( self::is_development_version() ) {
1860
			/* translators: %s is a URL */
1861
			$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' ) );
1862
1863
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1864
		}
1865
		// Throw up a notice if using staging mode
1866 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1867
			/* translators: %s is a URL */
1868
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1869
1870
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1871
		}
1872
	}
1873
1874
	/**
1875
	 * Whether Jetpack's version maps to a public release, or a development version.
1876
	 */
1877
	public static function is_development_version() {
1878
		/**
1879
		 * Allows filtering whether this is a development version of Jetpack.
1880
		 *
1881
		 * This filter is especially useful for tests.
1882
		 *
1883
		 * @since 4.3.0
1884
		 *
1885
		 * @param bool $development_version Is this a develoment version of Jetpack?
1886
		 */
1887
		return (bool) apply_filters(
1888
			'jetpack_development_version',
1889
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1890
		);
1891
	}
1892
1893
	/**
1894
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1895
	 */
1896
	public static function is_user_connected( $user_id = false ) {
1897
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1898
		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...
1899
	}
1900
1901
	/**
1902
	 * Get the wpcom user data of the current|specified connected user.
1903
	 */
1904
	public static function get_connected_user_data( $user_id = null ) {
1905
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1906
		return self::connection()->get_connected_user_data( $user_id );
1907
	}
1908
1909
	/**
1910
	 * Get the wpcom email of the current|specified connected user.
1911
	 */
1912
	public static function get_connected_user_email( $user_id = null ) {
1913
		if ( ! $user_id ) {
1914
			$user_id = get_current_user_id();
1915
		}
1916
1917
		$xml = new Jetpack_IXR_Client(
1918
			array(
1919
				'user_id' => $user_id,
1920
			)
1921
		);
1922
		$xml->query( 'wpcom.getUserEmail' );
1923
		if ( ! $xml->isError() ) {
1924
			return $xml->getResponse();
1925
		}
1926
		return false;
1927
	}
1928
1929
	/**
1930
	 * Get the wpcom email of the master user.
1931
	 */
1932
	public static function get_master_user_email() {
1933
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1934
		if ( $master_user_id ) {
1935
			return self::get_connected_user_email( $master_user_id );
1936
		}
1937
		return '';
1938
	}
1939
1940
	/**
1941
	 * Whether the current user is the connection owner.
1942
	 *
1943
	 * @deprecated since 7.7
1944
	 *
1945
	 * @return bool Whether the current user is the connection owner.
1946
	 */
1947
	public function current_user_is_connection_owner() {
1948
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1949
		return self::connection()->is_connection_owner();
1950
	}
1951
1952
	/**
1953
	 * Gets current user IP address.
1954
	 *
1955
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1956
	 *
1957
	 * @return string                  Current user IP address.
1958
	 */
1959
	public static function current_user_ip( $check_all_headers = false ) {
1960
		if ( $check_all_headers ) {
1961
			foreach ( array(
1962
				'HTTP_CF_CONNECTING_IP',
1963
				'HTTP_CLIENT_IP',
1964
				'HTTP_X_FORWARDED_FOR',
1965
				'HTTP_X_FORWARDED',
1966
				'HTTP_X_CLUSTER_CLIENT_IP',
1967
				'HTTP_FORWARDED_FOR',
1968
				'HTTP_FORWARDED',
1969
				'HTTP_VIA',
1970
			) as $key ) {
1971
				if ( ! empty( $_SERVER[ $key ] ) ) {
1972
					return $_SERVER[ $key ];
1973
				}
1974
			}
1975
		}
1976
1977
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1978
	}
1979
1980
	/**
1981
	 * Synchronize connected user role changes
1982
	 */
1983
	function user_role_change( $user_id ) {
1984
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1985
		Users::user_role_change( $user_id );
1986
	}
1987
1988
	/**
1989
	 * Loads the currently active modules.
1990
	 */
1991
	public static function load_modules() {
1992
		$is_offline_mode = ( new Status() )->is_offline_mode();
1993
		if (
1994
			! self::is_connection_ready()
1995
			&& ! $is_offline_mode
1996
			&& ! self::is_onboarding()
1997
			&& (
1998
				! is_multisite()
1999
				|| ! get_site_option( 'jetpack_protect_active' )
2000
			)
2001
		) {
2002
			return;
2003
		}
2004
2005
		$version = Jetpack_Options::get_option( 'version' );
2006 View Code Duplication
		if ( ! $version ) {
2007
			$version = $old_version = JETPACK__VERSION . ':' . time();
2008
			/** This action is documented in class.jetpack.php */
2009
			do_action( 'updating_jetpack_version', $version, false );
2010
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2011
		}
2012
		list( $version ) = explode( ':', $version );
2013
2014
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
2015
2016
		$modules_data = array();
2017
2018
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
2019
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
2020
			$updated_modules = array();
2021
			foreach ( $modules as $module ) {
2022
				$modules_data[ $module ] = self::get_module( $module );
2023
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
2024
					continue;
2025
				}
2026
2027
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2028
					continue;
2029
				}
2030
2031
				$updated_modules[] = $module;
2032
			}
2033
2034
			$modules = array_diff( $modules, $updated_modules );
2035
		}
2036
2037
		$is_userless = self::connection()->is_userless();
2038
2039
		foreach ( $modules as $index => $module ) {
2040
			// If we're in offline/user-less mode, disable modules requiring a connection/user connection.
2041
			if ( $is_offline_mode || $is_userless ) {
2042
				// Prime the pump if we need to
2043
				if ( empty( $modules_data[ $module ] ) ) {
2044
					$modules_data[ $module ] = self::get_module( $module );
2045
				}
2046
				// If the module requires a connection, but we're in local mode, don't include it.
2047
				if ( $is_offline_mode && $modules_data[ $module ]['requires_connection'] ) {
2048
					continue;
2049
				}
2050
2051
				if ( $is_userless && $modules_data[ $module ]['requires_user_connection'] ) {
2052
					continue;
2053
				}
2054
			}
2055
2056
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2057
				continue;
2058
			}
2059
2060
			if ( ! include_once self::get_module_path( $module ) ) {
2061
				unset( $modules[ $index ] );
2062
				self::update_active_modules( array_values( $modules ) );
2063
				continue;
2064
			}
2065
2066
			/**
2067
			 * Fires when a specific module is loaded.
2068
			 * The dynamic part of the hook, $module, is the module slug.
2069
			 *
2070
			 * @since 1.1.0
2071
			 */
2072
			do_action( 'jetpack_module_loaded_' . $module );
2073
		}
2074
2075
		/**
2076
		 * Fires when all the modules are loaded.
2077
		 *
2078
		 * @since 1.1.0
2079
		 */
2080
		do_action( 'jetpack_modules_loaded' );
2081
2082
		// 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.
2083
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2084
	}
2085
2086
	/**
2087
	 * Check if Jetpack's REST API compat file should be included
2088
	 *
2089
	 * @action plugins_loaded
2090
	 * @return null
2091
	 */
2092
	public function check_rest_api_compat() {
2093
		/**
2094
		 * Filters the list of REST API compat files to be included.
2095
		 *
2096
		 * @since 2.2.5
2097
		 *
2098
		 * @param array $args Array of REST API compat files to include.
2099
		 */
2100
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2101
2102
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2103
			require_once $_jetpack_rest_api_compat_include;
2104
		}
2105
	}
2106
2107
	/**
2108
	 * Gets all plugins currently active in values, regardless of whether they're
2109
	 * traditionally activated or network activated.
2110
	 *
2111
	 * @todo Store the result in core's object cache maybe?
2112
	 */
2113
	public static function get_active_plugins() {
2114
		$active_plugins = (array) get_option( 'active_plugins', array() );
2115
2116
		if ( is_multisite() ) {
2117
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2118
			// whereas active_plugins stores them in the values.
2119
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2120
			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...
2121
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2122
			}
2123
		}
2124
2125
		sort( $active_plugins );
2126
2127
		return array_unique( $active_plugins );
2128
	}
2129
2130
	/**
2131
	 * Gets and parses additional plugin data to send with the heartbeat data
2132
	 *
2133
	 * @since 3.8.1
2134
	 *
2135
	 * @return array Array of plugin data
2136
	 */
2137
	public static function get_parsed_plugin_data() {
2138
		if ( ! function_exists( 'get_plugins' ) ) {
2139
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2140
		}
2141
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2142
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2143
		$active_plugins = self::get_active_plugins();
2144
2145
		$plugins = array();
2146
		foreach ( $all_plugins as $path => $plugin_data ) {
2147
			$plugins[ $path ] = array(
2148
				'is_active' => in_array( $path, $active_plugins ),
2149
				'file'      => $path,
2150
				'name'      => $plugin_data['Name'],
2151
				'version'   => $plugin_data['Version'],
2152
				'author'    => $plugin_data['Author'],
2153
			);
2154
		}
2155
2156
		return $plugins;
2157
	}
2158
2159
	/**
2160
	 * Gets and parses theme data to send with the heartbeat data
2161
	 *
2162
	 * @since 3.8.1
2163
	 *
2164
	 * @return array Array of theme data
2165
	 */
2166
	public static function get_parsed_theme_data() {
2167
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2168
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2169
2170
		$themes = array();
2171
		foreach ( $all_themes as $slug => $theme_data ) {
2172
			$theme_headers = array();
2173
			foreach ( $header_keys as $header_key ) {
2174
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2175
			}
2176
2177
			$themes[ $slug ] = array(
2178
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2179
				'slug'            => $slug,
2180
				'theme_root'      => $theme_data->get_theme_root_uri(),
2181
				'parent'          => $theme_data->parent(),
2182
				'headers'         => $theme_headers,
2183
			);
2184
		}
2185
2186
		return $themes;
2187
	}
2188
2189
	/**
2190
	 * Checks whether a specific plugin is active.
2191
	 *
2192
	 * We don't want to store these in a static variable, in case
2193
	 * there are switch_to_blog() calls involved.
2194
	 */
2195
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2196
		return in_array( $plugin, self::get_active_plugins() );
2197
	}
2198
2199
	/**
2200
	 * Check if Jetpack's Open Graph tags should be used.
2201
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2202
	 *
2203
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2204
	 * @action plugins_loaded
2205
	 * @return null
2206
	 */
2207
	public function check_open_graph() {
2208
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2209
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2210
		}
2211
2212
		$active_plugins = self::get_active_plugins();
2213
2214
		if ( ! empty( $active_plugins ) ) {
2215
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2216
				if ( in_array( $plugin, $active_plugins ) ) {
2217
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2218
					break;
2219
				}
2220
			}
2221
		}
2222
2223
		/**
2224
		 * Allow the addition of Open Graph Meta Tags to all pages.
2225
		 *
2226
		 * @since 2.0.3
2227
		 *
2228
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2229
		 */
2230
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2231
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2232
		}
2233
	}
2234
2235
	/**
2236
	 * Check if Jetpack's Twitter tags should be used.
2237
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2238
	 *
2239
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2240
	 * @action plugins_loaded
2241
	 * @return null
2242
	 */
2243
	public function check_twitter_tags() {
2244
2245
		$active_plugins = self::get_active_plugins();
2246
2247
		if ( ! empty( $active_plugins ) ) {
2248
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2249
				if ( in_array( $plugin, $active_plugins ) ) {
2250
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2251
					break;
2252
				}
2253
			}
2254
		}
2255
2256
		/**
2257
		 * Allow Twitter Card Meta tags to be disabled.
2258
		 *
2259
		 * @since 2.6.0
2260
		 *
2261
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2262
		 */
2263
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2264
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2265
		}
2266
	}
2267
2268
	/**
2269
	 * Allows plugins to submit security reports.
2270
	 *
2271
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2272
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2273
	 * @param array  $args         See definitions above
2274
	 */
2275
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2276
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2277
	}
2278
2279
	/* Jetpack Options API */
2280
2281
	public static function get_option_names( $type = 'compact' ) {
2282
		return Jetpack_Options::get_option_names( $type );
2283
	}
2284
2285
	/**
2286
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2287
	 *
2288
	 * @param string $name    Option name
2289
	 * @param mixed  $default (optional)
2290
	 */
2291
	public static function get_option( $name, $default = false ) {
2292
		return Jetpack_Options::get_option( $name, $default );
2293
	}
2294
2295
	/**
2296
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2297
	 *
2298
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2299
	 * @param string $name  Option name
2300
	 * @param mixed  $value Option value
2301
	 */
2302
	public static function update_option( $name, $value ) {
2303
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2304
		return Jetpack_Options::update_option( $name, $value );
2305
	}
2306
2307
	/**
2308
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2309
	 *
2310
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2311
	 * @param array $array array( option name => option value, ... )
2312
	 */
2313
	public static function update_options( $array ) {
2314
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2315
		return Jetpack_Options::update_options( $array );
2316
	}
2317
2318
	/**
2319
	 * Deletes the given option.  May be passed multiple option names as an array.
2320
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2321
	 *
2322
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2323
	 * @param string|array $names
2324
	 */
2325
	public static function delete_option( $names ) {
2326
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2327
		return Jetpack_Options::delete_option( $names );
2328
	}
2329
2330
	/**
2331
	 * Enters a user token into the user_tokens option
2332
	 *
2333
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2334
	 *
2335
	 * @param int    $user_id The user id.
2336
	 * @param string $token The user token.
2337
	 * @param bool   $is_master_user Whether the user is the master user.
2338
	 * @return bool
2339
	 */
2340
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2341
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2342
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2343
	}
2344
2345
	/**
2346
	 * Returns an array of all PHP files in the specified absolute path.
2347
	 * Equivalent to glob( "$absolute_path/*.php" ).
2348
	 *
2349
	 * @param string $absolute_path The absolute path of the directory to search.
2350
	 * @return array Array of absolute paths to the PHP files.
2351
	 */
2352
	public static function glob_php( $absolute_path ) {
2353
		if ( function_exists( 'glob' ) ) {
2354
			return glob( "$absolute_path/*.php" );
2355
		}
2356
2357
		$absolute_path = untrailingslashit( $absolute_path );
2358
		$files         = array();
2359
		if ( ! $dir = @opendir( $absolute_path ) ) {
2360
			return $files;
2361
		}
2362
2363
		while ( false !== $file = readdir( $dir ) ) {
2364
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2365
				continue;
2366
			}
2367
2368
			$file = "$absolute_path/$file";
2369
2370
			if ( ! is_file( $file ) ) {
2371
				continue;
2372
			}
2373
2374
			$files[] = $file;
2375
		}
2376
2377
		closedir( $dir );
2378
2379
		return $files;
2380
	}
2381
2382
	public static function activate_new_modules( $redirect = false ) {
2383
		if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2384
			return;
2385
		}
2386
2387
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2388 View Code Duplication
		if ( ! $jetpack_old_version ) {
2389
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2390
			/** This action is documented in class.jetpack.php */
2391
			do_action( 'updating_jetpack_version', $version, false );
2392
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2393
		}
2394
2395
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2396
2397
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2398
			return;
2399
		}
2400
2401
		$active_modules     = self::get_active_modules();
2402
		$reactivate_modules = array();
2403
		foreach ( $active_modules as $active_module ) {
2404
			$module = self::get_module( $active_module );
2405
			if ( ! isset( $module['changed'] ) ) {
2406
				continue;
2407
			}
2408
2409
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2410
				continue;
2411
			}
2412
2413
			$reactivate_modules[] = $active_module;
2414
			self::deactivate_module( $active_module );
2415
		}
2416
2417
		$new_version = JETPACK__VERSION . ':' . time();
2418
		/** This action is documented in class.jetpack.php */
2419
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2420
		Jetpack_Options::update_options(
2421
			array(
2422
				'version'     => $new_version,
2423
				'old_version' => $jetpack_old_version,
2424
			)
2425
		);
2426
2427
		self::state( 'message', 'modules_activated' );
2428
2429
		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...
2430
2431
		if ( $redirect ) {
2432
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2433
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2434
				$page = $_GET['page'];
2435
			}
2436
2437
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2438
			exit;
2439
		}
2440
	}
2441
2442
	/**
2443
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2444
	 * Make sure to tuck away module "library" files in a sub-directory.
2445
	 *
2446
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2447
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2448
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2449
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2450
	 *
2451
	 * @return array $modules Array of module slugs
2452
	 */
2453
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2454
		static $modules = null;
2455
2456
		if ( ! isset( $modules ) ) {
2457
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2458
			// Use the cache if we're on the front-end and it's available...
2459
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2460
				$modules = $available_modules_option[ JETPACK__VERSION ];
2461
			} else {
2462
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2463
2464
				$modules = array();
2465
2466
				foreach ( $files as $file ) {
2467
					if ( ! $headers = self::get_module( $file ) ) {
2468
						continue;
2469
					}
2470
2471
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2472
				}
2473
2474
				Jetpack_Options::update_option(
2475
					'available_modules',
2476
					array(
2477
						JETPACK__VERSION => $modules,
2478
					)
2479
				);
2480
			}
2481
		}
2482
2483
		/**
2484
		 * Filters the array of modules available to be activated.
2485
		 *
2486
		 * @since 2.4.0
2487
		 *
2488
		 * @param array $modules Array of available modules.
2489
		 * @param string $min_version Minimum version number required to use modules.
2490
		 * @param string $max_version Maximum version number required to use modules.
2491
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2492
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2493
		 */
2494
		$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...
2495
2496
		if ( ! $min_version && ! $max_version && is_null( $requires_connection ) && is_null( $requires_user_connection ) ) {
2497
			return array_keys( $mods );
2498
		}
2499
2500
		$r = array();
2501
		foreach ( $mods as $slug => $introduced ) {
2502
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2503
				continue;
2504
			}
2505
2506
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2507
				continue;
2508
			}
2509
2510
			$mod_details = self::get_module( $slug );
2511
2512
			if ( null !== $requires_connection && (bool) $requires_connection !== $mod_details['requires_connection'] ) {
2513
				continue;
2514
			}
2515
2516
			if ( null !== $requires_user_connection && (bool) $requires_user_connection !== $mod_details['requires_user_connection'] ) {
2517
				continue;
2518
			}
2519
2520
			$r[] = $slug;
2521
		}
2522
2523
		return $r;
2524
	}
2525
2526
	/**
2527
	 * Get default modules loaded on activation.
2528
	 *
2529
	 * @param bool|string $min_version Onlu return modules introduced in this version or later. Default is false, do not filter.
2530
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2531
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2532
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2533
	 *
2534
	 * @return array $modules Array of module slugs
2535
	 */
2536
	public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2537
		$return = array();
2538
2539
		foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2540
			$module_data = self::get_module( $module );
2541
2542
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2543
				case 'yes':
2544
					$return[] = $module;
2545
					break;
2546
				case 'public':
2547
					if ( Jetpack_Options::get_option( 'public' ) ) {
2548
						$return[] = $module;
2549
					}
2550
					break;
2551
				case 'no':
2552
				default:
2553
					break;
2554
			}
2555
		}
2556
		/**
2557
		 * Filters the array of default modules.
2558
		 *
2559
		 * @since 2.5.0
2560
		 *
2561
		 * @param array $return Array of default modules.
2562
		 * @param string $min_version Minimum version number required to use modules.
2563
		 * @param string $max_version Maximum version number required to use modules.
2564
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2565
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2566
		 */
2567
		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...
2568
	}
2569
2570
	/**
2571
	 * Checks activated modules during auto-activation to determine
2572
	 * if any of those modules are being deprecated.  If so, close
2573
	 * them out, and add any replacement modules.
2574
	 *
2575
	 * Runs at priority 99 by default.
2576
	 *
2577
	 * This is run late, so that it can still activate a module if
2578
	 * the new module is a replacement for another that the user
2579
	 * currently has active, even if something at the normal priority
2580
	 * would kibosh everything.
2581
	 *
2582
	 * @since 2.6
2583
	 * @uses jetpack_get_default_modules filter
2584
	 * @param array $modules
2585
	 * @return array
2586
	 */
2587
	function handle_deprecated_modules( $modules ) {
2588
		$deprecated_modules = array(
2589
			'debug'            => null,  // Closed out and moved to the debugger library.
2590
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2591
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2592
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2593
		);
2594
2595
		// Don't activate SSO if they never completed activating WPCC.
2596
		if ( self::is_module_active( 'wpcc' ) ) {
2597
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2598
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2599
				$deprecated_modules['wpcc'] = null;
2600
			}
2601
		}
2602
2603
		foreach ( $deprecated_modules as $module => $replacement ) {
2604
			if ( self::is_module_active( $module ) ) {
2605
				self::deactivate_module( $module );
2606
				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...
2607
					$modules[] = $replacement;
2608
				}
2609
			}
2610
		}
2611
2612
		return array_unique( $modules );
2613
	}
2614
2615
	/**
2616
	 * Checks activated plugins during auto-activation to determine
2617
	 * if any of those plugins are in the list with a corresponding module
2618
	 * that is not compatible with the plugin. The module will not be allowed
2619
	 * to auto-activate.
2620
	 *
2621
	 * @since 2.6
2622
	 * @uses jetpack_get_default_modules filter
2623
	 * @param array $modules
2624
	 * @return array
2625
	 */
2626
	function filter_default_modules( $modules ) {
2627
2628
		$active_plugins = self::get_active_plugins();
2629
2630
		if ( ! empty( $active_plugins ) ) {
2631
2632
			// For each module we'd like to auto-activate...
2633
			foreach ( $modules as $key => $module ) {
2634
				// If there are potential conflicts for it...
2635
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2636
					// For each potential conflict...
2637
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2638
						// If that conflicting plugin is active...
2639
						if ( in_array( $plugin, $active_plugins ) ) {
2640
							// Remove that item from being auto-activated.
2641
							unset( $modules[ $key ] );
2642
						}
2643
					}
2644
				}
2645
			}
2646
		}
2647
2648
		return $modules;
2649
	}
2650
2651
	/**
2652
	 * Extract a module's slug from its full path.
2653
	 */
2654
	public static function get_module_slug( $file ) {
2655
		return str_replace( '.php', '', basename( $file ) );
2656
	}
2657
2658
	/**
2659
	 * Generate a module's path from its slug.
2660
	 */
2661
	public static function get_module_path( $slug ) {
2662
		/**
2663
		 * Filters the path of a modules.
2664
		 *
2665
		 * @since 7.4.0
2666
		 *
2667
		 * @param array $return The absolute path to a module's root php file
2668
		 * @param string $slug The module slug
2669
		 */
2670
		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...
2671
	}
2672
2673
	/**
2674
	 * Load module data from module file. Headers differ from WordPress
2675
	 * plugin headers to avoid them being identified as standalone
2676
	 * plugins on the WordPress plugins page.
2677
	 */
2678
	public static function get_module( $module ) {
2679
		$headers = array(
2680
			'name'                      => 'Module Name',
2681
			'description'               => 'Module Description',
2682
			'sort'                      => 'Sort Order',
2683
			'recommendation_order'      => 'Recommendation Order',
2684
			'introduced'                => 'First Introduced',
2685
			'changed'                   => 'Major Changes In',
2686
			'deactivate'                => 'Deactivate',
2687
			'free'                      => 'Free',
2688
			'requires_connection'       => 'Requires Connection',
2689
			'requires_user_connection'  => 'Requires User Connection',
2690
			'auto_activate'             => 'Auto Activate',
2691
			'module_tags'               => 'Module Tags',
2692
			'feature'                   => 'Feature',
2693
			'additional_search_queries' => 'Additional Search Queries',
2694
			'plan_classes'              => 'Plans',
2695
		);
2696
2697
		static $modules_details;
2698
		$file = self::get_module_path( self::get_module_slug( $module ) );
2699
2700
		if ( isset( $modules_details[ $module ] ) ) {
2701
			$mod = $modules_details[ $module ];
2702
		} else {
2703
2704
			$mod = self::get_file_data( $file, $headers );
2705
			if ( empty( $mod['name'] ) ) {
2706
				return false;
2707
			}
2708
2709
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2710
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2711
			$mod['deactivate']               = empty( $mod['deactivate'] );
2712
			$mod['free']                     = empty( $mod['free'] );
2713
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2714
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2715
2716
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2717
				$mod['auto_activate'] = 'No';
2718
			} else {
2719
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2720
			}
2721
2722
			if ( $mod['module_tags'] ) {
2723
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2724
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2725
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2726
			} else {
2727
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2728
			}
2729
2730 View Code Duplication
			if ( $mod['plan_classes'] ) {
2731
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2732
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2733
			} else {
2734
				$mod['plan_classes'] = array( 'free' );
2735
			}
2736
2737 View Code Duplication
			if ( $mod['feature'] ) {
2738
				$mod['feature'] = explode( ',', $mod['feature'] );
2739
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2740
			} else {
2741
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2742
			}
2743
2744
			$modules_details[ $module ] = $mod;
2745
2746
		}
2747
2748
		/**
2749
		 * Filters the feature array on a module.
2750
		 *
2751
		 * This filter allows you to control where each module is filtered: Recommended,
2752
		 * and the default "Other" listing.
2753
		 *
2754
		 * @since 3.5.0
2755
		 *
2756
		 * @param array   $mod['feature'] The areas to feature this module:
2757
		 *     'Recommended' shows on the main Jetpack admin screen.
2758
		 *     'Other' should be the default if no other value is in the array.
2759
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2760
		 * @param array   $mod All the currently assembled module data.
2761
		 */
2762
		$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...
2763
2764
		/**
2765
		 * Filter the returned data about a module.
2766
		 *
2767
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2768
		 * so please be careful.
2769
		 *
2770
		 * @since 3.6.0
2771
		 *
2772
		 * @param array   $mod    The details of the requested module.
2773
		 * @param string  $module The slug of the module, e.g. sharedaddy
2774
		 * @param string  $file   The path to the module source file.
2775
		 */
2776
		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...
2777
	}
2778
2779
	/**
2780
	 * Like core's get_file_data implementation, but caches the result.
2781
	 */
2782
	public static function get_file_data( $file, $headers ) {
2783
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2784
		$file_name = basename( $file );
2785
2786
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2787
2788
		$file_data_option = get_transient( $cache_key );
2789
2790
		if ( ! is_array( $file_data_option ) ) {
2791
			delete_transient( $cache_key );
2792
			$file_data_option = false;
2793
		}
2794
2795
		if ( false === $file_data_option ) {
2796
			$file_data_option = array();
2797
		}
2798
2799
		$key           = md5( $file_name . serialize( $headers ) );
2800
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2801
2802
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2803
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2804
			return $file_data_option[ $key ];
2805
		}
2806
2807
		$data = get_file_data( $file, $headers );
2808
2809
		$file_data_option[ $key ] = $data;
2810
2811
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2812
2813
		return $data;
2814
	}
2815
2816
	/**
2817
	 * Return translated module tag.
2818
	 *
2819
	 * @param string $tag Tag as it appears in each module heading.
2820
	 *
2821
	 * @return mixed
2822
	 */
2823
	public static function translate_module_tag( $tag ) {
2824
		return jetpack_get_module_i18n_tag( $tag );
2825
	}
2826
2827
	/**
2828
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2829
	 *
2830
	 * @since 3.9.2
2831
	 *
2832
	 * @param array $modules
2833
	 *
2834
	 * @return string|void
2835
	 */
2836
	public static function get_translated_modules( $modules ) {
2837
		foreach ( $modules as $index => $module ) {
2838
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2839
			if ( isset( $module['name'] ) ) {
2840
				$modules[ $index ]['name'] = $i18n_module['name'];
2841
			}
2842
			if ( isset( $module['description'] ) ) {
2843
				$modules[ $index ]['description']       = $i18n_module['description'];
2844
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2845
			}
2846
		}
2847
		return $modules;
2848
	}
2849
2850
	/**
2851
	 * Get a list of activated modules as an array of module slugs.
2852
	 */
2853
	public static function get_active_modules() {
2854
		$active = Jetpack_Options::get_option( 'active_modules' );
2855
2856
		if ( ! is_array( $active ) ) {
2857
			$active = array();
2858
		}
2859
2860
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2861
			$active[] = 'vaultpress';
2862
		} else {
2863
			$active = array_diff( $active, array( 'vaultpress' ) );
2864
		}
2865
2866
		// If protect is active on the main site of a multisite, it should be active on all sites.
2867
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2868
			$active[] = 'protect';
2869
		}
2870
2871
		/**
2872
		 * Allow filtering of the active modules.
2873
		 *
2874
		 * Gives theme and plugin developers the power to alter the modules that
2875
		 * are activated on the fly.
2876
		 *
2877
		 * @since 5.8.0
2878
		 *
2879
		 * @param array $active Array of active module slugs.
2880
		 */
2881
		$active = apply_filters( 'jetpack_active_modules', $active );
2882
2883
		return array_unique( $active );
2884
	}
2885
2886
	/**
2887
	 * Check whether or not a Jetpack module is active.
2888
	 *
2889
	 * @param string $module The slug of a Jetpack module.
2890
	 * @return bool
2891
	 *
2892
	 * @static
2893
	 */
2894
	public static function is_module_active( $module ) {
2895
		return in_array( $module, self::get_active_modules() );
2896
	}
2897
2898
	public static function is_module( $module ) {
2899
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2900
	}
2901
2902
	/**
2903
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2904
	 *
2905
	 * @param bool $catch True to start catching, False to stop.
2906
	 *
2907
	 * @static
2908
	 */
2909
	public static function catch_errors( $catch ) {
2910
		static $display_errors, $error_reporting;
2911
2912
		if ( $catch ) {
2913
			$display_errors  = @ini_set( 'display_errors', 1 );
2914
			$error_reporting = @error_reporting( E_ALL );
2915
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2916
		} else {
2917
			@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...
2918
			@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...
2919
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2920
		}
2921
	}
2922
2923
	/**
2924
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2925
	 */
2926
	public static function catch_errors_on_shutdown() {
2927
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2928
	}
2929
2930
	/**
2931
	 * Rewrite any string to make paths easier to read.
2932
	 *
2933
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2934
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2935
	 *
2936
	 * @param $string
2937
	 * @return mixed
2938
	 */
2939
	public static function alias_directories( $string ) {
2940
		// ABSPATH has a trailing slash.
2941
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2942
		// WP_CONTENT_DIR does not have a trailing slash.
2943
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2944
2945
		return $string;
2946
	}
2947
2948
	public static function activate_default_modules(
2949
		$min_version = false,
2950
		$max_version = false,
2951
		$other_modules = array(),
2952
		$redirect = null,
2953
		$send_state_messages = null,
2954
		$requires_connection = null,
2955
		$requires_user_connection = null
2956
	) {
2957
		$jetpack = self::init();
2958
2959
		if ( is_null( $redirect ) ) {
2960
			if (
2961
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2962
			||
2963
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2964
			||
2965
				( defined( 'WP_CLI' ) && WP_CLI )
2966
			||
2967
				( defined( 'DOING_CRON' ) && DOING_CRON )
2968
			||
2969
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2970
			) {
2971
				$redirect = false;
2972
			} elseif ( is_admin() ) {
2973
				$redirect = true;
2974
			} else {
2975
				$redirect = false;
2976
			}
2977
		}
2978
2979
		if ( is_null( $send_state_messages ) ) {
2980
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2981
		}
2982
2983
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2984
		$modules = array_merge( $other_modules, $modules );
2985
2986
		// Look for standalone plugins and disable if active.
2987
2988
		$to_deactivate = array();
2989
		foreach ( $modules as $module ) {
2990
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2991
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2992
			}
2993
		}
2994
2995
		$deactivated = array();
2996
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2997
			list( $probable_file, $probable_title ) = $deactivate_me;
2998
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2999
				$deactivated[] = $module;
3000
			}
3001
		}
3002
3003
		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...
3004
			if ( $send_state_messages ) {
3005
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
3006
			}
3007
3008
			if ( $redirect ) {
3009
				$url = add_query_arg(
3010
					array(
3011
						'action'   => 'activate_default_modules',
3012
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
3013
					),
3014
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
3015
				);
3016
				wp_safe_redirect( $url );
3017
				exit;
3018
			}
3019
		}
3020
3021
		/**
3022
		 * Fires before default modules are activated.
3023
		 *
3024
		 * @since 1.9.0
3025
		 *
3026
		 * @param string    $min_version Minimum version number required to use modules.
3027
		 * @param string    $max_version Maximum version number required to use modules.
3028
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3029
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3030
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3031
		 */
3032
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3033
3034
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3035
		if ( $send_state_messages ) {
3036
			self::restate();
3037
			self::catch_errors( true );
3038
		}
3039
3040
		$active = self::get_active_modules();
3041
3042
		foreach ( $modules as $module ) {
3043
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3044
				$active[] = $module;
3045
				self::update_active_modules( $active );
3046
				continue;
3047
			}
3048
3049
			if ( $send_state_messages && in_array( $module, $active ) ) {
3050
				$module_info = self::get_module( $module );
3051 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3052
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3053
					if ( $active_state = self::state( $state ) ) {
3054
						$active_state = explode( ',', $active_state );
3055
					} else {
3056
						$active_state = array();
3057
					}
3058
					$active_state[] = $module;
3059
					self::state( $state, implode( ',', $active_state ) );
3060
				}
3061
				continue;
3062
			}
3063
3064
			$file = self::get_module_path( $module );
3065
			if ( ! file_exists( $file ) ) {
3066
				continue;
3067
			}
3068
3069
			// we'll override this later if the plugin can be included without fatal error
3070
			if ( $redirect ) {
3071
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3072
			}
3073
3074
			if ( $send_state_messages ) {
3075
				self::state( 'error', 'module_activation_failed' );
3076
				self::state( 'module', $module );
3077
			}
3078
3079
			ob_start();
3080
			require_once $file;
3081
3082
			$active[] = $module;
3083
3084 View Code Duplication
			if ( $send_state_messages ) {
3085
3086
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3087
				if ( $active_state = self::state( $state ) ) {
3088
					$active_state = explode( ',', $active_state );
3089
				} else {
3090
					$active_state = array();
3091
				}
3092
				$active_state[] = $module;
3093
				self::state( $state, implode( ',', $active_state ) );
3094
			}
3095
3096
			self::update_active_modules( $active );
3097
3098
			ob_end_clean();
3099
		}
3100
3101
		if ( $send_state_messages ) {
3102
			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...
3103
			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...
3104
		}
3105
3106
		self::catch_errors( false );
3107
		/**
3108
		 * Fires when default modules are activated.
3109
		 *
3110
		 * @since 1.9.0
3111
		 *
3112
		 * @param string    $min_version Minimum version number required to use modules.
3113
		 * @param string    $max_version Maximum version number required to use modules.
3114
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3115
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3116
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3117
		 */
3118
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3119
	}
3120
3121
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3122
		/**
3123
		 * Fires before a module is activated.
3124
		 *
3125
		 * @since 2.6.0
3126
		 *
3127
		 * @param string $module Module slug.
3128
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3129
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3130
		 */
3131
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3132
3133
		$jetpack = self::init();
3134
3135
		if ( ! strlen( $module ) ) {
3136
			return false;
3137
		}
3138
3139
		if ( ! self::is_module( $module ) ) {
3140
			return false;
3141
		}
3142
3143
		// If it's already active, then don't do it again
3144
		$active = self::get_active_modules();
3145
		foreach ( $active as $act ) {
3146
			if ( $act == $module ) {
3147
				return true;
3148
			}
3149
		}
3150
3151
		$module_data = self::get_module( $module );
3152
3153
		$is_offline_mode = ( new Status() )->is_offline_mode();
3154
		if ( ! self::is_connection_ready() ) {
3155
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3156
				return false;
3157
			}
3158
3159
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3160
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3161
				return false;
3162
			}
3163
		}
3164
3165
		// Check and see if the old plugin is active
3166
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3167
			// Deactivate the old plugin
3168
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3169
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3170
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3171
				self::state( 'deactivated_plugins', $module );
3172
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3173
				exit;
3174
			}
3175
		}
3176
3177
		// Protect won't work with mis-configured IPs
3178
		if ( 'protect' === $module ) {
3179
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3180
			if ( ! jetpack_protect_get_ip() ) {
3181
				self::state( 'message', 'protect_misconfigured_ip' );
3182
				return false;
3183
			}
3184
		}
3185
3186
		if ( ! Jetpack_Plan::supports( $module ) ) {
3187
			return false;
3188
		}
3189
3190
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3191
		self::state( 'module', $module );
3192
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3193
3194
		self::catch_errors( true );
3195
		ob_start();
3196
		require self::get_module_path( $module );
3197
		/** This action is documented in class.jetpack.php */
3198
		do_action( 'jetpack_activate_module', $module );
3199
		$active[] = $module;
3200
		self::update_active_modules( $active );
3201
3202
		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...
3203
		ob_end_clean();
3204
		self::catch_errors( false );
3205
3206
		if ( $redirect ) {
3207
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3208
		}
3209
		if ( $exit ) {
3210
			exit;
3211
		}
3212
		return true;
3213
	}
3214
3215
	function activate_module_actions( $module ) {
3216
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3217
	}
3218
3219
	public static function deactivate_module( $module ) {
3220
		/**
3221
		 * Fires when a module is deactivated.
3222
		 *
3223
		 * @since 1.9.0
3224
		 *
3225
		 * @param string $module Module slug.
3226
		 */
3227
		do_action( 'jetpack_pre_deactivate_module', $module );
3228
3229
		$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...
3230
3231
		$active = self::get_active_modules();
3232
		$new    = array_filter( array_diff( $active, (array) $module ) );
3233
3234
		return self::update_active_modules( $new );
3235
	}
3236
3237
	public static function enable_module_configurable( $module ) {
3238
		$module = self::get_module_slug( $module );
3239
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3240
	}
3241
3242
	/**
3243
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3244
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3245
	 *
3246
	 * @param string $module Module slug
3247
	 * @return string $url module configuration URL
3248
	 */
3249
	public static function module_configuration_url( $module ) {
3250
		$module      = self::get_module_slug( $module );
3251
		$default_url = self::admin_url() . "#/settings?term=$module";
3252
		/**
3253
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3254
		 *
3255
		 * @since 6.9.0
3256
		 *
3257
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3258
		 */
3259
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3260
3261
		return $url;
3262
	}
3263
3264
	/* Installation */
3265
	public static function bail_on_activation( $message, $deactivate = true ) {
3266
		?>
3267
<!doctype html>
3268
<html>
3269
<head>
3270
<meta charset="<?php bloginfo( 'charset' ); ?>">
3271
<style>
3272
* {
3273
	text-align: center;
3274
	margin: 0;
3275
	padding: 0;
3276
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3277
}
3278
p {
3279
	margin-top: 1em;
3280
	font-size: 18px;
3281
}
3282
</style>
3283
<body>
3284
<p><?php echo esc_html( $message ); ?></p>
3285
</body>
3286
</html>
3287
		<?php
3288
		if ( $deactivate ) {
3289
			$plugins = get_option( 'active_plugins' );
3290
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3291
			$update  = false;
3292
			foreach ( $plugins as $i => $plugin ) {
3293
				if ( $plugin === $jetpack ) {
3294
					$plugins[ $i ] = false;
3295
					$update        = true;
3296
				}
3297
			}
3298
3299
			if ( $update ) {
3300
				update_option( 'active_plugins', array_filter( $plugins ) );
3301
			}
3302
		}
3303
		exit;
3304
	}
3305
3306
	/**
3307
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3308
	 *
3309
	 * @static
3310
	 */
3311
	public static function plugin_activation( $network_wide ) {
3312
		Jetpack_Options::update_option( 'activated', 1 );
3313
3314
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3315
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3316
		}
3317
3318
		if ( $network_wide ) {
3319
			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...
3320
		}
3321
3322
		// For firing one-off events (notices) immediately after activation
3323
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3324
3325
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3326
3327
		Health::on_jetpack_activated();
3328
3329
		self::plugin_initialize();
3330
	}
3331
3332
	public static function get_activation_source( $referer_url ) {
3333
3334
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3335
			return array( 'wp-cli', null );
3336
		}
3337
3338
		$referer = wp_parse_url( $referer_url );
3339
3340
		$source_type  = 'unknown';
3341
		$source_query = null;
3342
3343
		if ( ! is_array( $referer ) ) {
3344
			return array( $source_type, $source_query );
3345
		}
3346
3347
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3348
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3349
3350
		if ( isset( $referer['query'] ) ) {
3351
			parse_str( $referer['query'], $query_parts );
3352
		} else {
3353
			$query_parts = array();
3354
		}
3355
3356
		if ( $plugins_path === $referer['path'] ) {
3357
			$source_type = 'list';
3358
		} elseif ( $plugins_install_path === $referer['path'] ) {
3359
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3360
			switch ( $tab ) {
3361
				case 'popular':
3362
					$source_type = 'popular';
3363
					break;
3364
				case 'recommended':
3365
					$source_type = 'recommended';
3366
					break;
3367
				case 'favorites':
3368
					$source_type = 'favorites';
3369
					break;
3370
				case 'search':
3371
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3372
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3373
					break;
3374
				default:
3375
					$source_type = 'featured';
3376
			}
3377
		}
3378
3379
		return array( $source_type, $source_query );
3380
	}
3381
3382
	/**
3383
	 * Runs before bumping version numbers up to a new version
3384
	 *
3385
	 * @param string $version    Version:timestamp.
3386
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3387
	 */
3388
	public static function do_version_bump( $version, $old_version ) {
3389
		if ( $old_version ) { // For existing Jetpack installations.
3390
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3391
3392
			// If a front end page is visited after the update, the 'wp' action will fire.
3393
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3394
3395
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3396
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3397
		}
3398
	}
3399
3400
	/**
3401
	 * Sets the display_update_modal state.
3402
	 */
3403
	public static function set_update_modal_display() {
3404
		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...
3405
3406
	}
3407
3408
	/**
3409
	 * Enqueues the block library styles.
3410
	 *
3411
	 * @param string $hook The current admin page.
3412
	 */
3413
	public static function enqueue_block_style( $hook ) {
3414
		if ( 'toplevel_page_jetpack' === $hook ) {
3415
			wp_enqueue_style( 'wp-block-library' );
3416
		}
3417
	}
3418
3419
	/**
3420
	 * Sets the internal version number and activation state.
3421
	 *
3422
	 * @static
3423
	 */
3424
	public static function plugin_initialize() {
3425
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3426
			Jetpack_Options::update_option( 'activated', 2 );
3427
		}
3428
3429 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3430
			$version = $old_version = JETPACK__VERSION . ':' . time();
3431
			/** This action is documented in class.jetpack.php */
3432
			do_action( 'updating_jetpack_version', $version, false );
3433
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3434
		}
3435
3436
		self::load_modules();
3437
3438
		Jetpack_Options::delete_option( 'do_activate' );
3439
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3440
	}
3441
3442
	/**
3443
	 * Removes all connection options
3444
	 *
3445
	 * @static
3446
	 */
3447
	public static function plugin_deactivation() {
3448
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3449
		$tracking = new Tracking();
3450
		$tracking->record_user_event( 'deactivate_plugin', array() );
3451
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3452
			Jetpack_Network::init()->deactivate();
3453
		} else {
3454
			self::disconnect( false );
3455
			// Jetpack_Heartbeat::init()->deactivate();
3456
		}
3457
	}
3458
3459
	/**
3460
	 * Disconnects from the Jetpack servers.
3461
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3462
	 *
3463
	 * @static
3464
	 */
3465
	public static function disconnect( $update_activated_state = true ) {
3466
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3467
3468
		$connection = self::connection();
3469
3470
		( new Nonce_Handler() )->clean_all();
3471
3472
		// If the site is in an IDC because sync is not allowed,
3473
		// let's make sure to not disconnect the production site.
3474
		if ( ! self::validate_sync_error_idc_option() ) {
3475
			$tracking = new Tracking();
3476
			$tracking->record_user_event( 'disconnect_site', array() );
3477
3478
			$connection->disconnect_site_wpcom( true );
3479
		}
3480
3481
		$connection->delete_all_connection_tokens( true );
3482
		Jetpack_IDC::clear_all_idc_options();
3483
3484
		if ( $update_activated_state ) {
3485
			Jetpack_Options::update_option( 'activated', 4 );
3486
		}
3487
3488
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3489
			// Check then record unique disconnection if site has never been disconnected previously
3490
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3491
				$jetpack_unique_connection['disconnected'] = 1;
3492
			} else {
3493
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3494
					// track unique disconnect
3495
					$jetpack = self::init();
3496
3497
					$jetpack->stat( 'connections', 'unique-disconnect' );
3498
					$jetpack->do_stats( 'server_side' );
3499
				}
3500
				// increment number of times disconnected
3501
				$jetpack_unique_connection['disconnected'] += 1;
3502
			}
3503
3504
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3505
		}
3506
3507
		// Delete all the sync related data. Since it could be taking up space.
3508
		Sender::get_instance()->uninstall();
3509
3510
	}
3511
3512
	/**
3513
	 * Disconnects the user
3514
	 *
3515
	 * @param int $user_id The user ID to disconnect.
3516
	 */
3517
	public function disconnect_user( $user_id ) {
3518
		$this->connection_manager->disconnect_user( $user_id );
3519
	}
3520
3521
	/**
3522
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3523
	 *
3524
	 * @deprecated since Jetpack 9.7.0
3525
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
3526
	 *
3527
	 * @return bool|WP_Error
3528
	 */
3529
	public static function try_registration() {
3530
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
3531
		return static::connection()->try_registration();
3532
	}
3533
3534
	/**
3535
	 * Checking the domain names in beta versions.
3536
	 * If this is a development version, before attempting to connect, let's make sure that the domains are viable.
3537
	 *
3538
	 * @param null|\WP_Error $error The domain validation error, or `null` if everything's fine.
3539
	 *
3540
	 * @return null|\WP_Error The domain validation error, or `null` if everything's fine.
3541
	 */
3542
	public static function registration_check_domains( $error ) {
3543
		if ( static::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3544
			$domains_to_check = array_unique(
3545
				array(
3546
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3547
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3548
				)
3549
			);
3550
			foreach ( $domains_to_check as $domain ) {
3551
				$result = static::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3550 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...
3552
				if ( is_wp_error( $result ) ) {
3553
					return $result;
3554
				}
3555
			}
3556
		}
3557
3558
		return $error;
3559
	}
3560
3561
	/**
3562
	 * Tracking an internal event log. Try not to put too much chaff in here.
3563
	 *
3564
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3565
	 */
3566
	public static function log( $code, $data = null ) {
3567
		// only grab the latest 200 entries
3568
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3569
3570
		// Append our event to the log
3571
		$log_entry = array(
3572
			'time'    => time(),
3573
			'user_id' => get_current_user_id(),
3574
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3575
			'code'    => $code,
3576
		);
3577
		// Don't bother storing it unless we've got some.
3578
		if ( ! is_null( $data ) ) {
3579
			$log_entry['data'] = $data;
3580
		}
3581
		$log[] = $log_entry;
3582
3583
		// Try add_option first, to make sure it's not autoloaded.
3584
		// @todo: Add an add_option method to Jetpack_Options
3585
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3586
			Jetpack_Options::update_option( 'log', $log );
3587
		}
3588
3589
		/**
3590
		 * Fires when Jetpack logs an internal event.
3591
		 *
3592
		 * @since 3.0.0
3593
		 *
3594
		 * @param array $log_entry {
3595
		 *  Array of details about the log entry.
3596
		 *
3597
		 *  @param string time Time of the event.
3598
		 *  @param int user_id ID of the user who trigerred the event.
3599
		 *  @param int blog_id Jetpack Blog ID.
3600
		 *  @param string code Unique name for the event.
3601
		 *  @param string data Data about the event.
3602
		 * }
3603
		 */
3604
		do_action( 'jetpack_log_entry', $log_entry );
3605
	}
3606
3607
	/**
3608
	 * Get the internal event log.
3609
	 *
3610
	 * @param $event (string) - only return the specific log events
3611
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3612
	 *
3613
	 * @return array of log events || WP_Error for invalid params
3614
	 */
3615
	public static function get_log( $event = false, $num = false ) {
3616
		if ( $event && ! is_string( $event ) ) {
3617
			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...
3618
		}
3619
3620
		if ( $num && ! is_numeric( $num ) ) {
3621
			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...
3622
		}
3623
3624
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3625
3626
		// If nothing set - act as it did before, otherwise let's start customizing the output
3627
		if ( ! $num && ! $event ) {
3628
			return $entire_log;
3629
		} else {
3630
			$entire_log = array_reverse( $entire_log );
3631
		}
3632
3633
		$custom_log_output = array();
3634
3635
		if ( $event ) {
3636
			foreach ( $entire_log as $log_event ) {
3637
				if ( $event == $log_event['code'] ) {
3638
					$custom_log_output[] = $log_event;
3639
				}
3640
			}
3641
		} else {
3642
			$custom_log_output = $entire_log;
3643
		}
3644
3645
		if ( $num ) {
3646
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3647
		}
3648
3649
		return $custom_log_output;
3650
	}
3651
3652
	/**
3653
	 * Log modification of important settings.
3654
	 */
3655
	public static function log_settings_change( $option, $old_value, $value ) {
3656
		switch ( $option ) {
3657
			case 'jetpack_sync_non_public_post_stati':
3658
				self::log( $option, $value );
3659
				break;
3660
		}
3661
	}
3662
3663
	/**
3664
	 * Return stat data for WPCOM sync
3665
	 */
3666
	public static function get_stat_data( $encode = true, $extended = true ) {
3667
		$data = Jetpack_Heartbeat::generate_stats_array();
3668
3669
		if ( $extended ) {
3670
			$additional_data = self::get_additional_stat_data();
3671
			$data            = array_merge( $data, $additional_data );
3672
		}
3673
3674
		if ( $encode ) {
3675
			return json_encode( $data );
3676
		}
3677
3678
		return $data;
3679
	}
3680
3681
	/**
3682
	 * Get additional stat data to sync to WPCOM
3683
	 */
3684
	public static function get_additional_stat_data( $prefix = '' ) {
3685
		$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...
3686
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3687
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3688
		$return[ "{$prefix}site-count" ]    = 0;
3689
3690
		if ( function_exists( 'get_blog_count' ) ) {
3691
			$return[ "{$prefix}site-count" ] = get_blog_count();
3692
		}
3693
		return $return;
3694
	}
3695
3696
	private static function get_site_user_count() {
3697
		global $wpdb;
3698
3699
		if ( function_exists( 'wp_is_large_network' ) ) {
3700
			if ( wp_is_large_network( 'users' ) ) {
3701
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3702
			}
3703
		}
3704
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3705
			// It wasn't there, so regenerate the data and save the transient
3706
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3707
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3708
		}
3709
		return $user_count;
3710
	}
3711
3712
	/* Admin Pages */
3713
3714
	function admin_init() {
3715
		// If the plugin is not connected, display a connect message.
3716
		if (
3717
			// the plugin was auto-activated and needs its candy
3718
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3719
		||
3720
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3721
			! Jetpack_Options::get_option( 'activated' )
3722
		) {
3723
			self::plugin_initialize();
3724
		}
3725
3726
		$is_offline_mode              = ( new Status() )->is_offline_mode();
3727
		$fallback_no_verify_ssl_certs = Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
3728
		/** Already documented in automattic/jetpack-connection::src/class-client.php */
3729
		$client_verify_ssl_certs = apply_filters( 'jetpack_client_verify_ssl_certs', false );
3730
3731
		if ( ! $is_offline_mode ) {
3732
			Jetpack_Connection_Banner::init();
3733
		}
3734
3735
		if ( ( self::is_connection_ready() || $is_offline_mode ) && false === $fallback_no_verify_ssl_certs && ! $client_verify_ssl_certs ) {
3736
			// Upgrade: 1.1 -> 1.1.1
3737
			// Check and see if host can verify the Jetpack servers' SSL certificate
3738
			$args = array();
3739
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3740
		}
3741
3742
		Jetpack_Recommendations_Banner::init();
3743
3744
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3745
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3746
		}
3747
3748
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3749
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3750
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3751
3752
		if ( isset( $_COOKIE['jetpackState']['display_update_modal'] ) ) {
3753
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3754
		}
3755
3756
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3757
3758
		if ( self::is_connection_ready() || $is_offline_mode ) {
3759
			// Artificially throw errors in certain specific cases during plugin activation.
3760
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3761
		}
3762
3763
		// Add custom column in wp-admin/users.php to show whether user is linked.
3764
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3765
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3766
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3767
	}
3768
3769
	function admin_body_class( $admin_body_class = '' ) {
3770
		$classes = explode( ' ', trim( $admin_body_class ) );
3771
3772
		$classes[] = self::is_connection_ready() ? 'jetpack-connected' : 'jetpack-disconnected';
3773
3774
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3775
		return " $admin_body_class ";
3776
	}
3777
3778
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3779
		return $admin_body_class . ' jetpack-pagestyles ';
3780
	}
3781
3782
	/**
3783
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3784
	 * This function artificially throws errors for such cases (per a specific list).
3785
	 *
3786
	 * @param string $plugin The activated plugin.
3787
	 */
3788
	function throw_error_on_activate_plugin( $plugin ) {
3789
		$active_modules = self::get_active_modules();
3790
3791
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3792
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3793
			$throw = false;
3794
3795
			// Try and make sure it really was the stats plugin
3796
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3797
				if ( 'stats.php' == basename( $plugin ) ) {
3798
					$throw = true;
3799
				}
3800
			} else {
3801
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3802
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3803
					$throw = true;
3804
				}
3805
			}
3806
3807
			if ( $throw ) {
3808
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3809
			}
3810
		}
3811
	}
3812
3813
	function intercept_plugin_error_scrape_init() {
3814
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3815
	}
3816
3817
	function intercept_plugin_error_scrape( $action, $result ) {
3818
		if ( ! $result ) {
3819
			return;
3820
		}
3821
3822
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3823
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3824
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3825
			}
3826
		}
3827
	}
3828
3829
	/**
3830
	 * Register the remote file upload request handlers, if needed.
3831
	 *
3832
	 * @access public
3833
	 */
3834
	public function add_remote_request_handlers() {
3835
		// Remote file uploads are allowed only via AJAX requests.
3836
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3837
			return;
3838
		}
3839
3840
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3841
		$remote_request_actions = array(
3842
			'jetpack_upload_file',
3843
			'jetpack_update_file',
3844
		);
3845
3846
		// phpcs:ignore WordPress.Security.NonceVerification
3847
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3848
			return;
3849
		}
3850
3851
		// Require Jetpack authentication for the remote file upload AJAX requests.
3852
		if ( ! $this->connection_manager ) {
3853
			$this->connection_manager = new Connection_Manager();
3854
		}
3855
3856
		$this->connection_manager->require_jetpack_authentication();
3857
3858
		// Register the remote file upload AJAX handlers.
3859
		foreach ( $remote_request_actions as $action ) {
3860
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3861
		}
3862
	}
3863
3864
	/**
3865
	 * Handler for Jetpack remote file uploads.
3866
	 *
3867
	 * @access public
3868
	 */
3869
	public function remote_request_handlers() {
3870
		$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...
3871
3872
		switch ( current_filter() ) {
3873
			case 'wp_ajax_nopriv_jetpack_upload_file':
3874
				$response = $this->upload_handler();
3875
				break;
3876
3877
			case 'wp_ajax_nopriv_jetpack_update_file':
3878
				$response = $this->upload_handler( true );
3879
				break;
3880
			default:
3881
				$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...
3882
				break;
3883
		}
3884
3885
		if ( ! $response ) {
3886
			$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...
3887
		}
3888
3889
		if ( is_wp_error( $response ) ) {
3890
			$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...
3891
			$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...
3892
			$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...
3893
3894
			if ( ! is_int( $status_code ) ) {
3895
				$status_code = 400;
3896
			}
3897
3898
			status_header( $status_code );
3899
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3900
		}
3901
3902
		status_header( 200 );
3903
		if ( true === $response ) {
3904
			exit;
3905
		}
3906
3907
		die( json_encode( (object) $response ) );
3908
	}
3909
3910
	/**
3911
	 * Uploads a file gotten from the global $_FILES.
3912
	 * If `$update_media_item` is true and `post_id` is defined
3913
	 * the attachment file of the media item (gotten through of the post_id)
3914
	 * will be updated instead of add a new one.
3915
	 *
3916
	 * @param  boolean $update_media_item - update media attachment
3917
	 * @return array - An array describing the uploadind files process
3918
	 */
3919
	function upload_handler( $update_media_item = false ) {
3920
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3921
			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...
3922
		}
3923
3924
		$user = wp_authenticate( '', '' );
3925
		if ( ! $user || is_wp_error( $user ) ) {
3926
			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...
3927
		}
3928
3929
		wp_set_current_user( $user->ID );
3930
3931
		if ( ! current_user_can( 'upload_files' ) ) {
3932
			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...
3933
		}
3934
3935
		if ( empty( $_FILES ) ) {
3936
			return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_files_uploaded'.

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

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

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

Loading history...
3937
		}
3938
3939
		foreach ( array_keys( $_FILES ) as $files_key ) {
3940
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3941
				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...
3942
			}
3943
		}
3944
3945
		$media_keys = array_keys( $_FILES['media'] );
3946
3947
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3948
		if ( ! $token || is_wp_error( $token ) ) {
3949
			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...
3950
		}
3951
3952
		$uploaded_files = array();
3953
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3954
		unset( $GLOBALS['post'] );
3955
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3956
			$file = array();
3957
			foreach ( $media_keys as $media_key ) {
3958
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3959
			}
3960
3961
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3962
3963
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3964
			if ( $hmac_provided !== $hmac_file ) {
3965
				$uploaded_files[ $index ] = (object) array(
3966
					'error'             => 'invalid_hmac',
3967
					'error_description' => 'The corresponding HMAC for this file does not match',
3968
				);
3969
				continue;
3970
			}
3971
3972
			$_FILES['.jetpack.upload.'] = $file;
3973
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3974
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3975
				$post_id = 0;
3976
			}
3977
3978
			if ( $update_media_item ) {
3979
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3980
					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...
3981
				}
3982
3983
				$media_array = $_FILES['media'];
3984
3985
				$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...
3986
				$file_array['type']     = $media_array['type'][0];
3987
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3988
				$file_array['error']    = $media_array['error'][0];
3989
				$file_array['size']     = $media_array['size'][0];
3990
3991
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3992
3993
				if ( is_wp_error( $edited_media_item ) ) {
3994
					return $edited_media_item;
3995
				}
3996
3997
				$response = (object) array(
3998
					'id'   => (string) $post_id,
3999
					'file' => (string) $edited_media_item->post_title,
4000
					'url'  => (string) wp_get_attachment_url( $post_id ),
4001
					'type' => (string) $edited_media_item->post_mime_type,
4002
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
4003
				);
4004
4005
				return (array) array( $response );
4006
			}
4007
4008
			$attachment_id = media_handle_upload(
4009
				'.jetpack.upload.',
4010
				$post_id,
4011
				array(),
4012
				array(
4013
					'action' => 'jetpack_upload_file',
4014
				)
4015
			);
4016
4017
			if ( ! $attachment_id ) {
4018
				$uploaded_files[ $index ] = (object) array(
4019
					'error'             => 'unknown',
4020
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
4021
				);
4022
			} elseif ( is_wp_error( $attachment_id ) ) {
4023
				$uploaded_files[ $index ] = (object) array(
4024
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
4025
					'error_description' => $attachment_id->get_error_message(),
4026
				);
4027
			} else {
4028
				$attachment               = get_post( $attachment_id );
4029
				$uploaded_files[ $index ] = (object) array(
4030
					'id'   => (string) $attachment_id,
4031
					'file' => $attachment->post_title,
4032
					'url'  => wp_get_attachment_url( $attachment_id ),
4033
					'type' => $attachment->post_mime_type,
4034
					'meta' => wp_get_attachment_metadata( $attachment_id ),
4035
				);
4036
				// Zip files uploads are not supported unless they are done for installation purposed
4037
				// lets delete them in case something goes wrong in this whole process
4038
				if ( 'application/zip' === $attachment->post_mime_type ) {
4039
					// Schedule a cleanup for 2 hours from now in case of failed install.
4040
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
4041
				}
4042
			}
4043
		}
4044
		if ( ! is_null( $global_post ) ) {
4045
			$GLOBALS['post'] = $global_post;
4046
		}
4047
4048
		return $uploaded_files;
4049
	}
4050
4051
	/**
4052
	 * Add help to the Jetpack page
4053
	 *
4054
	 * @since Jetpack (1.2.3)
4055
	 * @return false if not the Jetpack page
4056
	 */
4057
	function admin_help() {
4058
		$current_screen = get_current_screen();
4059
4060
		// Overview
4061
		$current_screen->add_help_tab(
4062
			array(
4063
				'id'      => 'home',
4064
				'title'   => __( 'Home', 'jetpack' ),
4065
				'content' =>
4066
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4067
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4068
					'<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>',
4069
			)
4070
		);
4071
4072
		// Screen Content
4073
		if ( current_user_can( 'manage_options' ) ) {
4074
			$current_screen->add_help_tab(
4075
				array(
4076
					'id'      => 'settings',
4077
					'title'   => __( 'Settings', 'jetpack' ),
4078
					'content' =>
4079
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4080
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4081
						'<ol>' .
4082
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4083
							'<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>' .
4084
						'</ol>' .
4085
						'<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>',
4086
				)
4087
			);
4088
		}
4089
4090
		// Help Sidebar
4091
		$support_url = Redirect::get_url( 'jetpack-support' );
4092
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4093
		$current_screen->set_help_sidebar(
4094
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4095
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4096
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4097
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4098
		);
4099
	}
4100
4101
	function admin_menu_css() {
4102
		wp_enqueue_style( 'jetpack-icons' );
4103
	}
4104
4105
	function admin_menu_order() {
4106
		return true;
4107
	}
4108
4109
	function jetpack_menu_order( $menu_order ) {
4110
		$jp_menu_order = array();
4111
4112
		foreach ( $menu_order as $index => $item ) {
4113
			if ( $item != 'jetpack' ) {
4114
				$jp_menu_order[] = $item;
4115
			}
4116
4117
			if ( $index == 0 ) {
4118
				$jp_menu_order[] = 'jetpack';
4119
			}
4120
		}
4121
4122
		return $jp_menu_order;
4123
	}
4124
4125
	function admin_banner_styles() {
4126
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4127
4128 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4129
			wp_register_style(
4130
				'jetpack-dops-style',
4131
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4132
				array(),
4133
				JETPACK__VERSION
4134
			);
4135
		}
4136
4137
		wp_enqueue_style(
4138
			'jetpack',
4139
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4140
			array( 'jetpack-dops-style' ),
4141
			JETPACK__VERSION . '-20121016'
4142
		);
4143
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4144
		wp_style_add_data( 'jetpack', 'suffix', $min );
4145
	}
4146
4147
	function plugin_action_links( $actions ) {
4148
4149
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4150
4151
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
4152
			return array_merge(
4153
				$jetpack_home,
4154
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4155
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4156
				$actions
4157
			);
4158
		}
4159
4160
		return array_merge( $jetpack_home, $actions );
4161
	}
4162
4163
	/**
4164
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4165
	 *
4166
	 * @param string $hook The current admin page.
4167
	 *
4168
	 * @return void
4169
	 */
4170
	public function deactivate_dialog( $hook ) {
4171
		if (
4172
			'plugins.php' === $hook
4173
			&& self::is_connection_ready()
4174
		) {
4175
4176
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4177
4178
			if ( count( $active_plugins_using_connection ) > 1 ) {
4179
4180
				add_thickbox();
4181
4182
				wp_register_script(
4183
					'jp-tracks',
4184
					'//stats.wp.com/w.js',
4185
					array(),
4186
					gmdate( 'YW' ),
4187
					true
4188
				);
4189
4190
				wp_register_script(
4191
					'jp-tracks-functions',
4192
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4193
					array( 'jp-tracks' ),
4194
					JETPACK__VERSION,
4195
					false
4196
				);
4197
4198
				wp_enqueue_script(
4199
					'jetpack-deactivate-dialog-js',
4200
					Assets::get_file_url_for_environment(
4201
						'_inc/build/jetpack-deactivate-dialog.min.js',
4202
						'_inc/jetpack-deactivate-dialog.js'
4203
					),
4204
					array( 'jquery', 'jp-tracks-functions' ),
4205
					JETPACK__VERSION,
4206
					true
4207
				);
4208
4209
				wp_localize_script(
4210
					'jetpack-deactivate-dialog-js',
4211
					'deactivate_dialog',
4212
					array(
4213
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4214
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4215
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4216
					)
4217
				);
4218
4219
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4220
4221
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4222
			}
4223
		}
4224
	}
4225
4226
	/**
4227
	 * Outputs the content of the deactivation modal
4228
	 *
4229
	 * @return void
4230
	 */
4231
	public function deactivate_dialog_content() {
4232
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4233
		unset( $active_plugins_using_connection['jetpack'] );
4234
		$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 4232 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...
4235
	}
4236
4237
	/**
4238
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4239
	 *
4240
	 * @param string $login_url The wp-login URL.
4241
	 * @param string $redirect  URL to redirect users after logging in.
4242
	 * @since Jetpack 8.4
4243
	 * @return string
4244
	 */
4245
	public function login_url( $login_url, $redirect ) {
4246
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4247
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4248
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4249
		}
4250
		return $login_url;
4251
	}
4252
4253
	/**
4254
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4255
	 *
4256
	 * @since Jetpack 8.4
4257
	 */
4258
	public function login_init() {
4259
		// phpcs:ignore WordPress.Security.NonceVerification
4260
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4261
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4262
			wp_safe_redirect(
4263
				add_query_arg(
4264
					array(
4265
						'forceInstall' => 1,
4266
						'url'          => rawurlencode( get_site_url() ),
4267
					),
4268
					// @todo provide way to go to specific calypso env.
4269
					self::get_calypso_host() . 'jetpack/connect'
4270
				)
4271
			);
4272
			exit;
4273
		}
4274
	}
4275
4276
	/*
4277
	 * Registration flow:
4278
	 * 1 - ::admin_page_load() action=register
4279
	 * 2 - ::try_registration()
4280
	 * 3 - ::register()
4281
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4282
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4283
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4284
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4285
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4286
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4287
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4288
	 *       jetpack_id, jetpack_secret, jetpack_public
4289
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4290
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4291
	 * 5 - user logs in with WP.com account
4292
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4293
	 *		- Manager::authorize()
4294
	 *		- Manager::get_token()
4295
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4296
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4297
	 *			- which responds with access_token, token_type, scope
4298
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4299
	 *		- Jetpack::activate_default_modules()
4300
	 *     		- Deactivates deprecated plugins
4301
	 *     		- Activates all default modules
4302
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4303
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4304
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4305
	 *     Done!
4306
	 */
4307
4308
	/**
4309
	 * Handles the page load events for the Jetpack admin page
4310
	 */
4311
	function admin_page_load() {
4312
		$error = false;
4313
4314
		// Make sure we have the right body class to hook stylings for subpages off of.
4315
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4316
4317
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4318
			// Should only be used in intermediate redirects to preserve state across redirects
4319
			self::restate();
4320
		}
4321
4322
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4323
			// @todo: Add validation against a known allowed list.
4324
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4325
			// User clicked in the iframe to link their accounts
4326
			if ( ! self::connection()->is_user_connected() ) {
4327
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4328
4329
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4330
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4331
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4332
4333
				if ( isset( $_GET['notes_iframe'] ) ) {
4334
					$connect_url .= '&notes_iframe';
4335
				}
4336
				wp_redirect( $connect_url );
4337
				exit;
4338
			} else {
4339
				if ( ! isset( $_GET['calypso_env'] ) ) {
4340
					self::state( 'message', 'already_authorized' );
4341
					wp_safe_redirect( self::admin_url() );
4342
					exit;
4343
				} else {
4344
					$connect_url  = $this->build_connect_url( true, false, $from );
4345
					$connect_url .= '&already_authorized=true';
4346
					wp_redirect( $connect_url );
4347
					exit;
4348
				}
4349
			}
4350
		}
4351
4352
		if ( isset( $_GET['action'] ) ) {
4353
			switch ( $_GET['action'] ) {
4354
				case 'authorize_redirect':
4355
					self::log( 'authorize_redirect' );
4356
4357
					add_filter(
4358
						'allowed_redirect_hosts',
4359
						function ( $domains ) {
4360
							$domains[] = 'jetpack.com';
4361
							$domains[] = 'jetpack.wordpress.com';
4362
							$domains[] = 'wordpress.com';
4363
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4364
							return array_unique( $domains );
4365
						}
4366
					);
4367
4368
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4369
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4370
4371
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4372
						// The destination URL is missing or invalid, nothing to do here.
4373
						exit;
4374
					}
4375
4376
					if ( static::connection()->is_connected() && static::connection()->is_user_connected() ) {
4377
						// The user is either already connected, or finished the connection process.
4378
						wp_safe_redirect( $dest_url );
4379
						exit;
4380
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4381
						// The user decided not to proceed with setting up the connection.
4382
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4383
						exit;
4384
					}
4385
4386
					$redirect_url = self::admin_url(
4387
						array(
4388
							'page'     => 'jetpack',
4389
							'action'   => 'authorize_redirect',
4390
							'dest_url' => rawurlencode( $dest_url ),
4391
							'done'     => '1',
4392
						)
4393
					);
4394
4395
					wp_safe_redirect( static::build_authorize_url( $redirect_url ) );
0 ignored issues
show
Documentation introduced by
$redirect_url is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4396
					exit;
4397
				case 'authorize':
4398
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4399
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4400
					exit;
4401
				case 'register':
4402
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4403
						$error = 'cheatin';
4404
						break;
4405
					}
4406
					check_admin_referer( 'jetpack-register' );
4407
					self::log( 'register' );
4408
					self::maybe_set_version_option();
4409
					$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4410
					if ( $from ) {
4411
						static::connection()->add_register_request_param( 'from', (string) $from );
4412
					}
4413
					$registered = static::connection()->try_registration();
4414
					if ( is_wp_error( $registered ) ) {
4415
						$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...
4416
						self::state( 'error', $error );
4417
						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...
4418
4419
						/**
4420
						 * Jetpack registration Error.
4421
						 *
4422
						 * @since 7.5.0
4423
						 *
4424
						 * @param string|int $error The error code.
4425
						 * @param \WP_Error $registered The error object.
4426
						 */
4427
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4428
						break;
4429
					}
4430
4431
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4432
4433
					/**
4434
					 * Jetpack registration Success.
4435
					 *
4436
					 * @since 7.5.0
4437
					 *
4438
					 * @param string $from 'from' GET parameter;
4439
					 */
4440
					do_action( 'jetpack_connection_register_success', $from );
4441
4442
					$url = $this->build_connect_url( true, $redirect, $from );
4443
4444
					if ( ! empty( $_GET['onboarding'] ) ) {
4445
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4446
					}
4447
4448
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4449
						$url = add_query_arg( 'auth_approved', 'true', $url );
4450
					}
4451
4452
					wp_redirect( $url );
4453
					exit;
4454
				case 'activate':
4455
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4456
						$error = 'cheatin';
4457
						break;
4458
					}
4459
4460
					$module = stripslashes( $_GET['module'] );
4461
					check_admin_referer( "jetpack_activate-$module" );
4462
					self::log( 'activate', $module );
4463
					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...
4464
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4465
					}
4466
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4467
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4468
					exit;
4469
				case 'activate_default_modules':
4470
					check_admin_referer( 'activate_default_modules' );
4471
					self::log( 'activate_default_modules' );
4472
					self::restate();
4473
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4474
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4475
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4476
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4477
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4478
					exit;
4479 View Code Duplication
				case 'disconnect':
4480
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4481
						$error = 'cheatin';
4482
						break;
4483
					}
4484
4485
					check_admin_referer( 'jetpack-disconnect' );
4486
					self::log( 'disconnect' );
4487
					self::disconnect();
4488
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4489
					exit;
4490 View Code Duplication
				case 'reconnect':
4491
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4492
						$error = 'cheatin';
4493
						break;
4494
					}
4495
4496
					check_admin_referer( 'jetpack-reconnect' );
4497
					self::log( 'reconnect' );
4498
					self::disconnect();
4499
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4500
					exit;
4501 View Code Duplication
				case 'deactivate':
4502
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4503
						$error = 'cheatin';
4504
						break;
4505
					}
4506
4507
					$modules = stripslashes( $_GET['module'] );
4508
					check_admin_referer( "jetpack_deactivate-$modules" );
4509
					foreach ( explode( ',', $modules ) as $module ) {
4510
						self::log( 'deactivate', $module );
4511
						self::deactivate_module( $module );
4512
						self::state( 'message', 'module_deactivated' );
4513
					}
4514
					self::state( 'module', $modules );
4515
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4516
					exit;
4517
				case 'unlink':
4518
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4519
					check_admin_referer( 'jetpack-unlink' );
4520
					self::log( 'unlink' );
4521
					$this->connection_manager->disconnect_user();
4522
					self::state( 'message', 'unlinked' );
4523
					if ( 'sub-unlink' == $redirect ) {
4524
						wp_safe_redirect( admin_url() );
4525
					} else {
4526
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4527
					}
4528
					exit;
4529
				case 'onboard':
4530
					if ( ! current_user_can( 'manage_options' ) ) {
4531
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4532
					} else {
4533
						self::create_onboarding_token();
4534
						$url = $this->build_connect_url( true );
4535
4536
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4537
							$url = add_query_arg( 'onboarding', $token, $url );
4538
						}
4539
4540
						$calypso_env = $this->get_calypso_env();
4541
						if ( ! empty( $calypso_env ) ) {
4542
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4543
						}
4544
4545
						wp_redirect( $url );
4546
						exit;
4547
					}
4548
					exit;
4549
				default:
4550
					/**
4551
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4552
					 *
4553
					 * @since 2.6.0
4554
					 *
4555
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4556
					 */
4557
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4558
			}
4559
		}
4560
4561
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4562
			self::activate_new_modules( true );
4563
		}
4564
4565
		$message_code = self::state( 'message' );
4566
		if ( self::state( 'optin-manage' ) ) {
4567
			$activated_manage = $message_code;
4568
			$message_code     = 'jetpack-manage';
4569
		}
4570
4571
		switch ( $message_code ) {
4572
			case 'jetpack-manage':
4573
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4574
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4575
				$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>';
4576
				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...
4577
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4578
				}
4579
				break;
4580
4581
		}
4582
4583
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4584
4585
		if ( ! empty( $deactivated_plugins ) ) {
4586
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4587
			$deactivated_titles  = array();
4588
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4589
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4590
					continue;
4591
				}
4592
4593
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4594
			}
4595
4596
			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...
4597
				if ( $this->message ) {
4598
					$this->message .= "<br /><br />\n";
4599
				}
4600
4601
				$this->message .= wp_sprintf(
4602
					_n(
4603
						'Jetpack contains the most recent version of the old %l plugin.',
4604
						'Jetpack contains the most recent versions of the old %l plugins.',
4605
						count( $deactivated_titles ),
4606
						'jetpack'
4607
					),
4608
					$deactivated_titles
4609
				);
4610
4611
				$this->message .= "<br />\n";
4612
4613
				$this->message .= _n(
4614
					'The old version has been deactivated and can be removed from your site.',
4615
					'The old versions have been deactivated and can be removed from your site.',
4616
					count( $deactivated_titles ),
4617
					'jetpack'
4618
				);
4619
			}
4620
		}
4621
4622
		$this->privacy_checks = self::state( 'privacy_checks' );
4623
4624
		if ( $this->message || $this->error || $this->privacy_checks ) {
4625
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4626
		}
4627
4628
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4629
	}
4630
4631
	function admin_notices() {
4632
4633
		if ( $this->error ) {
4634
			?>
4635
<div id="message" class="jetpack-message jetpack-err">
4636
	<div class="squeezer">
4637
		<h2>
4638
			<?php
4639
			echo wp_kses(
4640
				$this->error,
4641
				array(
4642
					'a'      => array( 'href' => array() ),
4643
					'small'  => true,
4644
					'code'   => true,
4645
					'strong' => true,
4646
					'br'     => true,
4647
					'b'      => true,
4648
				)
4649
			);
4650
			?>
4651
			</h2>
4652
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4653
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4654
<?php	endif; ?>
4655
	</div>
4656
</div>
4657
			<?php
4658
		}
4659
4660
		if ( $this->message ) {
4661
			?>
4662
<div id="message" class="jetpack-message">
4663
	<div class="squeezer">
4664
		<h2>
4665
			<?php
4666
			echo wp_kses(
4667
				$this->message,
4668
				array(
4669
					'strong' => array(),
4670
					'a'      => array( 'href' => true ),
4671
					'br'     => true,
4672
				)
4673
			);
4674
			?>
4675
			</h2>
4676
	</div>
4677
</div>
4678
			<?php
4679
		}
4680
4681
		if ( $this->privacy_checks ) :
4682
			$module_names = $module_slugs = array();
4683
4684
			$privacy_checks = explode( ',', $this->privacy_checks );
4685
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4686
			foreach ( $privacy_checks as $module_slug ) {
4687
				$module = self::get_module( $module_slug );
4688
				if ( ! $module ) {
4689
					continue;
4690
				}
4691
4692
				$module_slugs[] = $module_slug;
4693
				$module_names[] = "<strong>{$module['name']}</strong>";
4694
			}
4695
4696
			$module_slugs = join( ',', $module_slugs );
4697
			?>
4698
<div id="message" class="jetpack-message jetpack-err">
4699
	<div class="squeezer">
4700
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4701
		<p>
4702
			<?php
4703
			echo wp_kses(
4704
				wptexturize(
4705
					wp_sprintf(
4706
						_nx(
4707
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4708
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4709
							count( $privacy_checks ),
4710
							'%l = list of Jetpack module/feature names',
4711
							'jetpack'
4712
						),
4713
						$module_names
4714
					)
4715
				),
4716
				array( 'strong' => true )
4717
			);
4718
4719
			echo "\n<br />\n";
4720
4721
			echo wp_kses(
4722
				sprintf(
4723
					_nx(
4724
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4725
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4726
						count( $privacy_checks ),
4727
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4728
						'jetpack'
4729
					),
4730
					wp_nonce_url(
4731
						self::admin_url(
4732
							array(
4733
								'page'   => 'jetpack',
4734
								'action' => 'deactivate',
4735
								'module' => urlencode( $module_slugs ),
4736
							)
4737
						),
4738
						"jetpack_deactivate-$module_slugs"
4739
					),
4740
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4741
				),
4742
				array(
4743
					'a' => array(
4744
						'href'  => true,
4745
						'title' => true,
4746
					),
4747
				)
4748
			);
4749
			?>
4750
		</p>
4751
	</div>
4752
</div>
4753
			<?php
4754
endif;
4755
	}
4756
4757
	/**
4758
	 * We can't always respond to a signed XML-RPC request with a
4759
	 * helpful error message. In some circumstances, doing so could
4760
	 * leak information.
4761
	 *
4762
	 * Instead, track that the error occurred via a Jetpack_Option,
4763
	 * and send that data back in the heartbeat.
4764
	 * All this does is increment a number, but it's enough to find
4765
	 * trends.
4766
	 *
4767
	 * @param WP_Error $xmlrpc_error The error produced during
4768
	 *                               signature validation.
4769
	 */
4770
	function track_xmlrpc_error( $xmlrpc_error ) {
4771
		$code = is_wp_error( $xmlrpc_error )
4772
			? $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...
4773
			: 'should-not-happen';
4774
4775
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4776
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4777
			// No need to update the option if we already have
4778
			// this code stored.
4779
			return;
4780
		}
4781
		$xmlrpc_errors[ $code ] = true;
4782
4783
		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...
4784
	}
4785
4786
	/**
4787
	 * Initialize the jetpack stats instance only when needed
4788
	 *
4789
	 * @return void
4790
	 */
4791
	private function initialize_stats() {
4792
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4793
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4794
		}
4795
	}
4796
4797
	/**
4798
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4799
	 */
4800
	function stat( $group, $detail ) {
4801
		$this->initialize_stats();
4802
		$this->a8c_mc_stats_instance->add( $group, $detail );
4803
4804
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4805
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4806
	}
4807
4808
	/**
4809
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4810
	 */
4811
	function do_stats( $method = '' ) {
4812
		$this->initialize_stats();
4813
		if ( 'server_side' === $method ) {
4814
			$this->a8c_mc_stats_instance->do_server_side_stats();
4815
		} else {
4816
			$this->a8c_mc_stats_instance->do_stats();
4817
		}
4818
4819
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4820
		$this->stats = array();
4821
	}
4822
4823
	/**
4824
	 * Runs stats code for a one-off, server-side.
4825
	 *
4826
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4827
	 *
4828
	 * @return bool If it worked.
4829
	 */
4830
	static function do_server_side_stat( $args ) {
4831
		$url                   = self::build_stats_url( $args );
4832
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4833
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4834
	}
4835
4836
	/**
4837
	 * Builds the stats url.
4838
	 *
4839
	 * @param $args array|string The arguments to append to the URL.
4840
	 *
4841
	 * @return string The URL to be pinged.
4842
	 */
4843
	static function build_stats_url( $args ) {
4844
4845
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4846
		return $a8c_mc_stats_instance->build_stats_url( $args );
4847
4848
	}
4849
4850
	/**
4851
	 * Builds a URL to the Jetpack connection auth page
4852
	 *
4853
	 * @since 3.9.5
4854
	 *
4855
	 * @param bool        $raw If true, URL will not be escaped.
4856
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4857
	 *                              If string, will be a custom redirect.
4858
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4859
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4860
	 *
4861
	 * @return string Connect URL
4862
	 */
4863
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4864
		$site_id    = Jetpack_Options::get_option( 'id' );
4865
		$blog_token = ( new Tokens() )->get_access_token();
4866
4867
		if ( $register || ! $blog_token || ! $site_id ) {
4868
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4869
4870
			if ( ! empty( $redirect ) ) {
4871
				$url = add_query_arg(
4872
					'redirect',
4873
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4874
					$url
4875
				);
4876
			}
4877
4878
			if ( is_network_admin() ) {
4879
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4880
			}
4881
4882
			$calypso_env = self::get_calypso_env();
4883
4884
			if ( ! empty( $calypso_env ) ) {
4885
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4886
			}
4887
		} else {
4888
4889
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4890
			// because otherwise this logic can get us in to a loop.
4891
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4892
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4893
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4894
4895
				$response = Client::wpcom_json_api_request_as_blog(
4896
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4897
					'1.1'
4898
				);
4899
4900
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4901
4902
					// Generating a register URL instead to refresh the existing token
4903
					return $this->build_connect_url( $raw, $redirect, $from, true );
4904
				}
4905
			}
4906
4907
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4863 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...
4908
		}
4909
4910
		if ( $from ) {
4911
			$url = add_query_arg( 'from', $from, $url );
4912
		}
4913
4914
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4915
		/**
4916
		 * Filter the URL used when connecting a user to a WordPress.com account.
4917
		 *
4918
		 * @since 8.1.0
4919
		 *
4920
		 * @param string $url Connection URL.
4921
		 * @param bool   $raw If true, URL will not be escaped.
4922
		 */
4923
		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...
4924
	}
4925
4926
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4927
4928
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4929
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4930
4931
		if ( $iframe ) {
4932
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4933
		}
4934
4935
		$c8n = self::connection();
4936
		$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...
4937
4938
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4939
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4940
4941
		if ( $iframe ) {
4942
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4943
		}
4944
4945
		/**
4946
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4947
		 *
4948
		 * @since 8.9.0
4949
		 *
4950
		 * @param string $url Connection URL.
4951
		 */
4952
		return apply_filters( 'jetpack_build_authorize_url', $url );
4953
	}
4954
4955
	/**
4956
	 * Filters the connection URL parameter array.
4957
	 *
4958
	 * @param array $args default URL parameters used by the package.
4959
	 * @return array the modified URL arguments array.
4960
	 */
4961
	public static function filter_connect_request_body( $args ) {
4962
		if (
4963
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4964
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4965
		) {
4966
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4967
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4968
				? $gp_locale->slug
4969
				: '';
4970
		}
4971
4972
		$tracking        = new Tracking();
4973
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4974
4975
		$args = array_merge(
4976
			$args,
4977
			array(
4978
				'_ui' => $tracks_identity['_ui'],
4979
				'_ut' => $tracks_identity['_ut'],
4980
			)
4981
		);
4982
4983
		$calypso_env = self::get_calypso_env();
4984
4985
		if ( ! empty( $calypso_env ) ) {
4986
			$args['calypso_env'] = $calypso_env;
4987
		}
4988
4989
		return $args;
4990
	}
4991
4992
	/**
4993
	 * Filters the URL that will process the connection data. It can be different from the URL
4994
	 * that we send the user to after everything is done.
4995
	 *
4996
	 * @param String $processing_url the default redirect URL used by the package.
4997
	 * @return String the modified URL.
4998
	 *
4999
	 * @deprecated since Jetpack 9.5.0
5000
	 */
5001
	public static function filter_connect_processing_url( $processing_url ) {
5002
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
5003
5004
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
5005
		return $processing_url;
5006
	}
5007
5008
	/**
5009
	 * Filters the redirection URL that is used for connect requests. The redirect
5010
	 * URL should return the user back to the Jetpack console.
5011
	 *
5012
	 * @param String $redirect the default redirect URL used by the package.
5013
	 * @return String the modified URL.
5014
	 */
5015
	public static function filter_connect_redirect_url( $redirect ) {
5016
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
5017
		$redirect           = $redirect
5018
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
5019
			: $jetpack_admin_page;
5020
5021
		if ( isset( $_REQUEST['is_multisite'] ) ) {
5022
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
5023
		}
5024
5025
		return $redirect;
5026
	}
5027
5028
	/**
5029
	 * This action fires at the beginning of the Manager::authorize method.
5030
	 */
5031
	public static function authorize_starting() {
5032
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
5033
		// Checking if site has been active/connected previously before recording unique connection.
5034
		if ( ! $jetpack_unique_connection ) {
5035
			// jetpack_unique_connection option has never been set.
5036
			$jetpack_unique_connection = array(
5037
				'connected'    => 0,
5038
				'disconnected' => 0,
5039
				'version'      => '3.6.1',
5040
			);
5041
5042
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
5043
5044
			// Track unique connection.
5045
			$jetpack = self::init();
5046
5047
			$jetpack->stat( 'connections', 'unique-connection' );
5048
			$jetpack->do_stats( 'server_side' );
5049
		}
5050
5051
		// Increment number of times connected.
5052
		$jetpack_unique_connection['connected'] += 1;
5053
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5054
	}
5055
5056
	/**
5057
	 * This action fires when the site is registered (connected at a site level).
5058
	 */
5059
	public function handle_unique_registrations_stats() {
5060
		$jetpack_unique_registrations = Jetpack_Options::get_option( 'unique_registrations' );
5061
		// Checking if site has been registered previously before recording unique connection.
5062
		if ( ! $jetpack_unique_registrations ) {
5063
5064
			$jetpack_unique_registrations = 0;
5065
5066
			$this->stat( 'connections', 'unique-registrations' );
5067
			$this->do_stats( 'server_side' );
5068
		}
5069
5070
		// Increment number of times connected.
5071
		$jetpack_unique_registrations ++;
5072
		Jetpack_Options::update_option( 'unique_registrations', $jetpack_unique_registrations );
5073
	}
5074
5075
	/**
5076
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5077
	 * linked.
5078
	 */
5079
	public static function authorize_ending_linked() {
5080
		// Don't activate anything since we are just connecting a user.
5081
		self::state( 'message', 'linked' );
5082
	}
5083
5084
	/**
5085
	 * This action fires at the end of the Manager::authorize method when the master user is
5086
	 * authorized.
5087
	 *
5088
	 * @param array $data The request data.
5089
	 */
5090
	public static function authorize_ending_authorized( $data ) {
5091
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5092
		self::invalidate_onboarding_token();
5093
5094
		// If redirect_uri is SSO, ensure SSO module is enabled.
5095
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5096
5097
		/** This filter is documented in class.jetpack-cli.php */
5098
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5099
5100
		$activate_sso = (
5101
			isset( $redirect_options['action'] ) &&
5102
			'jetpack-sso' === $redirect_options['action'] &&
5103
			$jetpack_start_enable_sso
5104
		);
5105
5106
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5107
5108
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5109
	}
5110
5111
	/**
5112
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5113
	 */
5114
	public static function activate_default_modules_on_site_register() {
5115
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5116
		if ( $active_modules ) {
5117
			self::delete_active_modules();
5118
5119
			// 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.
5120
			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...
5121
		} else {
5122
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5123
			self::activate_default_modules( false, false, array(), false, null, null, false );
5124
		}
5125
5126
		// Since this is a fresh connection, be sure to clear out IDC options.
5127
		Jetpack_IDC::clear_all_idc_options();
5128
	}
5129
5130
	/**
5131
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5132
	 * reconnect process is completed.
5133
	 * Note that this currently only happens when we don't need the user to re-authorize
5134
	 * their WP.com account, eg in cases where we are restoring a connection with
5135
	 * unhealthy blog token.
5136
	 */
5137
	public static function reconnection_completed() {
5138
		self::state( 'message', 'reconnection_completed' );
5139
	}
5140
5141
	/**
5142
	 * Get our assumed site creation date.
5143
	 * Calculated based on the earlier date of either:
5144
	 * - Earliest admin user registration date.
5145
	 * - Earliest date of post of any post type.
5146
	 *
5147
	 * @since 7.2.0
5148
	 * @deprecated since 7.8.0
5149
	 *
5150
	 * @return string Assumed site creation date and time.
5151
	 */
5152
	public static function get_assumed_site_creation_date() {
5153
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5154
		return self::connection()->get_assumed_site_creation_date();
5155
	}
5156
5157 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5158
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5159
5160
		if ( $activation_source_name ) {
5161
			$args['_as'] = urlencode( $activation_source_name );
5162
		}
5163
5164
		if ( $activation_source_keyword ) {
5165
			$args['_ak'] = urlencode( $activation_source_keyword );
5166
		}
5167
	}
5168
5169
	function build_reconnect_url( $raw = false ) {
5170
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5171
		return $raw ? $url : esc_url( $url );
5172
	}
5173
5174
	public static function admin_url( $args = null ) {
5175
		$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...
5176
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5177
		return $url;
5178
	}
5179
5180
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5181
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5182
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5183
	}
5184
5185
	function dismiss_jetpack_notice() {
5186
5187
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5188
			return;
5189
		}
5190
5191
		switch ( $_GET['jetpack-notice'] ) {
5192
			case 'dismiss':
5193
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5194
5195
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5196
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5197
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5198
				}
5199
				break;
5200
		}
5201
	}
5202
5203
	public static function sort_modules( $a, $b ) {
5204
		if ( $a['sort'] == $b['sort'] ) {
5205
			return 0;
5206
		}
5207
5208
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5209
	}
5210
5211
	function ajax_recheck_ssl() {
5212
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5213
		$result = self::permit_ssl( true );
5214
		wp_send_json(
5215
			array(
5216
				'enabled' => $result,
5217
				'message' => get_transient( 'jetpack_https_test_message' ),
5218
			)
5219
		);
5220
	}
5221
5222
	/* Client API */
5223
5224
	/**
5225
	 * Returns the requested Jetpack API URL
5226
	 *
5227
	 * @deprecated since 7.7
5228
	 * @return string
5229
	 */
5230
	public static function api_url( $relative_url ) {
5231
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5232
		$connection = self::connection();
5233
		return $connection->api_url( $relative_url );
5234
	}
5235
5236
	/**
5237
	 * @deprecated 8.0
5238
	 *
5239
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5240
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5241
	 */
5242
	public static function fix_url_for_bad_hosts( $url ) {
5243
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5244
		return $url;
5245
	}
5246
5247
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5248
		// Default to a blog token.
5249
		$token_type = 'blog';
5250
5251
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5252
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5253
			if ( ! empty( $_GET['onboarding'] ) ) {
5254
				$jpo = $_GET;
5255
			} else {
5256
				$jpo = json_decode( $request_data, true );
5257
			}
5258
5259
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5260
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5261
5262
			if (
5263
				isset( $jpo_user )
5264
				&& isset( $jpo_token )
5265
				&& is_email( $jpo_user )
5266
				&& ctype_alnum( $jpo_token )
5267
				&& isset( $_GET['rest_route'] )
5268
				&& self::validate_onboarding_token_action(
5269
					$jpo_token,
5270
					$_GET['rest_route']
5271
				)
5272
			) {
5273
				$jp_user = get_user_by( 'email', $jpo_user );
5274
				if ( is_a( $jp_user, 'WP_User' ) ) {
5275
					wp_set_current_user( $jp_user->ID );
5276
					$user_can = is_multisite()
5277
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5278
						: current_user_can( 'manage_options' );
5279
					if ( $user_can ) {
5280
						$token_type              = 'user';
5281
						$token->external_user_id = $jp_user->ID;
5282
					}
5283
				}
5284
			}
5285
5286
			$token_data['type']    = $token_type;
5287
			$token_data['user_id'] = $token->external_user_id;
5288
		}
5289
5290
		return $token_data;
5291
	}
5292
5293
	/**
5294
	 * Create a random secret for validating onboarding payload
5295
	 *
5296
	 * @return string Secret token
5297
	 */
5298
	public static function create_onboarding_token() {
5299
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5300
			$token = wp_generate_password( 32, false );
5301
			Jetpack_Options::update_option( 'onboarding', $token );
5302
		}
5303
5304
		return $token;
5305
	}
5306
5307
	/**
5308
	 * Remove the onboarding token
5309
	 *
5310
	 * @return bool True on success, false on failure
5311
	 */
5312
	public static function invalidate_onboarding_token() {
5313
		return Jetpack_Options::delete_option( 'onboarding' );
5314
	}
5315
5316
	/**
5317
	 * Validate an onboarding token for a specific action
5318
	 *
5319
	 * @return boolean True if token/action pair is accepted, false if not
5320
	 */
5321
	public static function validate_onboarding_token_action( $token, $action ) {
5322
		// Compare tokens, bail if tokens do not match
5323
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5324
			return false;
5325
		}
5326
5327
		// List of valid actions we can take
5328
		$valid_actions = array(
5329
			'/jetpack/v4/settings',
5330
		);
5331
5332
		// Only allow valid actions.
5333
		if ( ! in_array( $action, $valid_actions ) ) {
5334
			return false;
5335
		}
5336
5337
		return true;
5338
	}
5339
5340
	/**
5341
	 * Checks to see if the URL is using SSL to connect with Jetpack
5342
	 *
5343
	 * @since 2.3.3
5344
	 * @return boolean
5345
	 */
5346
	public static function permit_ssl( $force_recheck = false ) {
5347
		// Do some fancy tests to see if ssl is being supported
5348
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5349
			$message = '';
5350
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5351
				$ssl = 0;
5352
			} else {
5353
				$ssl = 1;
5354
5355
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5356
					$ssl     = 0;
5357
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5358
				} else {
5359
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5360
					if ( is_wp_error( $response ) ) {
5361
						$ssl     = 0;
5362
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5363
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5364
						$ssl     = 0;
5365
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5366
					}
5367
				}
5368
			}
5369
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5370
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5371
		}
5372
5373
		return (bool) $ssl;
5374
	}
5375
5376
	/*
5377
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5378
	 */
5379
	public function alert_auto_ssl_fail() {
5380
		if ( ! current_user_can( 'manage_options' ) ) {
5381
			return;
5382
		}
5383
5384
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5385
		?>
5386
5387
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5388
			<div class="jp-banner__content">
5389
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5390
				<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>
5391
				<p>
5392
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5393
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5394
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5395
				</p>
5396
				<p>
5397
					<?php
5398
					printf(
5399
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5400
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5401
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5402
					);
5403
					?>
5404
				</p>
5405
			</div>
5406
		</div>
5407
		<style>
5408
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5409
		</style>
5410
		<script type="text/javascript">
5411
			jQuery( document ).ready( function( $ ) {
5412
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5413
					var $this = $( this );
5414
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5415
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5416
					e.preventDefault();
5417
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5418
					$.post( ajaxurl, data )
5419
					  .done( function( response ) {
5420
						  if ( response.enabled ) {
5421
							  $( '#jetpack-ssl-warning' ).hide();
5422
						  } else {
5423
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5424
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5425
						  }
5426
					  }.bind( $this ) );
5427
				} );
5428
			} );
5429
		</script>
5430
5431
		<?php
5432
	}
5433
5434
	/**
5435
	 * Returns the Jetpack XML-RPC API
5436
	 *
5437
	 * @deprecated 8.0 Use Connection_Manager instead.
5438
	 * @return string
5439
	 */
5440
	public static function xmlrpc_api_url() {
5441
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5442
		return self::connection()->xmlrpc_api_url();
5443
	}
5444
5445
	/**
5446
	 * Returns the connection manager object.
5447
	 *
5448
	 * @return Automattic\Jetpack\Connection\Manager
5449
	 */
5450
	public static function connection() {
5451
		$jetpack = static::init();
5452
5453
		// If the connection manager hasn't been instantiated, do that now.
5454
		if ( ! $jetpack->connection_manager ) {
5455
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5456
		}
5457
5458
		return $jetpack->connection_manager;
5459
	}
5460
5461
	/**
5462
	 * Creates two secret tokens and the end of life timestamp for them.
5463
	 *
5464
	 * Note these tokens are unique per call, NOT static per site for connecting.
5465
	 *
5466
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5467
	 *
5468
	 * @since 2.6
5469
	 * @param String  $action  The action name.
5470
	 * @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...
5471
	 * @param Integer $exp     Expiration time in seconds.
5472
	 * @return array
5473
	 */
5474
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5475
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5476
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5477
	}
5478
5479
	public static function get_secrets( $action, $user_id ) {
5480
		$secrets = ( new Secrets() )->get( $action, $user_id );
5481
5482
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5483
			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...
5484
		}
5485
5486
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5487
			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...
5488
		}
5489
5490
		return $secrets;
5491
	}
5492
5493
	/**
5494
	 * Builds the timeout limit for queries talking with the wpcom servers.
5495
	 *
5496
	 * Based on local php max_execution_time in php.ini
5497
	 *
5498
	 * @since 2.6
5499
	 * @return int
5500
	 * @deprecated
5501
	 **/
5502
	public function get_remote_query_timeout_limit() {
5503
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5504
		return self::get_max_execution_time();
5505
	}
5506
5507
	/**
5508
	 * Builds the timeout limit for queries talking with the wpcom servers.
5509
	 *
5510
	 * Based on local php max_execution_time in php.ini
5511
	 *
5512
	 * @since 5.4
5513
	 * @return int
5514
	 **/
5515
	public static function get_max_execution_time() {
5516
		$timeout = (int) ini_get( 'max_execution_time' );
5517
5518
		// Ensure exec time set in php.ini
5519
		if ( ! $timeout ) {
5520
			$timeout = 30;
5521
		}
5522
		return $timeout;
5523
	}
5524
5525
	/**
5526
	 * Sets a minimum request timeout, and returns the current timeout
5527
	 *
5528
	 * @since 5.4
5529
	 **/
5530 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5531
		$timeout = self::get_max_execution_time();
5532
		if ( $timeout < $min_timeout ) {
5533
			$timeout = $min_timeout;
5534
			set_time_limit( $timeout );
5535
		}
5536
		return $timeout;
5537
	}
5538
5539
	/**
5540
	 * Takes the response from the Jetpack register new site endpoint and
5541
	 * verifies it worked properly.
5542
	 *
5543
	 * @since 2.6
5544
	 * @deprecated since 7.7.0
5545
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5546
	 **/
5547
	public function validate_remote_register_response() {
5548
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5549
	}
5550
5551
	/**
5552
	 * @deprecated since Jetpack 9.7.0
5553
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
5554
	 *
5555
	 * @return bool|WP_Error
5556
	 */
5557
	public static function register() {
5558
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
5559
		return static::connection()->try_registration( false );
5560
	}
5561
5562
	/**
5563
	 * Filters the registration request body to include tracking properties.
5564
	 *
5565
	 * @deprecated since Jetpack 9.7.0
5566
	 * @see Automattic\Jetpack\Connection\Utils::filter_register_request_body()
5567
	 *
5568
	 * @param array $properties
5569
	 * @return array amended properties.
5570
	 */
5571
	public static function filter_register_request_body( $properties ) {
5572
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Utils::filter_register_request_body' );
5573
		return Connection_Utils::filter_register_request_body( $properties );
5574
	}
5575
5576
	/**
5577
	 * Filters the token request body to include tracking properties.
5578
	 *
5579
	 * @param array $properties
5580
	 * @return array amended properties.
5581
	 */
5582 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5583
		$tracking        = new Tracking();
5584
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5585
5586
		return array_merge(
5587
			$properties,
5588
			array(
5589
				'_ui' => $tracks_identity['_ui'],
5590
				'_ut' => $tracks_identity['_ut'],
5591
			)
5592
		);
5593
	}
5594
5595
	/**
5596
	 * If the db version is showing something other that what we've got now, bump it to current.
5597
	 *
5598
	 * @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...
5599
	 */
5600
	public static function maybe_set_version_option() {
5601
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5602
		if ( JETPACK__VERSION != $version ) {
5603
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5604
5605
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5606
				/** This action is documented in class.jetpack.php */
5607
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5608
			}
5609
5610
			return true;
5611
		}
5612
		return false;
5613
	}
5614
5615
	/* Client Server API */
5616
5617
	/**
5618
	 * Loads the Jetpack XML-RPC client.
5619
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5620
	 *
5621
	 * @deprecated since 7.7.0
5622
	 */
5623
	public static function load_xml_rpc_client() {
5624
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5625
	}
5626
5627
	/**
5628
	 * Resets the saved authentication state in between testing requests.
5629
	 *
5630
	 * @deprecated since 8.9.0
5631
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5632
	 */
5633
	public function reset_saved_auth_state() {
5634
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5635
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5636
	}
5637
5638
	/**
5639
	 * Verifies the signature of the current request.
5640
	 *
5641
	 * @deprecated since 7.7.0
5642
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5643
	 *
5644
	 * @return false|array
5645
	 */
5646
	public function verify_xml_rpc_signature() {
5647
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5648
		return self::connection()->verify_xml_rpc_signature();
5649
	}
5650
5651
	/**
5652
	 * Verifies the signature of the current request.
5653
	 *
5654
	 * This function has side effects and should not be used. Instead,
5655
	 * use the memoized version `->verify_xml_rpc_signature()`.
5656
	 *
5657
	 * @deprecated since 7.7.0
5658
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5659
	 * @internal
5660
	 */
5661
	private function internal_verify_xml_rpc_signature() {
5662
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5663
	}
5664
5665
	/**
5666
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5667
	 *
5668
	 * @deprecated since 7.7.0
5669
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5670
	 *
5671
	 * @param \WP_User|mixed $user     User object if authenticated.
5672
	 * @param string         $username Username.
5673
	 * @param string         $password Password string.
5674
	 * @return \WP_User|mixed Authenticated user or error.
5675
	 */
5676 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5677
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5678
5679
		if ( ! $this->connection_manager ) {
5680
			$this->connection_manager = new Connection_Manager();
5681
		}
5682
5683
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5684
	}
5685
5686
	/**
5687
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5688
	 * Uses the existing XMLRPC request signing implementation.
5689
	 *
5690
	 * @deprecated since 8.9.0
5691
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5692
	 */
5693
	function wp_rest_authenticate( $user ) {
5694
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5695
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5696
	}
5697
5698
	/**
5699
	 * Report authentication status to the WP REST API.
5700
	 *
5701
	 * @deprecated since 8.9.0
5702
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5703
	 *
5704
	 * @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...
5705
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5706
	 */
5707
	public function wp_rest_authentication_errors( $value ) {
5708
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5709
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5710
	}
5711
5712
	/**
5713
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5714
	 * Capture it here so we can verify the signature later.
5715
	 *
5716
	 * @deprecated since 7.7.0
5717
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5718
	 *
5719
	 * @param array $methods XMLRPC methods.
5720
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5721
	 */
5722 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5723
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5724
5725
		if ( ! $this->connection_manager ) {
5726
			$this->connection_manager = new Connection_Manager();
5727
		}
5728
5729
		return $this->connection_manager->xmlrpc_methods( $methods );
5730
	}
5731
5732
	/**
5733
	 * Register additional public XMLRPC methods.
5734
	 *
5735
	 * @deprecated since 7.7.0
5736
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5737
	 *
5738
	 * @param array $methods Public XMLRPC methods.
5739
	 * @return array Public XMLRPC methods, with the getOptions one.
5740
	 */
5741 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5742
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5743
5744
		if ( ! $this->connection_manager ) {
5745
			$this->connection_manager = new Connection_Manager();
5746
		}
5747
5748
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5749
	}
5750
5751
	/**
5752
	 * Handles a getOptions XMLRPC method call.
5753
	 *
5754
	 * @deprecated since 7.7.0
5755
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5756
	 *
5757
	 * @param array $args method call arguments.
5758
	 * @return array an amended XMLRPC server options array.
5759
	 */
5760 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5761
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5762
5763
		if ( ! $this->connection_manager ) {
5764
			$this->connection_manager = new Connection_Manager();
5765
		}
5766
5767
		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...
5768
	}
5769
5770
	/**
5771
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5772
	 *
5773
	 * @deprecated since 7.7.0
5774
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5775
	 *
5776
	 * @param array $options Standard Core options.
5777
	 * @return array Amended options.
5778
	 */
5779 View Code Duplication
	public function xmlrpc_options( $options ) {
5780
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5781
5782
		if ( ! $this->connection_manager ) {
5783
			$this->connection_manager = new Connection_Manager();
5784
		}
5785
5786
		return $this->connection_manager->xmlrpc_options( $options );
5787
	}
5788
5789
	/**
5790
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5791
	 * SET: state( $key, $value );
5792
	 * GET: $value = state( $key );
5793
	 *
5794
	 * @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...
5795
	 * @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...
5796
	 * @param bool   $restate private
5797
	 */
5798
	public static function state( $key = null, $value = null, $restate = false ) {
5799
		static $state = array();
5800
		static $path, $domain;
5801
		if ( ! isset( $path ) ) {
5802
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5803
			$admin_url = self::admin_url();
5804
			$bits      = wp_parse_url( $admin_url );
5805
5806
			if ( is_array( $bits ) ) {
5807
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5808
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5809
			} else {
5810
				$path = $domain = null;
5811
			}
5812
		}
5813
5814
		// Extract state from cookies and delete cookies
5815
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5816
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5817
			unset( $_COOKIE['jetpackState'] );
5818
			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...
5819
				if ( strlen( $v ) ) {
5820
					$state[ $k ] = $v;
5821
				}
5822
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5823
			}
5824
		}
5825
5826
		if ( $restate ) {
5827
			foreach ( $state as $k => $v ) {
5828
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5829
			}
5830
			return;
5831
		}
5832
5833
		// Get a state variable.
5834
		if ( isset( $key ) && ! isset( $value ) ) {
5835
			if ( array_key_exists( $key, $state ) ) {
5836
				return $state[ $key ];
5837
			}
5838
			return null;
5839
		}
5840
5841
		// Set a state variable.
5842
		if ( isset( $key ) && isset( $value ) ) {
5843
			if ( is_array( $value ) && isset( $value[0] ) ) {
5844
				$value = $value[0];
5845
			}
5846
			$state[ $key ] = $value;
5847
			if ( ! headers_sent() ) {
5848
				if ( self::should_set_cookie( $key ) ) {
5849
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5850
				}
5851
			}
5852
		}
5853
	}
5854
5855
	public static function restate() {
5856
		self::state( null, null, true );
5857
	}
5858
5859
	/**
5860
	 * Determines whether the jetpackState[$key] value should be added to the
5861
	 * cookie.
5862
	 *
5863
	 * @param string $key The state key.
5864
	 *
5865
	 * @return boolean Whether the value should be added to the cookie.
5866
	 */
5867
	public static function should_set_cookie( $key ) {
5868
		global $current_screen;
5869
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5870
5871
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5872
			return false;
5873
		}
5874
5875
		return true;
5876
	}
5877
5878
	public static function check_privacy( $file ) {
5879
		static $is_site_publicly_accessible = null;
5880
5881
		if ( is_null( $is_site_publicly_accessible ) ) {
5882
			$is_site_publicly_accessible = false;
5883
5884
			$rpc = new Jetpack_IXR_Client();
5885
5886
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5887
			if ( $success ) {
5888
				$response = $rpc->getResponse();
5889
				if ( $response ) {
5890
					$is_site_publicly_accessible = true;
5891
				}
5892
			}
5893
5894
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5895
		}
5896
5897
		if ( $is_site_publicly_accessible ) {
5898
			return;
5899
		}
5900
5901
		$module_slug = self::get_module_slug( $file );
5902
5903
		$privacy_checks = self::state( 'privacy_checks' );
5904
		if ( ! $privacy_checks ) {
5905
			$privacy_checks = $module_slug;
5906
		} else {
5907
			$privacy_checks .= ",$module_slug";
5908
		}
5909
5910
		self::state( 'privacy_checks', $privacy_checks );
5911
	}
5912
5913
	/**
5914
	 * Helper method for multicall XMLRPC.
5915
	 *
5916
	 * @deprecated since 8.9.0
5917
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5918
	 *
5919
	 * @param ...$args Args for the async_call.
5920
	 */
5921
	public static function xmlrpc_async_call( ...$args ) {
5922
5923
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5924
5925
		global $blog_id;
5926
		static $clients = array();
5927
5928
		$client_blog_id = is_multisite() ? $blog_id : 0;
5929
5930
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5931
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5932
			if ( function_exists( 'ignore_user_abort' ) ) {
5933
				ignore_user_abort( true );
5934
			}
5935
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5936
		}
5937
5938
		if ( ! empty( $args[0] ) ) {
5939
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5940
		} elseif ( is_multisite() ) {
5941
			foreach ( $clients as $client_blog_id => $client ) {
5942
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5943
					continue;
5944
				}
5945
5946
				$switch_success = switch_to_blog( $client_blog_id, true );
5947
				if ( ! $switch_success ) {
5948
					continue;
5949
				}
5950
5951
				flush();
5952
				$client->query();
5953
5954
				restore_current_blog();
5955
			}
5956
		} else {
5957
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5958
				flush();
5959
				$clients[0]->query();
5960
			}
5961
		}
5962
	}
5963
5964
	/**
5965
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5966
	 *
5967
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5968
	 *
5969
	 * @param string $url WordPress.com static resource URL.
5970
	 */
5971
	public static function staticize_subdomain( $url ) {
5972
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5973
		return Assets::staticize_subdomain( $url );
5974
	}
5975
5976
	/* JSON API Authorization */
5977
5978
	/**
5979
	 * Handles the login action for Authorizing the JSON API
5980
	 */
5981
	function login_form_json_api_authorization() {
5982
		$this->verify_json_api_authorization_request();
5983
5984
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5985
5986
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5987
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5988
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5989
	}
5990
5991
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5992
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5993
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5994
			return $url;
5995
		}
5996
5997
		$parsed_url = wp_parse_url( $url );
5998
		$url        = strtok( $url, '?' );
5999
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
6000
		if ( ! empty( $parsed_url['query'] ) ) {
6001
			$url .= "&{$parsed_url['query']}";
6002
		}
6003
6004
		return $url;
6005
	}
6006
6007
	// Make sure the POSTed request is handled by the same action
6008
	function preserve_action_in_login_form_for_json_api_authorization() {
6009
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6010
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6011
	}
6012
6013
	// If someone logs in to approve API access, store the Access Code in usermeta
6014
	function store_json_api_authorization_token( $user_login, $user ) {
6015
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6016
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6017
		$token = wp_generate_password( 32, false );
6018
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6019
	}
6020
6021
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
6022
	function allow_wpcom_public_api_domain( $domains ) {
6023
		$domains[] = 'public-api.wordpress.com';
6024
		return $domains;
6025
	}
6026
6027
	static function is_redirect_encoded( $redirect_url ) {
6028
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
6029
	}
6030
6031
	// Add all wordpress.com environments to the safe redirect allowed list.
6032
	function allow_wpcom_environments( $domains ) {
6033
		$domains[] = 'wordpress.com';
6034
		$domains[] = 'wpcalypso.wordpress.com';
6035
		$domains[] = 'horizon.wordpress.com';
6036
		$domains[] = 'calypso.localhost';
6037
		return $domains;
6038
	}
6039
6040
	// Add the Access Code details to the public-api.wordpress.com redirect
6041
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6042
		return add_query_arg(
6043
			urlencode_deep(
6044
				array(
6045
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6046
					'jetpack-user-id' => (int) $user->ID,
6047
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6048
				)
6049
			),
6050
			$redirect_to
6051
		);
6052
	}
6053
6054
	/**
6055
	 * Verifies the request by checking the signature
6056
	 *
6057
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6058
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6059
	 *
6060
	 * @param null|array $environment
6061
	 */
6062
	function verify_json_api_authorization_request( $environment = null ) {
6063
		$environment = is_null( $environment )
6064
			? $_REQUEST
6065
			: $environment;
6066
6067
		//phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
6068
		list( $env_token, $env_version, $env_user_id ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $env_version is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
6069
		$token = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
6070
		if ( ! $token || empty( $token->secret ) ) {
6071
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6072
		}
6073
6074
		$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' );
6075
6076
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6077
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6078
			/**
6079
			 * Jetpack authorisation request Error.
6080
			 *
6081
			 * @since 7.5.0
6082
			 */
6083
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6084
			$die_error = sprintf(
6085
				/* translators: %s is a URL */
6086
				__( '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' ),
6087
				Redirect::get_url( 'jetpack-support-double-encoding' )
6088
			);
6089
		}
6090
6091
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6092
6093
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6094
			$signature = $jetpack_signature->sign_request(
6095
				$environment['token'],
6096
				$environment['timestamp'],
6097
				$environment['nonce'],
6098
				'',
6099
				'GET',
6100
				$environment['jetpack_json_api_original_query'],
6101
				null,
6102
				true
6103
			);
6104
		} else {
6105
			$signature = $jetpack_signature->sign_current_request(
6106
				array(
6107
					'body'   => null,
6108
					'method' => 'GET',
6109
				)
6110
			);
6111
		}
6112
6113
		if ( ! $signature ) {
6114
			wp_die( $die_error );
6115
		} elseif ( is_wp_error( $signature ) ) {
6116
			wp_die( $die_error );
6117
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6118
			if ( is_ssl() ) {
6119
				// 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
6120
				$signature = $jetpack_signature->sign_current_request(
6121
					array(
6122
						'scheme' => 'http',
6123
						'body'   => null,
6124
						'method' => 'GET',
6125
					)
6126
				);
6127
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6128
					wp_die( $die_error );
6129
				}
6130
			} else {
6131
				wp_die( $die_error );
6132
			}
6133
		}
6134
6135
		$timestamp = (int) $environment['timestamp'];
6136
		$nonce     = stripslashes( (string) $environment['nonce'] );
6137
6138
		if ( ! $this->connection_manager ) {
6139
			$this->connection_manager = new Connection_Manager();
6140
		}
6141
6142
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
6143
			// De-nonce the nonce, at least for 5 minutes.
6144
			// 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)
6145
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6146
			if ( $old_nonce_time < time() - 300 ) {
6147
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6148
			}
6149
		}
6150
6151
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6152
		$data_filters = array(
6153
			'state'        => 'opaque',
6154
			'client_id'    => 'int',
6155
			'client_title' => 'string',
6156
			'client_image' => 'url',
6157
		);
6158
6159
		foreach ( $data_filters as $key => $sanitation ) {
6160
			if ( ! isset( $data->$key ) ) {
6161
				wp_die( $die_error );
6162
			}
6163
6164
			switch ( $sanitation ) {
6165
				case 'int':
6166
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6167
					break;
6168
				case 'opaque':
6169
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6170
					break;
6171
				case 'string':
6172
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6173
					break;
6174
				case 'url':
6175
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6176
					break;
6177
			}
6178
		}
6179
6180
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6181
			wp_die( $die_error );
6182
		}
6183
	}
6184
6185
	function login_message_json_api_authorization( $message ) {
6186
		return '<p class="message">' . sprintf(
6187
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6188
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6189
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6190
	}
6191
6192
	/**
6193
	 * Get $content_width, but with a <s>twist</s> filter.
6194
	 */
6195
	public static function get_content_width() {
6196
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6197
			? $GLOBALS['content_width']
6198
			: false;
6199
		/**
6200
		 * Filter the Content Width value.
6201
		 *
6202
		 * @since 2.2.3
6203
		 *
6204
		 * @param string $content_width Content Width value.
6205
		 */
6206
		return apply_filters( 'jetpack_content_width', $content_width );
6207
	}
6208
6209
	/**
6210
	 * Pings the WordPress.com Mirror Site for the specified options.
6211
	 *
6212
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6213
	 *
6214
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6215
	 */
6216
	public function get_cloud_site_options( $option_names ) {
6217
		$option_names = array_filter( (array) $option_names, 'is_string' );
6218
6219
		$xml = new Jetpack_IXR_Client();
6220
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6221
		if ( $xml->isError() ) {
6222
			return array(
6223
				'error_code' => $xml->getErrorCode(),
6224
				'error_msg'  => $xml->getErrorMessage(),
6225
			);
6226
		}
6227
		$cloud_site_options = $xml->getResponse();
6228
6229
		return $cloud_site_options;
6230
	}
6231
6232
	/**
6233
	 * Checks if the site is currently in an identity crisis.
6234
	 *
6235
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6236
	 */
6237
	public static function check_identity_crisis() {
6238
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6239
			return false;
6240
		}
6241
6242
		return Jetpack_Options::get_option( 'sync_error_idc' );
6243
	}
6244
6245
	/**
6246
	 * Checks whether the home and siteurl specifically are allowed.
6247
	 * Written so that we don't have re-check $key and $value params every time
6248
	 * we want to check if this site is allowed, for example in footer.php
6249
	 *
6250
	 * @since  3.8.0
6251
	 * @return bool True = already allowed False = not on the allowed list.
6252
	 */
6253
	public static function is_staging_site() {
6254
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6255
		return ( new Status() )->is_staging_site();
6256
	}
6257
6258
	/**
6259
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6260
	 *
6261
	 * @since 4.4.0
6262
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6263
	 *
6264
	 * @return bool
6265
	 */
6266
	public static function validate_sync_error_idc_option() {
6267
		$is_valid = false;
6268
6269
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6270
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6271
		if ( $sync_error && self::sync_idc_optin() ) {
6272
			$local_options = self::get_sync_error_idc_option();
6273
			// Ensure all values are set.
6274
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6275
6276
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6277
				if (
6278
						isset( $sync_error['wpcom_home'] ) &&
6279
						isset( $sync_error['wpcom_siteurl'] ) &&
6280
						$sync_error['wpcom_home'] === $local_options['home'] &&
6281
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6282
				) {
6283
					$is_valid = false;
6284
					// Enable migrate_for_idc so that sync actions are accepted.
6285
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6286
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6287
					$is_valid = true;
6288
				}
6289
			}
6290
		}
6291
6292
		/**
6293
		 * Filters whether the sync_error_idc option is valid.
6294
		 *
6295
		 * @since 4.4.0
6296
		 *
6297
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6298
		 */
6299
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6300
6301
		if ( ! $is_valid && $sync_error ) {
6302
			// Since the option exists, and did not validate, delete it
6303
			Jetpack_Options::delete_option( 'sync_error_idc' );
6304
		}
6305
6306
		return $is_valid;
6307
	}
6308
6309
	/**
6310
	 * Normalizes a url by doing three things:
6311
	 *  - Strips protocol
6312
	 *  - Strips www
6313
	 *  - Adds a trailing slash
6314
	 *
6315
	 * @since 4.4.0
6316
	 * @param string $url
6317
	 * @return WP_Error|string
6318
	 */
6319
	public static function normalize_url_protocol_agnostic( $url ) {
6320
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6321
		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...
6322
			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...
6323
		}
6324
6325
		// Strip www and protocols
6326
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6327
		return $url;
6328
	}
6329
6330
	/**
6331
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6332
	 *
6333
	 * @since 4.4.0
6334
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6335
	 *
6336
	 * @param array $response
6337
	 * @return array Array of the local urls, wpcom urls, and error code
6338
	 */
6339
	public static function get_sync_error_idc_option( $response = array() ) {
6340
		// Since the local options will hit the database directly, store the values
6341
		// in a transient to allow for autoloading and caching on subsequent views.
6342
		$local_options = get_transient( 'jetpack_idc_local' );
6343
		if ( false === $local_options ) {
6344
			$local_options = array(
6345
				'home'    => Functions::home_url(),
6346
				'siteurl' => Functions::site_url(),
6347
			);
6348
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6349
		}
6350
6351
		$options = array_merge( $local_options, $response );
6352
6353
		$returned_values = array();
6354
		foreach ( $options as $key => $option ) {
6355
			if ( 'error_code' === $key ) {
6356
				$returned_values[ $key ] = $option;
6357
				continue;
6358
			}
6359
6360
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6361
				continue;
6362
			}
6363
6364
			$returned_values[ $key ] = $normalized_url;
6365
		}
6366
6367
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6368
6369
		return $returned_values;
6370
	}
6371
6372
	/**
6373
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6374
	 * If set to true, the site will be put into staging mode.
6375
	 *
6376
	 * @since 4.3.2
6377
	 * @return bool
6378
	 */
6379
	public static function sync_idc_optin() {
6380
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6381
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6382
		} else {
6383
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6384
		}
6385
6386
		/**
6387
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
6388
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
6389
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6390
		 *
6391
		 * @since 4.3.2
6392
		 *
6393
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6394
		 */
6395
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6396
	}
6397
6398
	/**
6399
	 * Maybe Use a .min.css stylesheet, maybe not.
6400
	 *
6401
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6402
	 */
6403
	public static function maybe_min_asset( $url, $path, $plugin ) {
6404
		// Short out on things trying to find actual paths.
6405
		if ( ! $path || empty( $plugin ) ) {
6406
			return $url;
6407
		}
6408
6409
		$path = ltrim( $path, '/' );
6410
6411
		// Strip out the abspath.
6412
		$base = dirname( plugin_basename( $plugin ) );
6413
6414
		// Short out on non-Jetpack assets.
6415
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6416
			return $url;
6417
		}
6418
6419
		// File name parsing.
6420
		$file              = "{$base}/{$path}";
6421
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6422
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6423
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6424
		$extension         = array_shift( $file_name_parts_r );
6425
6426
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6427
			// Already pointing at the minified version.
6428
			if ( 'min' === $file_name_parts_r[0] ) {
6429
				return $url;
6430
			}
6431
6432
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6433
			if ( file_exists( $min_full_path ) ) {
6434
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6435
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6436
				if ( 'css' === $extension ) {
6437
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6438
					self::$min_assets[ $key ] = $path;
6439
				}
6440
			}
6441
		}
6442
6443
		return $url;
6444
	}
6445
6446
	/**
6447
	 * If the asset is minified, let's flag .min as the suffix.
6448
	 *
6449
	 * Attached to `style_loader_src` filter.
6450
	 *
6451
	 * @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...
6452
	 * @param string $handle The registered handle of the script in question.
6453
	 * @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...
6454
	 */
6455
	public static function set_suffix_on_min( $src, $handle ) {
6456
		if ( false === strpos( $src, '.min.css' ) ) {
6457
			return $src;
6458
		}
6459
6460
		if ( ! empty( self::$min_assets ) ) {
6461
			foreach ( self::$min_assets as $file => $path ) {
6462
				if ( false !== strpos( $src, $file ) ) {
6463
					wp_style_add_data( $handle, 'suffix', '.min' );
6464
					return $src;
6465
				}
6466
			}
6467
		}
6468
6469
		return $src;
6470
	}
6471
6472
	/**
6473
	 * Maybe inlines a stylesheet.
6474
	 *
6475
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6476
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6477
	 *
6478
	 * Attached to `style_loader_tag` filter.
6479
	 *
6480
	 * @param string $tag The tag that would link to the external asset.
6481
	 * @param string $handle The registered handle of the script in question.
6482
	 *
6483
	 * @return string
6484
	 */
6485
	public static function maybe_inline_style( $tag, $handle ) {
6486
		global $wp_styles;
6487
		$item = $wp_styles->registered[ $handle ];
6488
6489
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6490
			return $tag;
6491
		}
6492
6493
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6494
			$href = $matches[1];
6495
			// Strip off query string
6496
			if ( $pos = strpos( $href, '?' ) ) {
6497
				$href = substr( $href, 0, $pos );
6498
			}
6499
			// Strip off fragment
6500
			if ( $pos = strpos( $href, '#' ) ) {
6501
				$href = substr( $href, 0, $pos );
6502
			}
6503
		} else {
6504
			return $tag;
6505
		}
6506
6507
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6508
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6509
			return $tag;
6510
		}
6511
6512
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6513
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6514
			// And this isn't the pass that actually deals with the RTL version...
6515
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6516
				// Short out, as the RTL version will deal with it in a moment.
6517
				return $tag;
6518
			}
6519
		}
6520
6521
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6522
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6523
		if ( $css ) {
6524
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6525
			if ( empty( $item->extra['after'] ) ) {
6526
				wp_add_inline_style( $handle, $css );
6527
			} else {
6528
				array_unshift( $item->extra['after'], $css );
6529
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6530
			}
6531
		}
6532
6533
		return $tag;
6534
	}
6535
6536
	/**
6537
	 * Loads a view file from the views
6538
	 *
6539
	 * Data passed in with the $data parameter will be available in the
6540
	 * template file as $data['value']
6541
	 *
6542
	 * @param string $template - Template file to load
6543
	 * @param array  $data - Any data to pass along to the template
6544
	 * @return boolean - If template file was found
6545
	 **/
6546
	public function load_view( $template, $data = array() ) {
6547
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6548
6549
		if ( file_exists( $views_dir . $template ) ) {
6550
			require_once $views_dir . $template;
6551
			return true;
6552
		}
6553
6554
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6555
		return false;
6556
	}
6557
6558
	/**
6559
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6560
	 */
6561
	public function deprecated_hooks() {
6562
		$filter_deprecated_list = array(
6563
			'jetpack_bail_on_shortcode'                    => array(
6564
				'replacement' => 'jetpack_shortcodes_to_include',
6565
				'version'     => 'jetpack-3.1.0',
6566
			),
6567
			'wpl_sharing_2014_1'                           => array(
6568
				'replacement' => null,
6569
				'version'     => 'jetpack-3.6.0',
6570
			),
6571
			'jetpack-tools-to-include'                     => array(
6572
				'replacement' => 'jetpack_tools_to_include',
6573
				'version'     => 'jetpack-3.9.0',
6574
			),
6575
			'jetpack_identity_crisis_options_to_check'     => array(
6576
				'replacement' => null,
6577
				'version'     => 'jetpack-4.0.0',
6578
			),
6579
			'update_option_jetpack_single_user_site'       => array(
6580
				'replacement' => null,
6581
				'version'     => 'jetpack-4.3.0',
6582
			),
6583
			'audio_player_default_colors'                  => array(
6584
				'replacement' => null,
6585
				'version'     => 'jetpack-4.3.0',
6586
			),
6587
			'add_option_jetpack_featured_images_enabled'   => array(
6588
				'replacement' => null,
6589
				'version'     => 'jetpack-4.3.0',
6590
			),
6591
			'add_option_jetpack_update_details'            => array(
6592
				'replacement' => null,
6593
				'version'     => 'jetpack-4.3.0',
6594
			),
6595
			'add_option_jetpack_updates'                   => array(
6596
				'replacement' => null,
6597
				'version'     => 'jetpack-4.3.0',
6598
			),
6599
			'add_option_jetpack_network_name'              => array(
6600
				'replacement' => null,
6601
				'version'     => 'jetpack-4.3.0',
6602
			),
6603
			'add_option_jetpack_network_allow_new_registrations' => array(
6604
				'replacement' => null,
6605
				'version'     => 'jetpack-4.3.0',
6606
			),
6607
			'add_option_jetpack_network_add_new_users'     => array(
6608
				'replacement' => null,
6609
				'version'     => 'jetpack-4.3.0',
6610
			),
6611
			'add_option_jetpack_network_site_upload_space' => array(
6612
				'replacement' => null,
6613
				'version'     => 'jetpack-4.3.0',
6614
			),
6615
			'add_option_jetpack_network_upload_file_types' => array(
6616
				'replacement' => null,
6617
				'version'     => 'jetpack-4.3.0',
6618
			),
6619
			'add_option_jetpack_network_enable_administration_menus' => array(
6620
				'replacement' => null,
6621
				'version'     => 'jetpack-4.3.0',
6622
			),
6623
			'add_option_jetpack_is_multi_site'             => array(
6624
				'replacement' => null,
6625
				'version'     => 'jetpack-4.3.0',
6626
			),
6627
			'add_option_jetpack_is_main_network'           => array(
6628
				'replacement' => null,
6629
				'version'     => 'jetpack-4.3.0',
6630
			),
6631
			'add_option_jetpack_main_network_site'         => array(
6632
				'replacement' => null,
6633
				'version'     => 'jetpack-4.3.0',
6634
			),
6635
			'jetpack_sync_all_registered_options'          => array(
6636
				'replacement' => null,
6637
				'version'     => 'jetpack-4.3.0',
6638
			),
6639
			'jetpack_has_identity_crisis'                  => array(
6640
				'replacement' => 'jetpack_sync_error_idc_validation',
6641
				'version'     => 'jetpack-4.4.0',
6642
			),
6643
			'jetpack_is_post_mailable'                     => array(
6644
				'replacement' => null,
6645
				'version'     => 'jetpack-4.4.0',
6646
			),
6647
			'jetpack_seo_site_host'                        => array(
6648
				'replacement' => null,
6649
				'version'     => 'jetpack-5.1.0',
6650
			),
6651
			'jetpack_installed_plugin'                     => array(
6652
				'replacement' => 'jetpack_plugin_installed',
6653
				'version'     => 'jetpack-6.0.0',
6654
			),
6655
			'jetpack_holiday_snow_option_name'             => array(
6656
				'replacement' => null,
6657
				'version'     => 'jetpack-6.0.0',
6658
			),
6659
			'jetpack_holiday_chance_of_snow'               => array(
6660
				'replacement' => null,
6661
				'version'     => 'jetpack-6.0.0',
6662
			),
6663
			'jetpack_holiday_snow_js_url'                  => array(
6664
				'replacement' => null,
6665
				'version'     => 'jetpack-6.0.0',
6666
			),
6667
			'jetpack_is_holiday_snow_season'               => array(
6668
				'replacement' => null,
6669
				'version'     => 'jetpack-6.0.0',
6670
			),
6671
			'jetpack_holiday_snow_option_updated'          => array(
6672
				'replacement' => null,
6673
				'version'     => 'jetpack-6.0.0',
6674
			),
6675
			'jetpack_holiday_snowing'                      => array(
6676
				'replacement' => null,
6677
				'version'     => 'jetpack-6.0.0',
6678
			),
6679
			'jetpack_sso_auth_cookie_expirtation'          => array(
6680
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6681
				'version'     => 'jetpack-6.1.0',
6682
			),
6683
			'jetpack_cache_plans'                          => array(
6684
				'replacement' => null,
6685
				'version'     => 'jetpack-6.1.0',
6686
			),
6687
6688
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6689
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6690
				'version'     => 'jetpack-6.5.0',
6691
			),
6692
			'jetpack_enable_site_verification'             => array(
6693
				'replacement' => null,
6694
				'version'     => 'jetpack-6.5.0',
6695
			),
6696
			'can_display_jetpack_manage_notice'            => array(
6697
				'replacement' => null,
6698
				'version'     => 'jetpack-7.3.0',
6699
			),
6700
			'atd_http_post_timeout'                        => array(
6701
				'replacement' => null,
6702
				'version'     => 'jetpack-7.3.0',
6703
			),
6704
			'atd_service_domain'                           => array(
6705
				'replacement' => null,
6706
				'version'     => 'jetpack-7.3.0',
6707
			),
6708
			'atd_load_scripts'                             => array(
6709
				'replacement' => null,
6710
				'version'     => 'jetpack-7.3.0',
6711
			),
6712
			'jetpack_widget_authors_exclude'               => array(
6713
				'replacement' => 'jetpack_widget_authors_params',
6714
				'version'     => 'jetpack-7.7.0',
6715
			),
6716
			// Removed in Jetpack 7.9.0
6717
			'jetpack_pwa_manifest'                         => array(
6718
				'replacement' => null,
6719
				'version'     => 'jetpack-7.9.0',
6720
			),
6721
			'jetpack_pwa_background_color'                 => array(
6722
				'replacement' => null,
6723
				'version'     => 'jetpack-7.9.0',
6724
			),
6725
			'jetpack_check_mobile'                         => array(
6726
				'replacement' => null,
6727
				'version'     => 'jetpack-8.3.0',
6728
			),
6729
			'jetpack_mobile_stylesheet'                    => array(
6730
				'replacement' => null,
6731
				'version'     => 'jetpack-8.3.0',
6732
			),
6733
			'jetpack_mobile_template'                      => array(
6734
				'replacement' => null,
6735
				'version'     => 'jetpack-8.3.0',
6736
			),
6737
			'jetpack_mobile_theme_menu'                    => array(
6738
				'replacement' => null,
6739
				'version'     => 'jetpack-8.3.0',
6740
			),
6741
			'minileven_show_featured_images'               => array(
6742
				'replacement' => null,
6743
				'version'     => 'jetpack-8.3.0',
6744
			),
6745
			'minileven_attachment_size'                    => array(
6746
				'replacement' => null,
6747
				'version'     => 'jetpack-8.3.0',
6748
			),
6749
			'instagram_cache_oembed_api_response_body'     => array(
6750
				'replacement' => null,
6751
				'version'     => 'jetpack-9.1.0',
6752
			),
6753
			'jetpack_can_make_outbound_https'              => array(
6754
				'replacement' => null,
6755
				'version'     => 'jetpack-9.1.0',
6756
			),
6757
		);
6758
6759
		foreach ( $filter_deprecated_list as $tag => $args ) {
6760
			if ( has_filter( $tag ) ) {
6761
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6762
			}
6763
		}
6764
6765
		$action_deprecated_list = array(
6766
			'jetpack_updated_theme'        => array(
6767
				'replacement' => 'jetpack_updated_themes',
6768
				'version'     => 'jetpack-6.2.0',
6769
			),
6770
			'atd_http_post_error'          => array(
6771
				'replacement' => null,
6772
				'version'     => 'jetpack-7.3.0',
6773
			),
6774
			'mobile_reject_mobile'         => array(
6775
				'replacement' => null,
6776
				'version'     => 'jetpack-8.3.0',
6777
			),
6778
			'mobile_force_mobile'          => array(
6779
				'replacement' => null,
6780
				'version'     => 'jetpack-8.3.0',
6781
			),
6782
			'mobile_app_promo_download'    => array(
6783
				'replacement' => null,
6784
				'version'     => 'jetpack-8.3.0',
6785
			),
6786
			'mobile_setup'                 => array(
6787
				'replacement' => null,
6788
				'version'     => 'jetpack-8.3.0',
6789
			),
6790
			'jetpack_mobile_footer_before' => array(
6791
				'replacement' => null,
6792
				'version'     => 'jetpack-8.3.0',
6793
			),
6794
			'wp_mobile_theme_footer'       => array(
6795
				'replacement' => null,
6796
				'version'     => 'jetpack-8.3.0',
6797
			),
6798
			'minileven_credits'            => array(
6799
				'replacement' => null,
6800
				'version'     => 'jetpack-8.3.0',
6801
			),
6802
			'jetpack_mobile_header_before' => array(
6803
				'replacement' => null,
6804
				'version'     => 'jetpack-8.3.0',
6805
			),
6806
			'jetpack_mobile_header_after'  => array(
6807
				'replacement' => null,
6808
				'version'     => 'jetpack-8.3.0',
6809
			),
6810
		);
6811
6812
		foreach ( $action_deprecated_list as $tag => $args ) {
6813
			if ( has_action( $tag ) ) {
6814
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6815
			}
6816
		}
6817
	}
6818
6819
	/**
6820
	 * Converts any url in a stylesheet, to the correct absolute url.
6821
	 *
6822
	 * Considerations:
6823
	 *  - Normal, relative URLs     `feh.png`
6824
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6825
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6826
	 *  - Absolute URLs             `http://domain.com/feh.png`
6827
	 *  - Domain root relative URLs `/feh.png`
6828
	 *
6829
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6830
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6831
	 *
6832
	 * @return mixed|string
6833
	 */
6834
	public static function absolutize_css_urls( $css, $css_file_url ) {
6835
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6836
		$css_dir = dirname( $css_file_url );
6837
		$p       = wp_parse_url( $css_dir );
6838
		$domain  = sprintf(
6839
			'%1$s//%2$s%3$s%4$s',
6840
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6841
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6842
			$p['host'],
6843
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6844
		);
6845
6846
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6847
			$find = $replace = array();
6848
			foreach ( $matches as $match ) {
6849
				$url = trim( $match['path'], "'\" \t" );
6850
6851
				// If this is a data url, we don't want to mess with it.
6852
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6853
					continue;
6854
				}
6855
6856
				// If this is an absolute or protocol-agnostic url,
6857
				// we don't want to mess with it.
6858
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6859
					continue;
6860
				}
6861
6862
				switch ( substr( $url, 0, 1 ) ) {
6863
					case '/':
6864
						$absolute = $domain . $url;
6865
						break;
6866
					default:
6867
						$absolute = $css_dir . '/' . $url;
6868
				}
6869
6870
				$find[]    = $match[0];
6871
				$replace[] = sprintf( 'url("%s")', $absolute );
6872
			}
6873
			$css = str_replace( $find, $replace, $css );
6874
		}
6875
6876
		return $css;
6877
	}
6878
6879
	/**
6880
	 * This methods removes all of the registered css files on the front end
6881
	 * from Jetpack in favor of using a single file. In effect "imploding"
6882
	 * all the files into one file.
6883
	 *
6884
	 * Pros:
6885
	 * - Uses only ONE css asset connection instead of 15
6886
	 * - Saves a minimum of 56k
6887
	 * - Reduces server load
6888
	 * - Reduces time to first painted byte
6889
	 *
6890
	 * Cons:
6891
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6892
	 *      should not cause any issues with themes.
6893
	 * - Plugins/themes dequeuing styles no longer do anything. See
6894
	 *      jetpack_implode_frontend_css filter for a workaround
6895
	 *
6896
	 * For some situations developers may wish to disable css imploding and
6897
	 * instead operate in legacy mode where each file loads seperately and
6898
	 * can be edited individually or dequeued. This can be accomplished with
6899
	 * the following line:
6900
	 *
6901
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6902
	 *
6903
	 * @since 3.2
6904
	 **/
6905
	public function implode_frontend_css( $travis_test = false ) {
6906
		$do_implode = true;
6907
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6908
			$do_implode = false;
6909
		}
6910
6911
		// Do not implode CSS when the page loads via the AMP plugin.
6912
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6913
			$do_implode = false;
6914
		}
6915
6916
		/**
6917
		 * Allow CSS to be concatenated into a single jetpack.css file.
6918
		 *
6919
		 * @since 3.2.0
6920
		 *
6921
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6922
		 */
6923
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6924
6925
		// Do not use the imploded file when default behavior was altered through the filter
6926
		if ( ! $do_implode ) {
6927
			return;
6928
		}
6929
6930
		// We do not want to use the imploded file in dev mode, or if not connected
6931
		if ( ( new Status() )->is_offline_mode() || ! self::is_connection_ready() ) {
6932
			if ( ! $travis_test ) {
6933
				return;
6934
			}
6935
		}
6936
6937
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6938
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6939
			return;
6940
		}
6941
6942
		/*
6943
		 * Now we assume Jetpack is connected and able to serve the single
6944
		 * file.
6945
		 *
6946
		 * In the future there will be a check here to serve the file locally
6947
		 * or potentially from the Jetpack CDN
6948
		 *
6949
		 * For now:
6950
		 * - Enqueue a single imploded css file
6951
		 * - Zero out the style_loader_tag for the bundled ones
6952
		 * - Be happy, drink scotch
6953
		 */
6954
6955
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6956
6957
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6958
6959
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6960
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6961
	}
6962
6963
	function concat_remove_style_loader_tag( $tag, $handle ) {
6964
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6965
			$tag = '';
6966
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6967
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6968
			}
6969
		}
6970
6971
		return $tag;
6972
	}
6973
6974
	/**
6975
	 * @deprecated
6976
	 * @see Automattic\Jetpack\Assets\add_aync_script
6977
	 */
6978
	public function script_add_async( $tag, $handle, $src ) {
6979
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6980
	}
6981
6982
	/*
6983
	 * Check the heartbeat data
6984
	 *
6985
	 * Organizes the heartbeat data by severity.  For example, if the site
6986
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6987
	 *
6988
	 * Data will be added to "caution" array, if it either:
6989
	 *  - Out of date Jetpack version
6990
	 *  - Out of date WP version
6991
	 *  - Out of date PHP version
6992
	 *
6993
	 * $return array $filtered_data
6994
	 */
6995
	public static function jetpack_check_heartbeat_data() {
6996
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6997
6998
		$good    = array();
6999
		$caution = array();
7000
		$bad     = array();
7001
7002
		foreach ( $raw_data as $stat => $value ) {
7003
7004
			// Check jetpack version
7005
			if ( 'version' == $stat ) {
7006
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
7007
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
7008
					continue;
7009
				}
7010
			}
7011
7012
			// Check WP version
7013
			if ( 'wp-version' == $stat ) {
7014
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
7015
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
7016
					continue;
7017
				}
7018
			}
7019
7020
			// Check PHP version
7021
			if ( 'php-version' == $stat ) {
7022
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
7023
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
7024
					continue;
7025
				}
7026
			}
7027
7028
			// Check ID crisis
7029
			if ( 'identitycrisis' == $stat ) {
7030
				if ( 'yes' == $value ) {
7031
					$bad[ $stat ] = $value;
7032
					continue;
7033
				}
7034
			}
7035
7036
			// The rest are good :)
7037
			$good[ $stat ] = $value;
7038
		}
7039
7040
		$filtered_data = array(
7041
			'good'    => $good,
7042
			'caution' => $caution,
7043
			'bad'     => $bad,
7044
		);
7045
7046
		return $filtered_data;
7047
	}
7048
7049
	/*
7050
	 * This method is used to organize all options that can be reset
7051
	 * without disconnecting Jetpack.
7052
	 *
7053
	 * It is used in class.jetpack-cli.php to reset options
7054
	 *
7055
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
7056
	 *
7057
	 * @return array of options to delete.
7058
	 */
7059
	public static function get_jetpack_options_for_reset() {
7060
		return Jetpack_Options::get_options_for_reset();
7061
	}
7062
7063
	/*
7064
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
7065
	 * so we can bring them directly to their site in calypso.
7066
	 *
7067
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
7068
	 *
7069
	 * @param string | url
7070
	 * @return string | url without the guff
7071
	 */
7072
	public static function build_raw_urls( $url ) {
7073
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
7074
7075
		return ( new Status() )->get_site_suffix( $url );
7076
	}
7077
7078
	/**
7079
	 * Stores and prints out domains to prefetch for page speed optimization.
7080
	 *
7081
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
7082
	 *
7083
	 * @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...
7084
	 */
7085
	public static function dns_prefetch( $urls = null ) {
7086
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
7087
		if ( $urls ) {
7088
			Assets::add_resource_hint( $urls );
7089
		}
7090
	}
7091
7092
	public function wp_dashboard_setup() {
7093
		if ( self::is_connection_ready() ) {
7094
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
7095
		}
7096
7097
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
7098
			$jetpack_logo = new Jetpack_Logo();
7099
			$widget_title = sprintf(
7100
				/* translators: Placeholder is a Jetpack logo. */
7101
				__( 'Stats by %s', 'jetpack' ),
7102
				$jetpack_logo->get_jp_emblem( true )
7103
			);
7104
7105
			// Wrap title in span so Logo can be properly styled.
7106
			$widget_title = sprintf(
7107
				'<span>%s</span>',
7108
				$widget_title
7109
			);
7110
7111
			wp_add_dashboard_widget(
7112
				'jetpack_summary_widget',
7113
				$widget_title,
7114
				array( __CLASS__, 'dashboard_widget' )
7115
			);
7116
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
7117
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
7118
7119
			// If we're inactive and not in offline mode, sort our box to the top.
7120
			if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
7121
				global $wp_meta_boxes;
7122
7123
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7124
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7125
7126
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7127
			}
7128
		}
7129
	}
7130
7131
	/**
7132
	 * @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...
7133
	 * @return mixed
7134
	 */
7135
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7136
		if ( ! is_array( $sorted ) ) {
7137
			return $sorted;
7138
		}
7139
7140
		foreach ( $sorted as $box_context => $ids ) {
7141
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7142
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7143
				continue;
7144
			}
7145
7146
			$ids_array = explode( ',', $ids );
7147
			$key       = array_search( 'dashboard_stats', $ids_array );
7148
7149
			if ( false !== $key ) {
7150
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7151
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7152
				$sorted[ $box_context ] = implode( ',', $ids_array );
7153
				// We've found it, stop searching, and just return.
7154
				break;
7155
			}
7156
		}
7157
7158
		return $sorted;
7159
	}
7160
7161
	public static function dashboard_widget() {
7162
		/**
7163
		 * Fires when the dashboard is loaded.
7164
		 *
7165
		 * @since 3.4.0
7166
		 */
7167
		do_action( 'jetpack_dashboard_widget' );
7168
	}
7169
7170
	public static function dashboard_widget_footer() {
7171
		?>
7172
		<footer>
7173
7174
		<div class="protect">
7175
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7176
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7177
				<p class="blocked-count">
7178
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7179
				</p>
7180
				<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>
7181
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7182
				<a href="
7183
				<?php
7184
				echo esc_url(
7185
					wp_nonce_url(
7186
						self::admin_url(
7187
							array(
7188
								'action' => 'activate',
7189
								'module' => 'protect',
7190
							)
7191
						),
7192
						'jetpack_activate-protect'
7193
					)
7194
				);
7195
				?>
7196
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7197
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7198
				</a>
7199
			<?php else : ?>
7200
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7201
			<?php endif; ?>
7202
		</div>
7203
7204
		<div class="akismet">
7205
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7206
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7207
				<p class="blocked-count">
7208
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7209
				</p>
7210
				<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>
7211
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7212
				<a href="
7213
				<?php
7214
				echo esc_url(
7215
					wp_nonce_url(
7216
						add_query_arg(
7217
							array(
7218
								'action' => 'activate',
7219
								'plugin' => 'akismet/akismet.php',
7220
							),
7221
							admin_url( 'plugins.php' )
7222
						),
7223
						'activate-plugin_akismet/akismet.php'
7224
					)
7225
				);
7226
				?>
7227
							" class="button button-jetpack">
7228
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7229
				</a>
7230
			<?php else : ?>
7231
				<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>
7232
			<?php endif; ?>
7233
		</div>
7234
7235
		</footer>
7236
		<?php
7237
	}
7238
7239
	/*
7240
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7241
	 */
7242
	function jetpack_icon_user_connected( $columns ) {
7243
		$columns['user_jetpack'] = '';
7244
		return $columns;
7245
	}
7246
7247
	/*
7248
	 * Show Jetpack icon if the user is linked.
7249
	 */
7250
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7251
		if ( 'user_jetpack' === $col && self::connection()->is_user_connected( $user_id ) ) {
7252
			$jetpack_logo = new Jetpack_Logo();
7253
			$emblem_html  = sprintf(
7254
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7255
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7256
				$jetpack_logo->get_jp_emblem()
7257
			);
7258
			return $emblem_html;
7259
		}
7260
7261
		return $val;
7262
	}
7263
7264
	/*
7265
	 * Style the Jetpack user column
7266
	 */
7267
	function jetpack_user_col_style() {
7268
		global $current_screen;
7269
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7270
			?>
7271
			<style>
7272
				.fixed .column-user_jetpack {
7273
					width: 21px;
7274
				}
7275
				.jp-emblem-user-admin svg {
7276
					width: 20px;
7277
					height: 20px;
7278
				}
7279
				.jp-emblem-user-admin path {
7280
					fill: #00BE28;
7281
				}
7282
			</style>
7283
			<?php
7284
		}
7285
	}
7286
7287
	/**
7288
	 * Checks if Akismet is active and working.
7289
	 *
7290
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7291
	 * that implied usage of methods present since more recent version.
7292
	 * See https://github.com/Automattic/jetpack/pull/9585
7293
	 *
7294
	 * @since  5.1.0
7295
	 *
7296
	 * @return bool True = Akismet available. False = Aksimet not available.
7297
	 */
7298
	public static function is_akismet_active() {
7299
		static $status = null;
7300
7301
		if ( ! is_null( $status ) ) {
7302
			return $status;
7303
		}
7304
7305
		// Check if a modern version of Akismet is active.
7306
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7307
			$status = false;
7308
			return $status;
7309
		}
7310
7311
		// Make sure there is a key known to Akismet at all before verifying key.
7312
		$akismet_key = Akismet::get_api_key();
7313
		if ( ! $akismet_key ) {
7314
			$status = false;
7315
			return $status;
7316
		}
7317
7318
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7319
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7320
7321
		// 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.
7322
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7323
		// We cache the result of the Akismet key verification for ten minutes.
7324
		if ( ! $akismet_key_state || $recheck ) {
7325
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7326
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7327
		}
7328
7329
		$status = 'valid' === $akismet_key_state;
7330
7331
		return $status;
7332
	}
7333
7334
	/**
7335
	 * @deprecated
7336
	 *
7337
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7338
	 */
7339
	public static function is_function_in_backtrace() {
7340
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7341
	}
7342
7343
	/**
7344
	 * Given a minified path, and a non-minified path, will return
7345
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7346
	 *
7347
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7348
	 * root Jetpack directory.
7349
	 *
7350
	 * @since 5.6.0
7351
	 *
7352
	 * @param string $min_path
7353
	 * @param string $non_min_path
7354
	 * @return string The URL to the file
7355
	 */
7356
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7357
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7358
	}
7359
7360
	/**
7361
	 * Checks for whether Jetpack Backup is enabled.
7362
	 * Will return true if the state of Backup is anything except "unavailable".
7363
	 *
7364
	 * @return bool|int|mixed
7365
	 */
7366
	public static function is_rewind_enabled() {
7367
		// Rewind is a paid feature, therefore requires a user-level connection.
7368
		if ( ! static::connection()->has_connected_owner() ) {
7369
			return false;
7370
		}
7371
7372
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7373
		if ( false === $rewind_enabled ) {
7374
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7375
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7376
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7377
				&& ! empty( $rewind_data['state'] )
7378
				&& 'active' === $rewind_data['state'] )
7379
				? 1
7380
				: 0;
7381
7382
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7383
		}
7384
		return $rewind_enabled;
7385
	}
7386
7387
	/**
7388
	 * Return Calypso environment value; used for developing Jetpack and pairing
7389
	 * it with different Calypso enrionments, such as localhost.
7390
	 *
7391
	 * @since 7.4.0
7392
	 *
7393
	 * @return string Calypso environment
7394
	 */
7395
	public static function get_calypso_env() {
7396
		if ( isset( $_GET['calypso_env'] ) ) {
7397
			return sanitize_key( $_GET['calypso_env'] );
7398
		}
7399
7400
		if ( getenv( 'CALYPSO_ENV' ) ) {
7401
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7402
		}
7403
7404
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7405
			return sanitize_key( CALYPSO_ENV );
7406
		}
7407
7408
		return '';
7409
	}
7410
7411
	/**
7412
	 * Returns the hostname with protocol for Calypso.
7413
	 * Used for developing Jetpack with Calypso.
7414
	 *
7415
	 * @since 8.4.0
7416
	 *
7417
	 * @return string Calypso host.
7418
	 */
7419
	public static function get_calypso_host() {
7420
		$calypso_env = self::get_calypso_env();
7421
		switch ( $calypso_env ) {
7422
			case 'development':
7423
				return 'http://calypso.localhost:3000/';
7424
			case 'wpcalypso':
7425
				return 'https://wpcalypso.wordpress.com/';
7426
			case 'horizon':
7427
				return 'https://horizon.wordpress.com/';
7428
			default:
7429
				return 'https://wordpress.com/';
7430
		}
7431
	}
7432
7433
	/**
7434
	 * Handles activating default modules as well general cleanup for the new connection.
7435
	 *
7436
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7437
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7438
	 * @param boolean $send_state_messages          Whether to send state messages.
7439
	 * @return void
7440
	 */
7441
	public static function handle_post_authorization_actions(
7442
		$activate_sso = false,
7443
		$redirect_on_activation_error = false,
7444
		$send_state_messages = true
7445
	) {
7446
		$other_modules = $activate_sso
7447
			? array( 'sso' )
7448
			: array();
7449
7450
		if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
7451
			$active_modules = Jetpack_Options::get_option( 'active_modules' );
7452
			self::delete_active_modules();
7453
7454
			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...
7455
		} else {
7456
			// Default modules that don't require a user were already activated on site_register.
7457
			// This time let's activate only those that require a user, this assures we don't reactivate manually deactivated modules while the site was user-less.
7458
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
7459
			Jetpack_Options::update_option( 'active_modules_initialized', true );
7460
		}
7461
7462
		// Since this is a fresh connection, be sure to clear out IDC options
7463
		Jetpack_IDC::clear_all_idc_options();
7464
7465
		if ( $send_state_messages ) {
7466
			self::state( 'message', 'authorized' );
7467
		}
7468
	}
7469
7470
	/**
7471
	 * Returns a boolean for whether backups UI should be displayed or not.
7472
	 *
7473
	 * @return bool Should backups UI be displayed?
7474
	 */
7475
	public static function show_backups_ui() {
7476
		/**
7477
		 * Whether UI for backups should be displayed.
7478
		 *
7479
		 * @since 6.5.0
7480
		 *
7481
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7482
		 */
7483
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7484
	}
7485
7486
	/*
7487
	 * Deprecated manage functions
7488
	 */
7489
	function prepare_manage_jetpack_notice() {
7490
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7491
	}
7492
	function manage_activate_screen() {
7493
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7494
	}
7495
	function admin_jetpack_manage_notice() {
7496
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7497
	}
7498
	function opt_out_jetpack_manage_url() {
7499
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7500
	}
7501
	function opt_in_jetpack_manage_url() {
7502
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7503
	}
7504
	function opt_in_jetpack_manage_notice() {
7505
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7506
	}
7507
	function can_display_jetpack_manage_notice() {
7508
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7509
	}
7510
7511
	/**
7512
	 * Clean leftoveruser meta.
7513
	 *
7514
	 * Delete Jetpack-related user meta when it is no longer needed.
7515
	 *
7516
	 * @since 7.3.0
7517
	 *
7518
	 * @param int $user_id User ID being updated.
7519
	 */
7520
	public static function user_meta_cleanup( $user_id ) {
7521
		$meta_keys = array(
7522
			// AtD removed from Jetpack 7.3
7523
			'AtD_options',
7524
			'AtD_check_when',
7525
			'AtD_guess_lang',
7526
			'AtD_ignored_phrases',
7527
		);
7528
7529
		foreach ( $meta_keys as $meta_key ) {
7530
			if ( get_user_meta( $user_id, $meta_key ) ) {
7531
				delete_user_meta( $user_id, $meta_key );
7532
			}
7533
		}
7534
	}
7535
7536
	/**
7537
	 * Checks if a Jetpack site is both active and not in offline mode.
7538
	 *
7539
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7540
	 *
7541
	 * @deprecated 8.8.0
7542
	 *
7543
	 * @return bool True if Jetpack is active and not in offline mode.
7544
	 */
7545
	public static function is_active_and_not_development_mode() {
7546
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7547
		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...
7548
			return false;
7549
		}
7550
		return true;
7551
	}
7552
7553
	/**
7554
	 * Checks if a Jetpack site is both active and not in offline mode.
7555
	 *
7556
	 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
7557
	 *
7558
	 * @since 8.8.0
7559
	 *
7560
	 * @return bool True if Jetpack is active and not in offline mode.
7561
	 */
7562
	public static function is_active_and_not_offline_mode() {
7563
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
7564
			return false;
7565
		}
7566
		return true;
7567
	}
7568
7569
	/**
7570
	 * Returns the list of products that we have available for purchase.
7571
	 */
7572
	public static function get_products_for_purchase() {
7573
		$products = array();
7574
		if ( ! is_multisite() ) {
7575
			$products[] = array(
7576
				'key'               => 'backup',
7577
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7578
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7579
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7580
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7581
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7582
				'options'           => array(
7583
					array(
7584
						'type'        => 'daily',
7585
						'slug'        => 'jetpack-backup-daily',
7586
						'key'         => 'jetpack_backup_daily',
7587
						'name'        => __( 'Daily Backups', 'jetpack' ),
7588
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7589
					),
7590
					array(
7591
						'type'        => 'realtime',
7592
						'slug'        => 'jetpack-backup-realtime',
7593
						'key'         => 'jetpack_backup_realtime',
7594
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7595
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7596
					),
7597
				),
7598
				'default_option'    => 'realtime',
7599
				'show_promotion'    => true,
7600
				'discount_percent'  => 70,
7601
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7602
			);
7603
7604
			$products[] = array(
7605
				'key'               => 'scan',
7606
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7607
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7608
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7609
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7610
				'show_promotion'    => true,
7611
				'discount_percent'  => 30,
7612
				'options'           => array(
7613
					array(
7614
						'type' => 'scan',
7615
						'slug' => 'jetpack-scan',
7616
						'key'  => 'jetpack_scan',
7617
						'name' => __( 'Daily Scan', 'jetpack' ),
7618
					),
7619
				),
7620
				'default_option'    => 'scan',
7621
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7622
			);
7623
		}
7624
7625
		$products[] = array(
7626
			'key'               => 'search',
7627
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7628
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7629
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7630
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7631
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7632
			'options'           => array(
7633
				array(
7634
					'type' => 'search',
7635
					'slug' => 'jetpack-search',
7636
					'key'  => 'jetpack_search',
7637
					'name' => __( 'Search', 'jetpack' ),
7638
				),
7639
			),
7640
			'tears'             => array(),
7641
			'default_option'    => 'search',
7642
			'show_promotion'    => false,
7643
			'included_in_plans' => array( 'search-plan' ),
7644
		);
7645
7646
		$products[] = array(
7647
			'key'               => 'anti-spam',
7648
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7649
			'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' ),
7650
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7651
			'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' ),
7652
			'options'           => array(
7653
				array(
7654
					'type' => 'anti-spam',
7655
					'slug' => 'jetpack-anti-spam',
7656
					'key'  => 'jetpack_anti_spam',
7657
					'name' => __( 'Anti-Spam', 'jetpack' ),
7658
				),
7659
			),
7660
			'default_option'    => 'anti-spam',
7661
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7662
		);
7663
7664
		return $products;
7665
	}
7666
}
7667