Completed
Push — add/auto-activate-userless-mod... ( 608011 )
by
unknown
36:53 queued 26:54
created

Jetpack::show_backups_ui()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$this->connection_manager is of type object<Automattic\Jetpack\Connection\Manager>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

Loading history...
3442
	 * @return Boolean Whether the disconnection of the user was successful.
3443
	 */
3444
	public static function unlink_user( $user_id = null ) {
3445
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3446
		return Connection_Manager::disconnect_user( $user_id );
3447
	}
3448
3449
	/**
3450
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3451
	 */
3452
	public static function try_registration() {
3453
		$terms_of_service = new Terms_Of_Service();
3454
		// The user has agreed to the TOS at some point by now.
3455
		$terms_of_service->agree();
3456
3457
		// Let's get some testing in beta versions and such.
3458
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3459
			// Before attempting to connect, let's make sure that the domains are viable.
3460
			$domains_to_check = array_unique(
3461
				array(
3462
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3463
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3464
				)
3465
			);
3466
			foreach ( $domains_to_check as $domain ) {
3467
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3466 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...
3468
				if ( is_wp_error( $result ) ) {
3469
					return $result;
3470
				}
3471
			}
3472
		}
3473
3474
		$result = self::register();
3475
3476
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3477
		if ( ! $result || is_wp_error( $result ) ) {
3478
			return $result;
3479
		} else {
3480
			return true;
3481
		}
3482
	}
3483
3484
	/**
3485
	 * Tracking an internal event log. Try not to put too much chaff in here.
3486
	 *
3487
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3488
	 */
3489
	public static function log( $code, $data = null ) {
3490
		// only grab the latest 200 entries
3491
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3492
3493
		// Append our event to the log
3494
		$log_entry = array(
3495
			'time'    => time(),
3496
			'user_id' => get_current_user_id(),
3497
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3498
			'code'    => $code,
3499
		);
3500
		// Don't bother storing it unless we've got some.
3501
		if ( ! is_null( $data ) ) {
3502
			$log_entry['data'] = $data;
3503
		}
3504
		$log[] = $log_entry;
3505
3506
		// Try add_option first, to make sure it's not autoloaded.
3507
		// @todo: Add an add_option method to Jetpack_Options
3508
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3509
			Jetpack_Options::update_option( 'log', $log );
3510
		}
3511
3512
		/**
3513
		 * Fires when Jetpack logs an internal event.
3514
		 *
3515
		 * @since 3.0.0
3516
		 *
3517
		 * @param array $log_entry {
3518
		 *  Array of details about the log entry.
3519
		 *
3520
		 *  @param string time Time of the event.
3521
		 *  @param int user_id ID of the user who trigerred the event.
3522
		 *  @param int blog_id Jetpack Blog ID.
3523
		 *  @param string code Unique name for the event.
3524
		 *  @param string data Data about the event.
3525
		 * }
3526
		 */
3527
		do_action( 'jetpack_log_entry', $log_entry );
3528
	}
3529
3530
	/**
3531
	 * Get the internal event log.
3532
	 *
3533
	 * @param $event (string) - only return the specific log events
3534
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3535
	 *
3536
	 * @return array of log events || WP_Error for invalid params
3537
	 */
3538
	public static function get_log( $event = false, $num = false ) {
3539
		if ( $event && ! is_string( $event ) ) {
3540
			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...
3541
		}
3542
3543
		if ( $num && ! is_numeric( $num ) ) {
3544
			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...
3545
		}
3546
3547
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3548
3549
		// If nothing set - act as it did before, otherwise let's start customizing the output
3550
		if ( ! $num && ! $event ) {
3551
			return $entire_log;
3552
		} else {
3553
			$entire_log = array_reverse( $entire_log );
3554
		}
3555
3556
		$custom_log_output = array();
3557
3558
		if ( $event ) {
3559
			foreach ( $entire_log as $log_event ) {
3560
				if ( $event == $log_event['code'] ) {
3561
					$custom_log_output[] = $log_event;
3562
				}
3563
			}
3564
		} else {
3565
			$custom_log_output = $entire_log;
3566
		}
3567
3568
		if ( $num ) {
3569
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3570
		}
3571
3572
		return $custom_log_output;
3573
	}
3574
3575
	/**
3576
	 * Log modification of important settings.
3577
	 */
3578
	public static function log_settings_change( $option, $old_value, $value ) {
3579
		switch ( $option ) {
3580
			case 'jetpack_sync_non_public_post_stati':
3581
				self::log( $option, $value );
3582
				break;
3583
		}
3584
	}
3585
3586
	/**
3587
	 * Return stat data for WPCOM sync
3588
	 */
3589
	public static function get_stat_data( $encode = true, $extended = true ) {
3590
		$data = Jetpack_Heartbeat::generate_stats_array();
3591
3592
		if ( $extended ) {
3593
			$additional_data = self::get_additional_stat_data();
3594
			$data            = array_merge( $data, $additional_data );
3595
		}
3596
3597
		if ( $encode ) {
3598
			return json_encode( $data );
3599
		}
3600
3601
		return $data;
3602
	}
3603
3604
	/**
3605
	 * Get additional stat data to sync to WPCOM
3606
	 */
3607
	public static function get_additional_stat_data( $prefix = '' ) {
3608
		$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...
3609
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3610
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3611
		$return[ "{$prefix}site-count" ]    = 0;
3612
3613
		if ( function_exists( 'get_blog_count' ) ) {
3614
			$return[ "{$prefix}site-count" ] = get_blog_count();
3615
		}
3616
		return $return;
3617
	}
3618
3619
	private static function get_site_user_count() {
3620
		global $wpdb;
3621
3622
		if ( function_exists( 'wp_is_large_network' ) ) {
3623
			if ( wp_is_large_network( 'users' ) ) {
3624
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3625
			}
3626
		}
3627
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3628
			// It wasn't there, so regenerate the data and save the transient
3629
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3630
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3631
		}
3632
		return $user_count;
3633
	}
3634
3635
	/* Admin Pages */
3636
3637
	function admin_init() {
3638
		// If the plugin is not connected, display a connect message.
3639
		if (
3640
			// the plugin was auto-activated and needs its candy
3641
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3642
		||
3643
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3644
			! Jetpack_Options::get_option( 'activated' )
3645
		) {
3646
			self::plugin_initialize();
3647
		}
3648
3649
		$is_offline_mode = ( new Status() )->is_offline_mode();
3650
		if ( ! self::is_active() && ! $is_offline_mode ) {
3651
			Jetpack_Connection_Banner::init();
3652
			/** Already documented in automattic/jetpack-connection::src/class-client.php */
3653
		} elseif ( ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) && ! apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
3654
			// Upgrade: 1.1 -> 1.1.1
3655
			// Check and see if host can verify the Jetpack servers' SSL certificate
3656
			$args = array();
3657
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3658
		}
3659
3660
		Jetpack_Recommendations_Banner::init();
3661
3662
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3663
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3664
		}
3665
3666
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3667
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3668
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3669
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3670
3671
		if ( self::is_active() || $is_offline_mode ) {
3672
			// Artificially throw errors in certain specific cases during plugin activation.
3673
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3674
		}
3675
3676
		// Add custom column in wp-admin/users.php to show whether user is linked.
3677
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3678
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3679
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3680
	}
3681
3682
	function admin_body_class( $admin_body_class = '' ) {
3683
		$classes = explode( ' ', trim( $admin_body_class ) );
3684
3685
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3686
3687
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3688
		return " $admin_body_class ";
3689
	}
3690
3691
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3692
		return $admin_body_class . ' jetpack-pagestyles ';
3693
	}
3694
3695
	/**
3696
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3697
	 * This function artificially throws errors for such cases (per a specific list).
3698
	 *
3699
	 * @param string $plugin The activated plugin.
3700
	 */
3701
	function throw_error_on_activate_plugin( $plugin ) {
3702
		$active_modules = self::get_active_modules();
3703
3704
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3705
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3706
			$throw = false;
3707
3708
			// Try and make sure it really was the stats plugin
3709
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3710
				if ( 'stats.php' == basename( $plugin ) ) {
3711
					$throw = true;
3712
				}
3713
			} else {
3714
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3715
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3716
					$throw = true;
3717
				}
3718
			}
3719
3720
			if ( $throw ) {
3721
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3722
			}
3723
		}
3724
	}
3725
3726
	function intercept_plugin_error_scrape_init() {
3727
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3728
	}
3729
3730
	function intercept_plugin_error_scrape( $action, $result ) {
3731
		if ( ! $result ) {
3732
			return;
3733
		}
3734
3735
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3736
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3737
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3738
			}
3739
		}
3740
	}
3741
3742
	/**
3743
	 * Register the remote file upload request handlers, if needed.
3744
	 *
3745
	 * @access public
3746
	 */
3747
	public function add_remote_request_handlers() {
3748
		// Remote file uploads are allowed only via AJAX requests.
3749
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3750
			return;
3751
		}
3752
3753
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3754
		$remote_request_actions = array(
3755
			'jetpack_upload_file',
3756
			'jetpack_update_file',
3757
		);
3758
3759
		// phpcs:ignore WordPress.Security.NonceVerification
3760
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3761
			return;
3762
		}
3763
3764
		// Require Jetpack authentication for the remote file upload AJAX requests.
3765
		if ( ! $this->connection_manager ) {
3766
			$this->connection_manager = new Connection_Manager();
3767
		}
3768
3769
		$this->connection_manager->require_jetpack_authentication();
3770
3771
		// Register the remote file upload AJAX handlers.
3772
		foreach ( $remote_request_actions as $action ) {
3773
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3774
		}
3775
	}
3776
3777
	/**
3778
	 * Handler for Jetpack remote file uploads.
3779
	 *
3780
	 * @access public
3781
	 */
3782
	public function remote_request_handlers() {
3783
		$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...
3784
3785
		switch ( current_filter() ) {
3786
			case 'wp_ajax_nopriv_jetpack_upload_file':
3787
				$response = $this->upload_handler();
3788
				break;
3789
3790
			case 'wp_ajax_nopriv_jetpack_update_file':
3791
				$response = $this->upload_handler( true );
3792
				break;
3793
			default:
3794
				$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...
3795
				break;
3796
		}
3797
3798
		if ( ! $response ) {
3799
			$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...
3800
		}
3801
3802
		if ( is_wp_error( $response ) ) {
3803
			$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...
3804
			$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...
3805
			$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...
3806
3807
			if ( ! is_int( $status_code ) ) {
3808
				$status_code = 400;
3809
			}
3810
3811
			status_header( $status_code );
3812
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3813
		}
3814
3815
		status_header( 200 );
3816
		if ( true === $response ) {
3817
			exit;
3818
		}
3819
3820
		die( json_encode( (object) $response ) );
3821
	}
3822
3823
	/**
3824
	 * Uploads a file gotten from the global $_FILES.
3825
	 * If `$update_media_item` is true and `post_id` is defined
3826
	 * the attachment file of the media item (gotten through of the post_id)
3827
	 * will be updated instead of add a new one.
3828
	 *
3829
	 * @param  boolean $update_media_item - update media attachment
3830
	 * @return array - An array describing the uploadind files process
3831
	 */
3832
	function upload_handler( $update_media_item = false ) {
3833
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3834
			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...
3835
		}
3836
3837
		$user = wp_authenticate( '', '' );
3838
		if ( ! $user || is_wp_error( $user ) ) {
3839
			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...
3840
		}
3841
3842
		wp_set_current_user( $user->ID );
3843
3844
		if ( ! current_user_can( 'upload_files' ) ) {
3845
			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...
3846
		}
3847
3848
		if ( empty( $_FILES ) ) {
3849
			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...
3850
		}
3851
3852
		foreach ( array_keys( $_FILES ) as $files_key ) {
3853
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3854
				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...
3855
			}
3856
		}
3857
3858
		$media_keys = array_keys( $_FILES['media'] );
3859
3860
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
3861
		if ( ! $token || is_wp_error( $token ) ) {
3862
			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...
3863
		}
3864
3865
		$uploaded_files = array();
3866
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3867
		unset( $GLOBALS['post'] );
3868
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3869
			$file = array();
3870
			foreach ( $media_keys as $media_key ) {
3871
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3872
			}
3873
3874
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3875
3876
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3877
			if ( $hmac_provided !== $hmac_file ) {
3878
				$uploaded_files[ $index ] = (object) array(
3879
					'error'             => 'invalid_hmac',
3880
					'error_description' => 'The corresponding HMAC for this file does not match',
3881
				);
3882
				continue;
3883
			}
3884
3885
			$_FILES['.jetpack.upload.'] = $file;
3886
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3887
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3888
				$post_id = 0;
3889
			}
3890
3891
			if ( $update_media_item ) {
3892
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3893
					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...
3894
				}
3895
3896
				$media_array = $_FILES['media'];
3897
3898
				$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...
3899
				$file_array['type']     = $media_array['type'][0];
3900
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3901
				$file_array['error']    = $media_array['error'][0];
3902
				$file_array['size']     = $media_array['size'][0];
3903
3904
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3905
3906
				if ( is_wp_error( $edited_media_item ) ) {
3907
					return $edited_media_item;
3908
				}
3909
3910
				$response = (object) array(
3911
					'id'   => (string) $post_id,
3912
					'file' => (string) $edited_media_item->post_title,
3913
					'url'  => (string) wp_get_attachment_url( $post_id ),
3914
					'type' => (string) $edited_media_item->post_mime_type,
3915
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3916
				);
3917
3918
				return (array) array( $response );
3919
			}
3920
3921
			$attachment_id = media_handle_upload(
3922
				'.jetpack.upload.',
3923
				$post_id,
3924
				array(),
3925
				array(
3926
					'action' => 'jetpack_upload_file',
3927
				)
3928
			);
3929
3930
			if ( ! $attachment_id ) {
3931
				$uploaded_files[ $index ] = (object) array(
3932
					'error'             => 'unknown',
3933
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3934
				);
3935
			} elseif ( is_wp_error( $attachment_id ) ) {
3936
				$uploaded_files[ $index ] = (object) array(
3937
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3938
					'error_description' => $attachment_id->get_error_message(),
3939
				);
3940
			} else {
3941
				$attachment               = get_post( $attachment_id );
3942
				$uploaded_files[ $index ] = (object) array(
3943
					'id'   => (string) $attachment_id,
3944
					'file' => $attachment->post_title,
3945
					'url'  => wp_get_attachment_url( $attachment_id ),
3946
					'type' => $attachment->post_mime_type,
3947
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3948
				);
3949
				// Zip files uploads are not supported unless they are done for installation purposed
3950
				// lets delete them in case something goes wrong in this whole process
3951
				if ( 'application/zip' === $attachment->post_mime_type ) {
3952
					// Schedule a cleanup for 2 hours from now in case of failed install.
3953
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3954
				}
3955
			}
3956
		}
3957
		if ( ! is_null( $global_post ) ) {
3958
			$GLOBALS['post'] = $global_post;
3959
		}
3960
3961
		return $uploaded_files;
3962
	}
3963
3964
	/**
3965
	 * Add help to the Jetpack page
3966
	 *
3967
	 * @since Jetpack (1.2.3)
3968
	 * @return false if not the Jetpack page
3969
	 */
3970
	function admin_help() {
3971
		$current_screen = get_current_screen();
3972
3973
		// Overview
3974
		$current_screen->add_help_tab(
3975
			array(
3976
				'id'      => 'home',
3977
				'title'   => __( 'Home', 'jetpack' ),
3978
				'content' =>
3979
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3980
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3981
					'<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>',
3982
			)
3983
		);
3984
3985
		// Screen Content
3986
		if ( current_user_can( 'manage_options' ) ) {
3987
			$current_screen->add_help_tab(
3988
				array(
3989
					'id'      => 'settings',
3990
					'title'   => __( 'Settings', 'jetpack' ),
3991
					'content' =>
3992
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3993
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3994
						'<ol>' .
3995
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3996
							'<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>' .
3997
						'</ol>' .
3998
						'<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>',
3999
				)
4000
			);
4001
		}
4002
4003
		// Help Sidebar
4004
		$support_url = Redirect::get_url( 'jetpack-support' );
4005
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4006
		$current_screen->set_help_sidebar(
4007
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4008
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4009
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4010
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4011
		);
4012
	}
4013
4014
	function admin_menu_css() {
4015
		wp_enqueue_style( 'jetpack-icons' );
4016
	}
4017
4018
	function admin_menu_order() {
4019
		return true;
4020
	}
4021
4022
	function jetpack_menu_order( $menu_order ) {
4023
		$jp_menu_order = array();
4024
4025
		foreach ( $menu_order as $index => $item ) {
4026
			if ( $item != 'jetpack' ) {
4027
				$jp_menu_order[] = $item;
4028
			}
4029
4030
			if ( $index == 0 ) {
4031
				$jp_menu_order[] = 'jetpack';
4032
			}
4033
		}
4034
4035
		return $jp_menu_order;
4036
	}
4037
4038
	function admin_banner_styles() {
4039
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4040
4041
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4042
			wp_register_style(
4043
				'jetpack-dops-style',
4044
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4045
				array(),
4046
				JETPACK__VERSION
4047
			);
4048
		}
4049
4050
		wp_enqueue_style(
4051
			'jetpack',
4052
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4053
			array( 'jetpack-dops-style' ),
4054
			JETPACK__VERSION . '-20121016'
4055
		);
4056
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4057
		wp_style_add_data( 'jetpack', 'suffix', $min );
4058
	}
4059
4060
	function plugin_action_links( $actions ) {
4061
4062
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4063
4064
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
4065
			return array_merge(
4066
				$jetpack_home,
4067
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4068
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4069
				$actions
4070
			);
4071
		}
4072
4073
		return array_merge( $jetpack_home, $actions );
4074
	}
4075
4076
	/**
4077
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4078
	 *
4079
	 * @param string $hook The current admin page.
4080
	 *
4081
	 * @return void
4082
	 */
4083
	public function deactivate_dialog( $hook ) {
4084
		if (
4085
			'plugins.php' === $hook
4086
			&& self::is_active()
4087
		) {
4088
4089
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4090
4091
			if ( count( $active_plugins_using_connection ) > 1 ) {
4092
4093
				add_thickbox();
4094
4095
				wp_register_script(
4096
					'jp-tracks',
4097
					'//stats.wp.com/w.js',
4098
					array(),
4099
					gmdate( 'YW' ),
4100
					true
4101
				);
4102
4103
				wp_register_script(
4104
					'jp-tracks-functions',
4105
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4106
					array( 'jp-tracks' ),
4107
					JETPACK__VERSION,
4108
					false
4109
				);
4110
4111
				wp_enqueue_script(
4112
					'jetpack-deactivate-dialog-js',
4113
					Assets::get_file_url_for_environment(
4114
						'_inc/build/jetpack-deactivate-dialog.min.js',
4115
						'_inc/jetpack-deactivate-dialog.js'
4116
					),
4117
					array( 'jquery', 'jp-tracks-functions' ),
4118
					JETPACK__VERSION,
4119
					true
4120
				);
4121
4122
				wp_localize_script(
4123
					'jetpack-deactivate-dialog-js',
4124
					'deactivate_dialog',
4125
					array(
4126
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4127
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4128
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4129
					)
4130
				);
4131
4132
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4133
4134
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4135
			}
4136
		}
4137
	}
4138
4139
	/**
4140
	 * Outputs the content of the deactivation modal
4141
	 *
4142
	 * @return void
4143
	 */
4144
	public function deactivate_dialog_content() {
4145
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4146
		unset( $active_plugins_using_connection['jetpack'] );
4147
		$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 4145 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...
4148
	}
4149
4150
	/**
4151
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4152
	 *
4153
	 * @param string $login_url The wp-login URL.
4154
	 * @param string $redirect  URL to redirect users after logging in.
4155
	 * @since Jetpack 8.4
4156
	 * @return string
4157
	 */
4158
	public function login_url( $login_url, $redirect ) {
4159
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4160
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4161
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4162
		}
4163
		return $login_url;
4164
	}
4165
4166
	/**
4167
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4168
	 *
4169
	 * @since Jetpack 8.4
4170
	 */
4171
	public function login_init() {
4172
		// phpcs:ignore WordPress.Security.NonceVerification
4173
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4174
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4175
			wp_safe_redirect(
4176
				add_query_arg(
4177
					array(
4178
						'forceInstall' => 1,
4179
						'url'          => rawurlencode( get_site_url() ),
4180
					),
4181
					// @todo provide way to go to specific calypso env.
4182
					self::get_calypso_host() . 'jetpack/connect'
4183
				)
4184
			);
4185
			exit;
4186
		}
4187
	}
4188
4189
	/*
4190
	 * Registration flow:
4191
	 * 1 - ::admin_page_load() action=register
4192
	 * 2 - ::try_registration()
4193
	 * 3 - ::register()
4194
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4195
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4196
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4197
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4198
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4199
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4200
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4201
	 *       jetpack_id, jetpack_secret, jetpack_public
4202
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4203
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4204
	 * 5 - user logs in with WP.com account
4205
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4206
	 *		- Manager::authorize()
4207
	 *		- Manager::get_token()
4208
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4209
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4210
	 *			- which responds with access_token, token_type, scope
4211
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4212
	 *		- Jetpack::activate_default_modules()
4213
	 *     		- Deactivates deprecated plugins
4214
	 *     		- Activates all default modules
4215
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4216
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4217
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4218
	 *     Done!
4219
	 */
4220
4221
	/**
4222
	 * Handles the page load events for the Jetpack admin page
4223
	 */
4224
	function admin_page_load() {
4225
		$error = false;
4226
4227
		// Make sure we have the right body class to hook stylings for subpages off of.
4228
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4229
4230
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4231
			// Should only be used in intermediate redirects to preserve state across redirects
4232
			self::restate();
4233
		}
4234
4235
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4236
			// @todo: Add validation against a known allowed list.
4237
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4238
			// User clicked in the iframe to link their accounts
4239
			if ( ! self::connection()->is_user_connected() ) {
4240
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4241
4242
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4243
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4244
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4245
4246
				if ( isset( $_GET['notes_iframe'] ) ) {
4247
					$connect_url .= '&notes_iframe';
4248
				}
4249
				wp_redirect( $connect_url );
4250
				exit;
4251
			} else {
4252
				if ( ! isset( $_GET['calypso_env'] ) ) {
4253
					self::state( 'message', 'already_authorized' );
4254
					wp_safe_redirect( self::admin_url() );
4255
					exit;
4256
				} else {
4257
					$connect_url  = $this->build_connect_url( true, false, $from );
4258
					$connect_url .= '&already_authorized=true';
4259
					wp_redirect( $connect_url );
4260
					exit;
4261
				}
4262
			}
4263
		}
4264
4265
		if ( isset( $_GET['action'] ) ) {
4266
			switch ( $_GET['action'] ) {
4267
				case 'authorize_redirect':
4268
					self::log( 'authorize_redirect' );
4269
4270
					add_filter(
4271
						'allowed_redirect_hosts',
4272
						function ( $domains ) {
4273
							$domains[] = 'jetpack.com';
4274
							$domains[] = 'jetpack.wordpress.com';
4275
							$domains[] = 'wordpress.com';
4276
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4277
							return array_unique( $domains );
4278
						}
4279
					);
4280
4281
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4282
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4283
4284
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4285
						// The destination URL is missing or invalid, nothing to do here.
4286
						exit;
4287
					}
4288
4289
					if ( static::is_active() && static::connection()->is_user_connected() ) {
4290
						// The user is either already connected, or finished the connection process.
4291
						wp_safe_redirect( $dest_url );
4292
						exit;
4293
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4294
						// The user decided not to proceed with setting up the connection.
4295
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4296
						exit;
4297
					}
4298
4299
					$redirect_url = self::admin_url(
4300
						array(
4301
							'page'     => 'jetpack',
4302
							'action'   => 'authorize_redirect',
4303
							'dest_url' => rawurlencode( $dest_url ),
4304
							'done'     => '1',
4305
						)
4306
					);
4307
4308
					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...
4309
					exit;
4310
				case 'authorize':
4311
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4312
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4313
					exit;
4314
				case 'register':
4315
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4316
						$error = 'cheatin';
4317
						break;
4318
					}
4319
					check_admin_referer( 'jetpack-register' );
4320
					self::log( 'register' );
4321
					self::maybe_set_version_option();
4322
					$registered = self::try_registration();
4323
					if ( is_wp_error( $registered ) ) {
4324
						$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...
4325
						self::state( 'error', $error );
4326
						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...
4327
4328
						/**
4329
						 * Jetpack registration Error.
4330
						 *
4331
						 * @since 7.5.0
4332
						 *
4333
						 * @param string|int $error The error code.
4334
						 * @param \WP_Error $registered The error object.
4335
						 */
4336
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4337
						break;
4338
					}
4339
4340
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4341
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4342
4343
					/**
4344
					 * Jetpack registration Success.
4345
					 *
4346
					 * @since 7.5.0
4347
					 *
4348
					 * @param string $from 'from' GET parameter;
4349
					 */
4350
					do_action( 'jetpack_connection_register_success', $from );
4351
4352
					$url = $this->build_connect_url( true, $redirect, $from );
4353
4354
					if ( ! empty( $_GET['onboarding'] ) ) {
4355
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4356
					}
4357
4358
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4359
						$url = add_query_arg( 'auth_approved', 'true', $url );
4360
					}
4361
4362
					wp_redirect( $url );
4363
					exit;
4364
				case 'activate':
4365
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4366
						$error = 'cheatin';
4367
						break;
4368
					}
4369
4370
					$module = stripslashes( $_GET['module'] );
4371
					check_admin_referer( "jetpack_activate-$module" );
4372
					self::log( 'activate', $module );
4373
					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...
4374
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4375
					}
4376
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4377
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4378
					exit;
4379
				case 'activate_default_modules':
4380
					check_admin_referer( 'activate_default_modules' );
4381
					self::log( 'activate_default_modules' );
4382
					self::restate();
4383
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4384
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4385
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4386
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4387
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4388
					exit;
4389
				case 'disconnect':
4390
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4391
						$error = 'cheatin';
4392
						break;
4393
					}
4394
4395
					check_admin_referer( 'jetpack-disconnect' );
4396
					self::log( 'disconnect' );
4397
					self::disconnect();
4398
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4399
					exit;
4400
				case 'reconnect':
4401
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4402
						$error = 'cheatin';
4403
						break;
4404
					}
4405
4406
					check_admin_referer( 'jetpack-reconnect' );
4407
					self::log( 'reconnect' );
4408
					$this->disconnect();
4409
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4410
					exit;
4411 View Code Duplication
				case 'deactivate':
4412
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4413
						$error = 'cheatin';
4414
						break;
4415
					}
4416
4417
					$modules = stripslashes( $_GET['module'] );
4418
					check_admin_referer( "jetpack_deactivate-$modules" );
4419
					foreach ( explode( ',', $modules ) as $module ) {
4420
						self::log( 'deactivate', $module );
4421
						self::deactivate_module( $module );
4422
						self::state( 'message', 'module_deactivated' );
4423
					}
4424
					self::state( 'module', $modules );
4425
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4426
					exit;
4427
				case 'unlink':
4428
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4429
					check_admin_referer( 'jetpack-unlink' );
4430
					self::log( 'unlink' );
4431
					Connection_Manager::disconnect_user();
4432
					self::state( 'message', 'unlinked' );
4433
					if ( 'sub-unlink' == $redirect ) {
4434
						wp_safe_redirect( admin_url() );
4435
					} else {
4436
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4437
					}
4438
					exit;
4439
				case 'onboard':
4440
					if ( ! current_user_can( 'manage_options' ) ) {
4441
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4442
					} else {
4443
						self::create_onboarding_token();
4444
						$url = $this->build_connect_url( true );
4445
4446
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4447
							$url = add_query_arg( 'onboarding', $token, $url );
4448
						}
4449
4450
						$calypso_env = $this->get_calypso_env();
4451
						if ( ! empty( $calypso_env ) ) {
4452
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4453
						}
4454
4455
						wp_redirect( $url );
4456
						exit;
4457
					}
4458
					exit;
4459
				default:
4460
					/**
4461
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4462
					 *
4463
					 * @since 2.6.0
4464
					 *
4465
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4466
					 */
4467
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4468
			}
4469
		}
4470
4471
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4472
			self::activate_new_modules( true );
4473
		}
4474
4475
		$message_code = self::state( 'message' );
4476
		if ( self::state( 'optin-manage' ) ) {
4477
			$activated_manage = $message_code;
4478
			$message_code     = 'jetpack-manage';
4479
		}
4480
4481
		switch ( $message_code ) {
4482
			case 'jetpack-manage':
4483
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4484
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4485
				$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>';
4486
				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...
4487
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4488
				}
4489
				break;
4490
4491
		}
4492
4493
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4494
4495
		if ( ! empty( $deactivated_plugins ) ) {
4496
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4497
			$deactivated_titles  = array();
4498
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4499
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4500
					continue;
4501
				}
4502
4503
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4504
			}
4505
4506
			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...
4507
				if ( $this->message ) {
4508
					$this->message .= "<br /><br />\n";
4509
				}
4510
4511
				$this->message .= wp_sprintf(
4512
					_n(
4513
						'Jetpack contains the most recent version of the old %l plugin.',
4514
						'Jetpack contains the most recent versions of the old %l plugins.',
4515
						count( $deactivated_titles ),
4516
						'jetpack'
4517
					),
4518
					$deactivated_titles
4519
				);
4520
4521
				$this->message .= "<br />\n";
4522
4523
				$this->message .= _n(
4524
					'The old version has been deactivated and can be removed from your site.',
4525
					'The old versions have been deactivated and can be removed from your site.',
4526
					count( $deactivated_titles ),
4527
					'jetpack'
4528
				);
4529
			}
4530
		}
4531
4532
		$this->privacy_checks = self::state( 'privacy_checks' );
4533
4534
		if ( $this->message || $this->error || $this->privacy_checks ) {
4535
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4536
		}
4537
4538
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4539
	}
4540
4541
	function admin_notices() {
4542
4543
		if ( $this->error ) {
4544
			?>
4545
<div id="message" class="jetpack-message jetpack-err">
4546
	<div class="squeezer">
4547
		<h2>
4548
			<?php
4549
			echo wp_kses(
4550
				$this->error,
4551
				array(
4552
					'a'      => array( 'href' => array() ),
4553
					'small'  => true,
4554
					'code'   => true,
4555
					'strong' => true,
4556
					'br'     => true,
4557
					'b'      => true,
4558
				)
4559
			);
4560
			?>
4561
			</h2>
4562
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4563
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4564
<?php	endif; ?>
4565
	</div>
4566
</div>
4567
			<?php
4568
		}
4569
4570
		if ( $this->message ) {
4571
			?>
4572
<div id="message" class="jetpack-message">
4573
	<div class="squeezer">
4574
		<h2>
4575
			<?php
4576
			echo wp_kses(
4577
				$this->message,
4578
				array(
4579
					'strong' => array(),
4580
					'a'      => array( 'href' => true ),
4581
					'br'     => true,
4582
				)
4583
			);
4584
			?>
4585
			</h2>
4586
	</div>
4587
</div>
4588
			<?php
4589
		}
4590
4591
		if ( $this->privacy_checks ) :
4592
			$module_names = $module_slugs = array();
4593
4594
			$privacy_checks = explode( ',', $this->privacy_checks );
4595
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4596
			foreach ( $privacy_checks as $module_slug ) {
4597
				$module = self::get_module( $module_slug );
4598
				if ( ! $module ) {
4599
					continue;
4600
				}
4601
4602
				$module_slugs[] = $module_slug;
4603
				$module_names[] = "<strong>{$module['name']}</strong>";
4604
			}
4605
4606
			$module_slugs = join( ',', $module_slugs );
4607
			?>
4608
<div id="message" class="jetpack-message jetpack-err">
4609
	<div class="squeezer">
4610
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4611
		<p>
4612
			<?php
4613
			echo wp_kses(
4614
				wptexturize(
4615
					wp_sprintf(
4616
						_nx(
4617
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4618
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4619
							count( $privacy_checks ),
4620
							'%l = list of Jetpack module/feature names',
4621
							'jetpack'
4622
						),
4623
						$module_names
4624
					)
4625
				),
4626
				array( 'strong' => true )
4627
			);
4628
4629
			echo "\n<br />\n";
4630
4631
			echo wp_kses(
4632
				sprintf(
4633
					_nx(
4634
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4635
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4636
						count( $privacy_checks ),
4637
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4638
						'jetpack'
4639
					),
4640
					wp_nonce_url(
4641
						self::admin_url(
4642
							array(
4643
								'page'   => 'jetpack',
4644
								'action' => 'deactivate',
4645
								'module' => urlencode( $module_slugs ),
4646
							)
4647
						),
4648
						"jetpack_deactivate-$module_slugs"
4649
					),
4650
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4651
				),
4652
				array(
4653
					'a' => array(
4654
						'href'  => true,
4655
						'title' => true,
4656
					),
4657
				)
4658
			);
4659
			?>
4660
		</p>
4661
	</div>
4662
</div>
4663
			<?php
4664
endif;
4665
	}
4666
4667
	/**
4668
	 * We can't always respond to a signed XML-RPC request with a
4669
	 * helpful error message. In some circumstances, doing so could
4670
	 * leak information.
4671
	 *
4672
	 * Instead, track that the error occurred via a Jetpack_Option,
4673
	 * and send that data back in the heartbeat.
4674
	 * All this does is increment a number, but it's enough to find
4675
	 * trends.
4676
	 *
4677
	 * @param WP_Error $xmlrpc_error The error produced during
4678
	 *                               signature validation.
4679
	 */
4680
	function track_xmlrpc_error( $xmlrpc_error ) {
4681
		$code = is_wp_error( $xmlrpc_error )
4682
			? $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...
4683
			: 'should-not-happen';
4684
4685
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4686
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4687
			// No need to update the option if we already have
4688
			// this code stored.
4689
			return;
4690
		}
4691
		$xmlrpc_errors[ $code ] = true;
4692
4693
		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...
4694
	}
4695
4696
	/**
4697
	 * Initialize the jetpack stats instance only when needed
4698
	 *
4699
	 * @return void
4700
	 */
4701
	private function initialize_stats() {
4702
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4703
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4704
		}
4705
	}
4706
4707
	/**
4708
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4709
	 */
4710
	function stat( $group, $detail ) {
4711
		$this->initialize_stats();
4712
		$this->a8c_mc_stats_instance->add( $group, $detail );
4713
4714
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4715
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4716
	}
4717
4718
	/**
4719
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4720
	 */
4721
	function do_stats( $method = '' ) {
4722
		$this->initialize_stats();
4723
		if ( 'server_side' === $method ) {
4724
			$this->a8c_mc_stats_instance->do_server_side_stats();
4725
		} else {
4726
			$this->a8c_mc_stats_instance->do_stats();
4727
		}
4728
4729
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4730
		$this->stats = array();
4731
	}
4732
4733
	/**
4734
	 * Runs stats code for a one-off, server-side.
4735
	 *
4736
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4737
	 *
4738
	 * @return bool If it worked.
4739
	 */
4740
	static function do_server_side_stat( $args ) {
4741
		$url                   = self::build_stats_url( $args );
4742
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4743
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4744
	}
4745
4746
	/**
4747
	 * Builds the stats url.
4748
	 *
4749
	 * @param $args array|string The arguments to append to the URL.
4750
	 *
4751
	 * @return string The URL to be pinged.
4752
	 */
4753
	static function build_stats_url( $args ) {
4754
4755
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4756
		return $a8c_mc_stats_instance->build_stats_url( $args );
4757
4758
	}
4759
4760
	/**
4761
	 * Get the role of the current user.
4762
	 *
4763
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4764
	 *
4765
	 * @access public
4766
	 * @static
4767
	 *
4768
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4769
	 */
4770
	public static function translate_current_user_to_role() {
4771
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4772
4773
		$roles = new Roles();
4774
		return $roles->translate_current_user_to_role();
4775
	}
4776
4777
	/**
4778
	 * Get the role of a particular user.
4779
	 *
4780
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4781
	 *
4782
	 * @access public
4783
	 * @static
4784
	 *
4785
	 * @param \WP_User $user User object.
4786
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4787
	 */
4788
	public static function translate_user_to_role( $user ) {
4789
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4790
4791
		$roles = new Roles();
4792
		return $roles->translate_user_to_role( $user );
4793
	}
4794
4795
	/**
4796
	 * Get the minimum capability for a role.
4797
	 *
4798
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4799
	 *
4800
	 * @access public
4801
	 * @static
4802
	 *
4803
	 * @param string $role Role name.
4804
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4805
	 */
4806
	public static function translate_role_to_cap( $role ) {
4807
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4808
4809
		$roles = new Roles();
4810
		return $roles->translate_role_to_cap( $role );
4811
	}
4812
4813
	/**
4814
	 * Sign a user role with the master access token.
4815
	 * If not specified, will default to the current user.
4816
	 *
4817
	 * @deprecated since 7.7
4818
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4819
	 *
4820
	 * @access public
4821
	 * @static
4822
	 *
4823
	 * @param string $role    User role.
4824
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
4825
	 * @return string Signed user role.
4826
	 */
4827
	public static function sign_role( $role, $user_id = null ) {
4828
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4829
		return self::connection()->sign_role( $role, $user_id );
4830
	}
4831
4832
	/**
4833
	 * Builds a URL to the Jetpack connection auth page
4834
	 *
4835
	 * @since 3.9.5
4836
	 *
4837
	 * @param bool        $raw If true, URL will not be escaped.
4838
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4839
	 *                              If string, will be a custom redirect.
4840
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4841
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4842
	 *
4843
	 * @return string Connect URL
4844
	 */
4845
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4846
		$site_id    = Jetpack_Options::get_option( 'id' );
4847
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4848
4849
		if ( $register || ! $blog_token || ! $site_id ) {
4850
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4851
4852
			if ( ! empty( $redirect ) ) {
4853
				$url = add_query_arg(
4854
					'redirect',
4855
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4856
					$url
4857
				);
4858
			}
4859
4860
			if ( is_network_admin() ) {
4861
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4862
			}
4863
4864
			$calypso_env = self::get_calypso_env();
4865
4866
			if ( ! empty( $calypso_env ) ) {
4867
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4868
			}
4869
		} else {
4870
4871
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4872
			// because otherwise this logic can get us in to a loop.
4873
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4874
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4875
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4876
4877
				$response = Client::wpcom_json_api_request_as_blog(
4878
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4879
					'1.1'
4880
				);
4881
4882
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4883
4884
					// Generating a register URL instead to refresh the existing token
4885
					return $this->build_connect_url( $raw, $redirect, $from, true );
4886
				}
4887
			}
4888
4889
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4845 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...
4890
		}
4891
4892
		if ( $from ) {
4893
			$url = add_query_arg( 'from', $from, $url );
4894
		}
4895
4896
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4897
		/**
4898
		 * Filter the URL used when connecting a user to a WordPress.com account.
4899
		 *
4900
		 * @since 8.1.0
4901
		 *
4902
		 * @param string $url Connection URL.
4903
		 * @param bool   $raw If true, URL will not be escaped.
4904
		 */
4905
		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...
4906
	}
4907
4908
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4909
4910
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4911
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4912
4913
		if ( $iframe ) {
4914
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4915
		}
4916
4917
		$c8n = self::connection();
4918
		$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...
4919
4920
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4921
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4922
4923
		if ( $iframe ) {
4924
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4925
		}
4926
4927
		/**
4928
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4929
		 *
4930
		 * @since 8.9.0
4931
		 *
4932
		 * @param string $url Connection URL.
4933
		 */
4934
		return apply_filters( 'jetpack_build_authorize_url', $url );
4935
	}
4936
4937
	/**
4938
	 * Filters the connection URL parameter array.
4939
	 *
4940
	 * @param array $args default URL parameters used by the package.
4941
	 * @return array the modified URL arguments array.
4942
	 */
4943
	public static function filter_connect_request_body( $args ) {
4944
		if (
4945
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4946
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4947
		) {
4948
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4949
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4950
				? $gp_locale->slug
4951
				: '';
4952
		}
4953
4954
		$tracking        = new Tracking();
4955
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4956
4957
		$args = array_merge(
4958
			$args,
4959
			array(
4960
				'_ui' => $tracks_identity['_ui'],
4961
				'_ut' => $tracks_identity['_ut'],
4962
			)
4963
		);
4964
4965
		$calypso_env = self::get_calypso_env();
4966
4967
		if ( ! empty( $calypso_env ) ) {
4968
			$args['calypso_env'] = $calypso_env;
4969
		}
4970
4971
		return $args;
4972
	}
4973
4974
	/**
4975
	 * Filters the URL that will process the connection data. It can be different from the URL
4976
	 * that we send the user to after everything is done.
4977
	 *
4978
	 * @param String $processing_url the default redirect URL used by the package.
4979
	 * @return String the modified URL.
4980
	 *
4981
	 * @deprecated since Jetpack 9.5.0
4982
	 */
4983
	public static function filter_connect_processing_url( $processing_url ) {
4984
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4985
4986
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4987
		return $processing_url;
4988
	}
4989
4990
	/**
4991
	 * Filters the redirection URL that is used for connect requests. The redirect
4992
	 * URL should return the user back to the Jetpack console.
4993
	 *
4994
	 * @param String $redirect the default redirect URL used by the package.
4995
	 * @return String the modified URL.
4996
	 */
4997
	public static function filter_connect_redirect_url( $redirect ) {
4998
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4999
		$redirect           = $redirect
5000
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
5001
			: $jetpack_admin_page;
5002
5003
		if ( isset( $_REQUEST['is_multisite'] ) ) {
5004
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
5005
		}
5006
5007
		return $redirect;
5008
	}
5009
5010
	/**
5011
	 * This action fires at the beginning of the Manager::authorize method.
5012
	 */
5013
	public static function authorize_starting() {
5014
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
5015
		// Checking if site has been active/connected previously before recording unique connection.
5016
		if ( ! $jetpack_unique_connection ) {
5017
			// jetpack_unique_connection option has never been set.
5018
			$jetpack_unique_connection = array(
5019
				'connected'    => 0,
5020
				'disconnected' => 0,
5021
				'version'      => '3.6.1',
5022
			);
5023
5024
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
5025
5026
			// Track unique connection.
5027
			$jetpack = self::init();
5028
5029
			$jetpack->stat( 'connections', 'unique-connection' );
5030
			$jetpack->do_stats( 'server_side' );
5031
		}
5032
5033
		// Increment number of times connected.
5034
		$jetpack_unique_connection['connected'] += 1;
5035
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5036
	}
5037
5038
	/**
5039
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5040
	 * linked.
5041
	 */
5042
	public static function authorize_ending_linked() {
5043
		// Don't activate anything since we are just connecting a user.
5044
		self::state( 'message', 'linked' );
5045
	}
5046
5047
	/**
5048
	 * This action fires at the end of the Manager::authorize method when the master user is
5049
	 * authorized.
5050
	 *
5051
	 * @param array $data The request data.
5052
	 */
5053
	public static function authorize_ending_authorized( $data ) {
5054
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5055
		self::invalidate_onboarding_token();
5056
5057
		// If redirect_uri is SSO, ensure SSO module is enabled.
5058
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5059
5060
		/** This filter is documented in class.jetpack-cli.php */
5061
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5062
5063
		$activate_sso = (
5064
			isset( $redirect_options['action'] ) &&
5065
			'jetpack-sso' === $redirect_options['action'] &&
5066
			$jetpack_start_enable_sso
5067
		);
5068
5069
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5070
5071
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5072
	}
5073
5074
	/**
5075
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5076
	 */
5077
	public static function site_registered() {
5078
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5079
		if ( $active_modules ) {
5080
			self::delete_active_modules();
5081
5082
			// 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.
5083
			self::activate_default_modules( 999, 1, $active_modules, null, null );
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...
5084
		} else {
5085
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5086
			self::activate_default_modules( false, false, array(), null, null, null, false );
5087
		}
5088
5089
		// Since this is a fresh connection, be sure to clear out IDC options.
5090
		Jetpack_IDC::clear_all_idc_options();
5091
	}
5092
5093
	/**
5094
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5095
	 * reconnect process is completed.
5096
	 * Note that this currently only happens when we don't need the user to re-authorize
5097
	 * their WP.com account, eg in cases where we are restoring a connection with
5098
	 * unhealthy blog token.
5099
	 */
5100
	public static function reconnection_completed() {
5101
		self::state( 'message', 'reconnection_completed' );
5102
	}
5103
5104
	/**
5105
	 * Get our assumed site creation date.
5106
	 * Calculated based on the earlier date of either:
5107
	 * - Earliest admin user registration date.
5108
	 * - Earliest date of post of any post type.
5109
	 *
5110
	 * @since 7.2.0
5111
	 * @deprecated since 7.8.0
5112
	 *
5113
	 * @return string Assumed site creation date and time.
5114
	 */
5115
	public static function get_assumed_site_creation_date() {
5116
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5117
		return self::connection()->get_assumed_site_creation_date();
5118
	}
5119
5120 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5121
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5122
5123
		if ( $activation_source_name ) {
5124
			$args['_as'] = urlencode( $activation_source_name );
5125
		}
5126
5127
		if ( $activation_source_keyword ) {
5128
			$args['_ak'] = urlencode( $activation_source_keyword );
5129
		}
5130
	}
5131
5132
	function build_reconnect_url( $raw = false ) {
5133
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5134
		return $raw ? $url : esc_url( $url );
5135
	}
5136
5137
	public static function admin_url( $args = null ) {
5138
		$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...
5139
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5140
		return $url;
5141
	}
5142
5143
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5144
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5145
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5146
	}
5147
5148
	function dismiss_jetpack_notice() {
5149
5150
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5151
			return;
5152
		}
5153
5154
		switch ( $_GET['jetpack-notice'] ) {
5155
			case 'dismiss':
5156
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5157
5158
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5159
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5160
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5161
				}
5162
				break;
5163
		}
5164
	}
5165
5166
	public static function sort_modules( $a, $b ) {
5167
		if ( $a['sort'] == $b['sort'] ) {
5168
			return 0;
5169
		}
5170
5171
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5172
	}
5173
5174
	function ajax_recheck_ssl() {
5175
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5176
		$result = self::permit_ssl( true );
5177
		wp_send_json(
5178
			array(
5179
				'enabled' => $result,
5180
				'message' => get_transient( 'jetpack_https_test_message' ),
5181
			)
5182
		);
5183
	}
5184
5185
	/* Client API */
5186
5187
	/**
5188
	 * Returns the requested Jetpack API URL
5189
	 *
5190
	 * @deprecated since 7.7
5191
	 * @return string
5192
	 */
5193
	public static function api_url( $relative_url ) {
5194
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5195
		$connection = self::connection();
5196
		return $connection->api_url( $relative_url );
5197
	}
5198
5199
	/**
5200
	 * @deprecated 8.0
5201
	 *
5202
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5203
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5204
	 */
5205
	public static function fix_url_for_bad_hosts( $url ) {
5206
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5207
		return $url;
5208
	}
5209
5210
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5211
		// Default to a blog token.
5212
		$token_type = 'blog';
5213
5214
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5215
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5216
			if ( ! empty( $_GET['onboarding'] ) ) {
5217
				$jpo = $_GET;
5218
			} else {
5219
				$jpo = json_decode( $request_data, true );
5220
			}
5221
5222
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5223
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5224
5225
			if (
5226
				isset( $jpo_user )
5227
				&& isset( $jpo_token )
5228
				&& is_email( $jpo_user )
5229
				&& ctype_alnum( $jpo_token )
5230
				&& isset( $_GET['rest_route'] )
5231
				&& self::validate_onboarding_token_action(
5232
					$jpo_token,
5233
					$_GET['rest_route']
5234
				)
5235
			) {
5236
				$jp_user = get_user_by( 'email', $jpo_user );
5237
				if ( is_a( $jp_user, 'WP_User' ) ) {
5238
					wp_set_current_user( $jp_user->ID );
5239
					$user_can = is_multisite()
5240
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5241
						: current_user_can( 'manage_options' );
5242
					if ( $user_can ) {
5243
						$token_type              = 'user';
5244
						$token->external_user_id = $jp_user->ID;
5245
					}
5246
				}
5247
			}
5248
5249
			$token_data['type']    = $token_type;
5250
			$token_data['user_id'] = $token->external_user_id;
5251
		}
5252
5253
		return $token_data;
5254
	}
5255
5256
	/**
5257
	 * Create a random secret for validating onboarding payload
5258
	 *
5259
	 * @return string Secret token
5260
	 */
5261
	public static function create_onboarding_token() {
5262
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5263
			$token = wp_generate_password( 32, false );
5264
			Jetpack_Options::update_option( 'onboarding', $token );
5265
		}
5266
5267
		return $token;
5268
	}
5269
5270
	/**
5271
	 * Remove the onboarding token
5272
	 *
5273
	 * @return bool True on success, false on failure
5274
	 */
5275
	public static function invalidate_onboarding_token() {
5276
		return Jetpack_Options::delete_option( 'onboarding' );
5277
	}
5278
5279
	/**
5280
	 * Validate an onboarding token for a specific action
5281
	 *
5282
	 * @return boolean True if token/action pair is accepted, false if not
5283
	 */
5284
	public static function validate_onboarding_token_action( $token, $action ) {
5285
		// Compare tokens, bail if tokens do not match
5286
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5287
			return false;
5288
		}
5289
5290
		// List of valid actions we can take
5291
		$valid_actions = array(
5292
			'/jetpack/v4/settings',
5293
		);
5294
5295
		// Only allow valid actions.
5296
		if ( ! in_array( $action, $valid_actions ) ) {
5297
			return false;
5298
		}
5299
5300
		return true;
5301
	}
5302
5303
	/**
5304
	 * Checks to see if the URL is using SSL to connect with Jetpack
5305
	 *
5306
	 * @since 2.3.3
5307
	 * @return boolean
5308
	 */
5309
	public static function permit_ssl( $force_recheck = false ) {
5310
		// Do some fancy tests to see if ssl is being supported
5311
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5312
			$message = '';
5313
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5314
				$ssl = 0;
5315
			} else {
5316
				$ssl = 1;
5317
5318
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5319
					$ssl     = 0;
5320
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5321
				} else {
5322
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5323
					if ( is_wp_error( $response ) ) {
5324
						$ssl     = 0;
5325
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5326
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5327
						$ssl     = 0;
5328
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5329
					}
5330
				}
5331
			}
5332
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5333
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5334
		}
5335
5336
		return (bool) $ssl;
5337
	}
5338
5339
	/*
5340
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5341
	 */
5342
	public function alert_auto_ssl_fail() {
5343
		if ( ! current_user_can( 'manage_options' ) ) {
5344
			return;
5345
		}
5346
5347
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5348
		?>
5349
5350
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5351
			<div class="jp-banner__content">
5352
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5353
				<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>
5354
				<p>
5355
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5356
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5357
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5358
				</p>
5359
				<p>
5360
					<?php
5361
					printf(
5362
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5363
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5364
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5365
					);
5366
					?>
5367
				</p>
5368
			</div>
5369
		</div>
5370
		<style>
5371
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5372
		</style>
5373
		<script type="text/javascript">
5374
			jQuery( document ).ready( function( $ ) {
5375
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5376
					var $this = $( this );
5377
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5378
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5379
					e.preventDefault();
5380
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5381
					$.post( ajaxurl, data )
5382
					  .done( function( response ) {
5383
						  if ( response.enabled ) {
5384
							  $( '#jetpack-ssl-warning' ).hide();
5385
						  } else {
5386
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5387
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5388
						  }
5389
					  }.bind( $this ) );
5390
				} );
5391
			} );
5392
		</script>
5393
5394
		<?php
5395
	}
5396
5397
	/**
5398
	 * Returns the Jetpack XML-RPC API
5399
	 *
5400
	 * @deprecated 8.0 Use Connection_Manager instead.
5401
	 * @return string
5402
	 */
5403
	public static function xmlrpc_api_url() {
5404
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5405
		return self::connection()->xmlrpc_api_url();
5406
	}
5407
5408
	/**
5409
	 * Returns the connection manager object.
5410
	 *
5411
	 * @return Automattic\Jetpack\Connection\Manager
5412
	 */
5413
	public static function connection() {
5414
		$jetpack = static::init();
5415
5416
		// If the connection manager hasn't been instantiated, do that now.
5417
		if ( ! $jetpack->connection_manager ) {
5418
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5419
		}
5420
5421
		return $jetpack->connection_manager;
5422
	}
5423
5424
	/**
5425
	 * Creates two secret tokens and the end of life timestamp for them.
5426
	 *
5427
	 * Note these tokens are unique per call, NOT static per site for connecting.
5428
	 *
5429
	 * @since 2.6
5430
	 * @param String  $action  The action name.
5431
	 * @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...
5432
	 * @param Integer $exp     Expiration time in seconds.
5433
	 * @return array
5434
	 */
5435
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5436
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5437
	}
5438
5439
	public static function get_secrets( $action, $user_id ) {
5440
		$secrets = self::connection()->get_secrets( $action, $user_id );
5441
5442
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5443
			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...
5444
		}
5445
5446
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5447
			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...
5448
		}
5449
5450
		return $secrets;
5451
	}
5452
5453
	/**
5454
	 * @deprecated 7.5 Use Connection_Manager instead.
5455
	 *
5456
	 * @param $action
5457
	 * @param $user_id
5458
	 */
5459
	public static function delete_secrets( $action, $user_id ) {
5460
		return self::connection()->delete_secrets( $action, $user_id );
5461
	}
5462
5463
	/**
5464
	 * Builds the timeout limit for queries talking with the wpcom servers.
5465
	 *
5466
	 * Based on local php max_execution_time in php.ini
5467
	 *
5468
	 * @since 2.6
5469
	 * @return int
5470
	 * @deprecated
5471
	 **/
5472
	public function get_remote_query_timeout_limit() {
5473
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5474
		return self::get_max_execution_time();
5475
	}
5476
5477
	/**
5478
	 * Builds the timeout limit for queries talking with the wpcom servers.
5479
	 *
5480
	 * Based on local php max_execution_time in php.ini
5481
	 *
5482
	 * @since 5.4
5483
	 * @return int
5484
	 **/
5485
	public static function get_max_execution_time() {
5486
		$timeout = (int) ini_get( 'max_execution_time' );
5487
5488
		// Ensure exec time set in php.ini
5489
		if ( ! $timeout ) {
5490
			$timeout = 30;
5491
		}
5492
		return $timeout;
5493
	}
5494
5495
	/**
5496
	 * Sets a minimum request timeout, and returns the current timeout
5497
	 *
5498
	 * @since 5.4
5499
	 **/
5500 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5501
		$timeout = self::get_max_execution_time();
5502
		if ( $timeout < $min_timeout ) {
5503
			$timeout = $min_timeout;
5504
			set_time_limit( $timeout );
5505
		}
5506
		return $timeout;
5507
	}
5508
5509
	/**
5510
	 * Takes the response from the Jetpack register new site endpoint and
5511
	 * verifies it worked properly.
5512
	 *
5513
	 * @since 2.6
5514
	 * @deprecated since 7.7.0
5515
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5516
	 **/
5517
	public function validate_remote_register_response() {
5518
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5519
	}
5520
5521
	/**
5522
	 * @return bool|WP_Error
5523
	 */
5524
	public static function register() {
5525
		$tracking = new Tracking();
5526
		$tracking->record_user_event( 'jpc_register_begin' );
5527
5528
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5529
5530
		$connection   = self::connection();
5531
		$registration = $connection->register();
5532
5533
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5534
5535
		if ( ! $registration || is_wp_error( $registration ) ) {
5536
			return $registration;
5537
		}
5538
5539
		return true;
5540
	}
5541
5542
	/**
5543
	 * Filters the registration request body to include tracking properties.
5544
	 *
5545
	 * @param array $properties
5546
	 * @return array amended properties.
5547
	 */
5548 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5549
		$tracking        = new Tracking();
5550
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5551
5552
		return array_merge(
5553
			$properties,
5554
			array(
5555
				'_ui' => $tracks_identity['_ui'],
5556
				'_ut' => $tracks_identity['_ut'],
5557
			)
5558
		);
5559
	}
5560
5561
	/**
5562
	 * Filters the token request body to include tracking properties.
5563
	 *
5564
	 * @param array $properties
5565
	 * @return array amended properties.
5566
	 */
5567 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5568
		$tracking        = new Tracking();
5569
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5570
5571
		return array_merge(
5572
			$properties,
5573
			array(
5574
				'_ui' => $tracks_identity['_ui'],
5575
				'_ut' => $tracks_identity['_ut'],
5576
			)
5577
		);
5578
	}
5579
5580
	/**
5581
	 * If the db version is showing something other that what we've got now, bump it to current.
5582
	 *
5583
	 * @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...
5584
	 */
5585
	public static function maybe_set_version_option() {
5586
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5587
		if ( JETPACK__VERSION != $version ) {
5588
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5589
5590
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5591
				/** This action is documented in class.jetpack.php */
5592
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5593
			}
5594
5595
			return true;
5596
		}
5597
		return false;
5598
	}
5599
5600
	/* Client Server API */
5601
5602
	/**
5603
	 * Loads the Jetpack XML-RPC client.
5604
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5605
	 *
5606
	 * @deprecated since 7.7.0
5607
	 */
5608
	public static function load_xml_rpc_client() {
5609
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5610
	}
5611
5612
	/**
5613
	 * Resets the saved authentication state in between testing requests.
5614
	 *
5615
	 * @deprecated since 8.9.0
5616
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5617
	 */
5618
	public function reset_saved_auth_state() {
5619
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5620
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5621
	}
5622
5623
	/**
5624
	 * Verifies the signature of the current request.
5625
	 *
5626
	 * @deprecated since 7.7.0
5627
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5628
	 *
5629
	 * @return false|array
5630
	 */
5631
	public function verify_xml_rpc_signature() {
5632
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5633
		return self::connection()->verify_xml_rpc_signature();
5634
	}
5635
5636
	/**
5637
	 * Verifies the signature of the current request.
5638
	 *
5639
	 * This function has side effects and should not be used. Instead,
5640
	 * use the memoized version `->verify_xml_rpc_signature()`.
5641
	 *
5642
	 * @deprecated since 7.7.0
5643
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5644
	 * @internal
5645
	 */
5646
	private function internal_verify_xml_rpc_signature() {
5647
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5648
	}
5649
5650
	/**
5651
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5652
	 *
5653
	 * @deprecated since 7.7.0
5654
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5655
	 *
5656
	 * @param \WP_User|mixed $user     User object if authenticated.
5657
	 * @param string         $username Username.
5658
	 * @param string         $password Password string.
5659
	 * @return \WP_User|mixed Authenticated user or error.
5660
	 */
5661 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5662
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5663
5664
		if ( ! $this->connection_manager ) {
5665
			$this->connection_manager = new Connection_Manager();
5666
		}
5667
5668
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5669
	}
5670
5671
	/**
5672
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5673
	 * Uses the existing XMLRPC request signing implementation.
5674
	 *
5675
	 * @deprecated since 8.9.0
5676
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5677
	 */
5678
	function wp_rest_authenticate( $user ) {
5679
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5680
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5681
	}
5682
5683
	/**
5684
	 * Report authentication status to the WP REST API.
5685
	 *
5686
	 * @deprecated since 8.9.0
5687
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5688
	 *
5689
	 * @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...
5690
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5691
	 */
5692
	public function wp_rest_authentication_errors( $value ) {
5693
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5694
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5695
	}
5696
5697
	/**
5698
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5699
	 * Capture it here so we can verify the signature later.
5700
	 *
5701
	 * @deprecated since 7.7.0
5702
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5703
	 *
5704
	 * @param array $methods XMLRPC methods.
5705
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5706
	 */
5707 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5708
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5709
5710
		if ( ! $this->connection_manager ) {
5711
			$this->connection_manager = new Connection_Manager();
5712
		}
5713
5714
		return $this->connection_manager->xmlrpc_methods( $methods );
5715
	}
5716
5717
	/**
5718
	 * Register additional public XMLRPC methods.
5719
	 *
5720
	 * @deprecated since 7.7.0
5721
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5722
	 *
5723
	 * @param array $methods Public XMLRPC methods.
5724
	 * @return array Public XMLRPC methods, with the getOptions one.
5725
	 */
5726 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5727
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5728
5729
		if ( ! $this->connection_manager ) {
5730
			$this->connection_manager = new Connection_Manager();
5731
		}
5732
5733
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5734
	}
5735
5736
	/**
5737
	 * Handles a getOptions XMLRPC method call.
5738
	 *
5739
	 * @deprecated since 7.7.0
5740
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5741
	 *
5742
	 * @param array $args method call arguments.
5743
	 * @return array an amended XMLRPC server options array.
5744
	 */
5745 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5746
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5747
5748
		if ( ! $this->connection_manager ) {
5749
			$this->connection_manager = new Connection_Manager();
5750
		}
5751
5752
		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...
5753
	}
5754
5755
	/**
5756
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5757
	 *
5758
	 * @deprecated since 7.7.0
5759
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5760
	 *
5761
	 * @param array $options Standard Core options.
5762
	 * @return array Amended options.
5763
	 */
5764 View Code Duplication
	public function xmlrpc_options( $options ) {
5765
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5766
5767
		if ( ! $this->connection_manager ) {
5768
			$this->connection_manager = new Connection_Manager();
5769
		}
5770
5771
		return $this->connection_manager->xmlrpc_options( $options );
5772
	}
5773
5774
	/**
5775
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5776
	 * SET: state( $key, $value );
5777
	 * GET: $value = state( $key );
5778
	 *
5779
	 * @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...
5780
	 * @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...
5781
	 * @param bool   $restate private
5782
	 */
5783
	public static function state( $key = null, $value = null, $restate = false ) {
5784
		static $state = array();
5785
		static $path, $domain;
5786
		if ( ! isset( $path ) ) {
5787
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5788
			$admin_url = self::admin_url();
5789
			$bits      = wp_parse_url( $admin_url );
5790
5791
			if ( is_array( $bits ) ) {
5792
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5793
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5794
			} else {
5795
				$path = $domain = null;
5796
			}
5797
		}
5798
5799
		// Extract state from cookies and delete cookies
5800
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5801
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5802
			unset( $_COOKIE['jetpackState'] );
5803
			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...
5804
				if ( strlen( $v ) ) {
5805
					$state[ $k ] = $v;
5806
				}
5807
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5808
			}
5809
		}
5810
5811
		if ( $restate ) {
5812
			foreach ( $state as $k => $v ) {
5813
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5814
			}
5815
			return;
5816
		}
5817
5818
		// Get a state variable.
5819
		if ( isset( $key ) && ! isset( $value ) ) {
5820
			if ( array_key_exists( $key, $state ) ) {
5821
				return $state[ $key ];
5822
			}
5823
			return null;
5824
		}
5825
5826
		// Set a state variable.
5827
		if ( isset( $key ) && isset( $value ) ) {
5828
			if ( is_array( $value ) && isset( $value[0] ) ) {
5829
				$value = $value[0];
5830
			}
5831
			$state[ $key ] = $value;
5832
			if ( ! headers_sent() ) {
5833
				if ( self::should_set_cookie( $key ) ) {
5834
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5835
				}
5836
			}
5837
		}
5838
	}
5839
5840
	public static function restate() {
5841
		self::state( null, null, true );
5842
	}
5843
5844
	/**
5845
	 * Determines whether the jetpackState[$key] value should be added to the
5846
	 * cookie.
5847
	 *
5848
	 * @param string $key The state key.
5849
	 *
5850
	 * @return boolean Whether the value should be added to the cookie.
5851
	 */
5852
	public static function should_set_cookie( $key ) {
5853
		global $current_screen;
5854
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5855
5856
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5857
			return false;
5858
		}
5859
5860
		return true;
5861
	}
5862
5863
	public static function check_privacy( $file ) {
5864
		static $is_site_publicly_accessible = null;
5865
5866
		if ( is_null( $is_site_publicly_accessible ) ) {
5867
			$is_site_publicly_accessible = false;
5868
5869
			$rpc = new Jetpack_IXR_Client();
5870
5871
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5872
			if ( $success ) {
5873
				$response = $rpc->getResponse();
5874
				if ( $response ) {
5875
					$is_site_publicly_accessible = true;
5876
				}
5877
			}
5878
5879
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5880
		}
5881
5882
		if ( $is_site_publicly_accessible ) {
5883
			return;
5884
		}
5885
5886
		$module_slug = self::get_module_slug( $file );
5887
5888
		$privacy_checks = self::state( 'privacy_checks' );
5889
		if ( ! $privacy_checks ) {
5890
			$privacy_checks = $module_slug;
5891
		} else {
5892
			$privacy_checks .= ",$module_slug";
5893
		}
5894
5895
		self::state( 'privacy_checks', $privacy_checks );
5896
	}
5897
5898
	/**
5899
	 * Helper method for multicall XMLRPC.
5900
	 *
5901
	 * @deprecated since 8.9.0
5902
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5903
	 *
5904
	 * @param ...$args Args for the async_call.
5905
	 */
5906
	public static function xmlrpc_async_call( ...$args ) {
5907
5908
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5909
5910
		global $blog_id;
5911
		static $clients = array();
5912
5913
		$client_blog_id = is_multisite() ? $blog_id : 0;
5914
5915
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5916
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => Connection_Manager::CONNECTION_OWNER ) );
5917
			if ( function_exists( 'ignore_user_abort' ) ) {
5918
				ignore_user_abort( true );
5919
			}
5920
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5921
		}
5922
5923
		if ( ! empty( $args[0] ) ) {
5924
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5925
		} elseif ( is_multisite() ) {
5926
			foreach ( $clients as $client_blog_id => $client ) {
5927
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5928
					continue;
5929
				}
5930
5931
				$switch_success = switch_to_blog( $client_blog_id, true );
5932
				if ( ! $switch_success ) {
5933
					continue;
5934
				}
5935
5936
				flush();
5937
				$client->query();
5938
5939
				restore_current_blog();
5940
			}
5941
		} else {
5942
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5943
				flush();
5944
				$clients[0]->query();
5945
			}
5946
		}
5947
	}
5948
5949
	/**
5950
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5951
	 *
5952
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5953
	 *
5954
	 * @param string $url WordPress.com static resource URL.
5955
	 */
5956
	public static function staticize_subdomain( $url ) {
5957
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5958
		return Assets::staticize_subdomain( $url );
5959
	}
5960
5961
	/* JSON API Authorization */
5962
5963
	/**
5964
	 * Handles the login action for Authorizing the JSON API
5965
	 */
5966
	function login_form_json_api_authorization() {
5967
		$this->verify_json_api_authorization_request();
5968
5969
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5970
5971
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5972
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5973
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5974
	}
5975
5976
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5977
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5978
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5979
			return $url;
5980
		}
5981
5982
		$parsed_url = wp_parse_url( $url );
5983
		$url        = strtok( $url, '?' );
5984
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5985
		if ( ! empty( $parsed_url['query'] ) ) {
5986
			$url .= "&{$parsed_url['query']}";
5987
		}
5988
5989
		return $url;
5990
	}
5991
5992
	// Make sure the POSTed request is handled by the same action
5993
	function preserve_action_in_login_form_for_json_api_authorization() {
5994
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5995
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5996
	}
5997
5998
	// If someone logs in to approve API access, store the Access Code in usermeta
5999
	function store_json_api_authorization_token( $user_login, $user ) {
6000
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6001
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6002
		$token = wp_generate_password( 32, false );
6003
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6004
	}
6005
6006
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
6007
	function allow_wpcom_public_api_domain( $domains ) {
6008
		$domains[] = 'public-api.wordpress.com';
6009
		return $domains;
6010
	}
6011
6012
	static function is_redirect_encoded( $redirect_url ) {
6013
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
6014
	}
6015
6016
	// Add all wordpress.com environments to the safe redirect allowed list.
6017
	function allow_wpcom_environments( $domains ) {
6018
		$domains[] = 'wordpress.com';
6019
		$domains[] = 'wpcalypso.wordpress.com';
6020
		$domains[] = 'horizon.wordpress.com';
6021
		$domains[] = 'calypso.localhost';
6022
		return $domains;
6023
	}
6024
6025
	// Add the Access Code details to the public-api.wordpress.com redirect
6026
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6027
		return add_query_arg(
6028
			urlencode_deep(
6029
				array(
6030
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6031
					'jetpack-user-id' => (int) $user->ID,
6032
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6033
				)
6034
			),
6035
			$redirect_to
6036
		);
6037
	}
6038
6039
	/**
6040
	 * Verifies the request by checking the signature
6041
	 *
6042
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6043
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6044
	 *
6045
	 * @param null|array $environment
6046
	 */
6047
	function verify_json_api_authorization_request( $environment = null ) {
6048
		$environment = is_null( $environment )
6049
			? $_REQUEST
6050
			: $environment;
6051
6052
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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

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

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

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