Completed
Push — add/tracks-callables-to-tracki... ( 2a9629...6469f8 )
by
unknown
131:57 queued 122:53
created

Jetpack::admin_init()   C

Complexity

Conditions 13
Paths 64

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
nc 64
nop 0
dl 0
loc 54
rs 6.6166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

Loading history...
1731
	}
1732
1733
	/**
1734
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1735
	 *
1736
	 * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1737
	 * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1738
	 * users and this option will be available by default for everybody.
1739
	 *
1740
	 * @since 9.6.0
1741
	 * @since 9.7.0 returns is_connected in all cases and adds filter to the returned value
1742
	 *
1743
	 * @return bool is the site connection ready to be used?
1744
	 */
1745
	public static function is_connection_ready() {
1746
		/**
1747
		 * Allows filtering whether the connection is ready to be used. If true, this will enable the Jetpack UI and modules
1748
		 *
1749
		 * Modules will be enabled depending on the connection status and if the module requires a connection or user connection.
1750
		 *
1751
		 * @since 9.7.0
1752
		 *
1753
		 * @param bool                                  $is_connection_ready Is the connection ready?
1754
		 * @param Automattic\Jetpack\Connection\Manager $connection_manager Instance of the Manager class, can be used to check the connection status.
1755
		 */
1756
		return apply_filters( 'jetpack_is_connection_ready', self::connection()->is_connected(), self::connection() );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with self::connection().

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

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

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

Loading history...
1757
	}
1758
1759
	/**
1760
	 * Make an API call to WordPress.com for plan status
1761
	 *
1762
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1763
	 *
1764
	 * @return bool True if plan is updated, false if no update
1765
	 */
1766
	public static function refresh_active_plan_from_wpcom() {
1767
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1768
		return Jetpack_Plan::refresh_from_wpcom();
1769
	}
1770
1771
	/**
1772
	 * Get the plan that this Jetpack site is currently using
1773
	 *
1774
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1775
	 * @return array Active Jetpack plan details.
1776
	 */
1777
	public static function get_active_plan() {
1778
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1779
		return Jetpack_Plan::get();
1780
	}
1781
1782
	/**
1783
	 * Determine whether the active plan supports a particular feature
1784
	 *
1785
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1786
	 * @return bool True if plan supports feature, false if not.
1787
	 */
1788
	public static function active_plan_supports( $feature ) {
1789
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1790
		return Jetpack_Plan::supports( $feature );
1791
	}
1792
1793
	/**
1794
	 * Deprecated: Is Jetpack in development (offline) mode?
1795
	 *
1796
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1797
	 * and themes still use it, and we do not want to flood them with notices.
1798
	 *
1799
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1800
	 *
1801
	 * @deprecated since 8.0.
1802
	 */
1803
	public static function is_development_mode() {
1804
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1805
		return ( new Status() )->is_offline_mode();
1806
	}
1807
1808
	/**
1809
	 * Whether the site is currently onboarding or not.
1810
	 * A site is considered as being onboarded if it currently has an onboarding token.
1811
	 *
1812
	 * @since 5.8
1813
	 *
1814
	 * @access public
1815
	 * @static
1816
	 *
1817
	 * @return bool True if the site is currently onboarding, false otherwise
1818
	 */
1819
	public static function is_onboarding() {
1820
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1821
	}
1822
1823
	/**
1824
	 * Determines reason for Jetpack offline mode.
1825
	 */
1826
	public static function development_mode_trigger_text() {
1827
		$status = new Status();
1828
1829
		if ( ! $status->is_offline_mode() ) {
1830
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1831
		}
1832
1833
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1834
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1835
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1836
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1837
		} elseif ( $status->is_local_site() ) {
1838
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1839
			/** This filter is documented in packages/status/src/class-status.php */
1840
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1841
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1842
		} else {
1843
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1844
		}
1845
1846
		return $notice;
1847
1848
	}
1849
	/**
1850
	 * Get Jetpack offline mode notice text and notice class.
1851
	 *
1852
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1853
	 */
1854
	public static function show_development_mode_notice() {
1855 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1856
			$notice = sprintf(
1857
				/* translators: %s is a URL */
1858
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1859
				Redirect::get_url( 'jetpack-support-development-mode' )
1860
			);
1861
1862
			$notice .= ' ' . self::development_mode_trigger_text();
1863
1864
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1865
		}
1866
1867
		// Throw up a notice if using a development version and as for feedback.
1868
		if ( self::is_development_version() ) {
1869
			/* translators: %s is a URL */
1870
			$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' ) );
1871
1872
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1873
		}
1874
		// Throw up a notice if using staging mode
1875 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1876
			/* translators: %s is a URL */
1877
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1878
1879
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1880
		}
1881
	}
1882
1883
	/**
1884
	 * Whether Jetpack's version maps to a public release, or a development version.
1885
	 */
1886
	public static function is_development_version() {
1887
		/**
1888
		 * Allows filtering whether this is a development version of Jetpack.
1889
		 *
1890
		 * This filter is especially useful for tests.
1891
		 *
1892
		 * @since 4.3.0
1893
		 *
1894
		 * @param bool $development_version Is this a develoment version of Jetpack?
1895
		 */
1896
		return (bool) apply_filters(
1897
			'jetpack_development_version',
1898
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1899
		);
1900
	}
1901
1902
	/**
1903
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1904
	 */
1905
	public static function is_user_connected( $user_id = false ) {
1906
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1907
		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...
1908
	}
1909
1910
	/**
1911
	 * Get the wpcom user data of the current|specified connected user.
1912
	 */
1913
	public static function get_connected_user_data( $user_id = null ) {
1914
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1915
		return self::connection()->get_connected_user_data( $user_id );
1916
	}
1917
1918
	/**
1919
	 * Get the wpcom email of the current|specified connected user.
1920
	 */
1921
	public static function get_connected_user_email( $user_id = null ) {
1922
		if ( ! $user_id ) {
1923
			$user_id = get_current_user_id();
1924
		}
1925
1926
		$xml = new Jetpack_IXR_Client(
1927
			array(
1928
				'user_id' => $user_id,
1929
			)
1930
		);
1931
		$xml->query( 'wpcom.getUserEmail' );
1932
		if ( ! $xml->isError() ) {
1933
			return $xml->getResponse();
1934
		}
1935
		return false;
1936
	}
1937
1938
	/**
1939
	 * Get the wpcom email of the master user.
1940
	 */
1941
	public static function get_master_user_email() {
1942
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1943
		if ( $master_user_id ) {
1944
			return self::get_connected_user_email( $master_user_id );
1945
		}
1946
		return '';
1947
	}
1948
1949
	/**
1950
	 * Whether the current user is the connection owner.
1951
	 *
1952
	 * @deprecated since 7.7
1953
	 *
1954
	 * @return bool Whether the current user is the connection owner.
1955
	 */
1956
	public function current_user_is_connection_owner() {
1957
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1958
		return self::connection()->is_connection_owner();
1959
	}
1960
1961
	/**
1962
	 * Gets current user IP address.
1963
	 *
1964
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1965
	 *
1966
	 * @return string                  Current user IP address.
1967
	 */
1968
	public static function current_user_ip( $check_all_headers = false ) {
1969
		if ( $check_all_headers ) {
1970
			foreach ( array(
1971
				'HTTP_CF_CONNECTING_IP',
1972
				'HTTP_CLIENT_IP',
1973
				'HTTP_X_FORWARDED_FOR',
1974
				'HTTP_X_FORWARDED',
1975
				'HTTP_X_CLUSTER_CLIENT_IP',
1976
				'HTTP_FORWARDED_FOR',
1977
				'HTTP_FORWARDED',
1978
				'HTTP_VIA',
1979
			) as $key ) {
1980
				if ( ! empty( $_SERVER[ $key ] ) ) {
1981
					return $_SERVER[ $key ];
1982
				}
1983
			}
1984
		}
1985
1986
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1987
	}
1988
1989
	/**
1990
	 * Synchronize connected user role changes
1991
	 */
1992
	function user_role_change( $user_id ) {
1993
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1994
		Users::user_role_change( $user_id );
1995
	}
1996
1997
	/**
1998
	 * Loads the currently active modules.
1999
	 */
2000
	public static function load_modules() {
2001
		$is_offline_mode = ( new Status() )->is_offline_mode();
2002
		if (
2003
			! self::is_connection_ready()
2004
			&& ! $is_offline_mode
2005
			&& ! self::is_onboarding()
2006
			&& (
2007
				! is_multisite()
2008
				|| ! get_site_option( 'jetpack_protect_active' )
2009
			)
2010
		) {
2011
			return;
2012
		}
2013
2014
		$version = Jetpack_Options::get_option( 'version' );
2015 View Code Duplication
		if ( ! $version ) {
2016
			$version = $old_version = JETPACK__VERSION . ':' . time();
2017
			/** This action is documented in class.jetpack.php */
2018
			do_action( 'updating_jetpack_version', $version, false );
2019
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2020
		}
2021
		list( $version ) = explode( ':', $version );
2022
2023
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
2024
2025
		$modules_data = array();
2026
2027
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
2028
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
2029
			$updated_modules = array();
2030
			foreach ( $modules as $module ) {
2031
				$modules_data[ $module ] = self::get_module( $module );
2032
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
2033
					continue;
2034
				}
2035
2036
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2037
					continue;
2038
				}
2039
2040
				$updated_modules[] = $module;
2041
			}
2042
2043
			$modules = array_diff( $modules, $updated_modules );
2044
		}
2045
2046
		$is_userless = self::connection()->is_userless();
2047
2048
		foreach ( $modules as $index => $module ) {
2049
			// If we're in offline/user-less mode, disable modules requiring a connection/user connection.
2050
			if ( $is_offline_mode || $is_userless ) {
2051
				// Prime the pump if we need to
2052
				if ( empty( $modules_data[ $module ] ) ) {
2053
					$modules_data[ $module ] = self::get_module( $module );
2054
				}
2055
				// If the module requires a connection, but we're in local mode, don't include it.
2056
				if ( $is_offline_mode && $modules_data[ $module ]['requires_connection'] ) {
2057
					continue;
2058
				}
2059
2060
				if ( $is_userless && $modules_data[ $module ]['requires_user_connection'] ) {
2061
					continue;
2062
				}
2063
			}
2064
2065
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2066
				continue;
2067
			}
2068
2069
			if ( ! include_once self::get_module_path( $module ) ) {
2070
				unset( $modules[ $index ] );
2071
				self::update_active_modules( array_values( $modules ) );
2072
				continue;
2073
			}
2074
2075
			/**
2076
			 * Fires when a specific module is loaded.
2077
			 * The dynamic part of the hook, $module, is the module slug.
2078
			 *
2079
			 * @since 1.1.0
2080
			 */
2081
			do_action( 'jetpack_module_loaded_' . $module );
2082
		}
2083
2084
		/**
2085
		 * Fires when all the modules are loaded.
2086
		 *
2087
		 * @since 1.1.0
2088
		 */
2089
		do_action( 'jetpack_modules_loaded' );
2090
2091
		// 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.
2092
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2093
	}
2094
2095
	/**
2096
	 * Check if Jetpack's REST API compat file should be included
2097
	 *
2098
	 * @action plugins_loaded
2099
	 * @return null
2100
	 */
2101
	public function check_rest_api_compat() {
2102
		/**
2103
		 * Filters the list of REST API compat files to be included.
2104
		 *
2105
		 * @since 2.2.5
2106
		 *
2107
		 * @param array $args Array of REST API compat files to include.
2108
		 */
2109
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2110
2111
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2112
			require_once $_jetpack_rest_api_compat_include;
2113
		}
2114
	}
2115
2116
	/**
2117
	 * Gets all plugins currently active in values, regardless of whether they're
2118
	 * traditionally activated or network activated.
2119
	 *
2120
	 * @todo Store the result in core's object cache maybe?
2121
	 */
2122
	public static function get_active_plugins() {
2123
		$active_plugins = (array) get_option( 'active_plugins', array() );
2124
2125
		if ( is_multisite() ) {
2126
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2127
			// whereas active_plugins stores them in the values.
2128
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2129
			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...
2130
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2131
			}
2132
		}
2133
2134
		sort( $active_plugins );
2135
2136
		return array_unique( $active_plugins );
2137
	}
2138
2139
	/**
2140
	 * Gets and parses additional plugin data to send with the heartbeat data
2141
	 *
2142
	 * @since 3.8.1
2143
	 *
2144
	 * @return array Array of plugin data
2145
	 */
2146
	public static function get_parsed_plugin_data() {
2147
		if ( ! function_exists( 'get_plugins' ) ) {
2148
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2149
		}
2150
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2151
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2152
		$active_plugins = self::get_active_plugins();
2153
2154
		$plugins = array();
2155
		foreach ( $all_plugins as $path => $plugin_data ) {
2156
			$plugins[ $path ] = array(
2157
				'is_active' => in_array( $path, $active_plugins ),
2158
				'file'      => $path,
2159
				'name'      => $plugin_data['Name'],
2160
				'version'   => $plugin_data['Version'],
2161
				'author'    => $plugin_data['Author'],
2162
			);
2163
		}
2164
2165
		return $plugins;
2166
	}
2167
2168
	/**
2169
	 * Gets and parses theme data to send with the heartbeat data
2170
	 *
2171
	 * @since 3.8.1
2172
	 *
2173
	 * @return array Array of theme data
2174
	 */
2175
	public static function get_parsed_theme_data() {
2176
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2177
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2178
2179
		$themes = array();
2180
		foreach ( $all_themes as $slug => $theme_data ) {
2181
			$theme_headers = array();
2182
			foreach ( $header_keys as $header_key ) {
2183
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2184
			}
2185
2186
			$themes[ $slug ] = array(
2187
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2188
				'slug'            => $slug,
2189
				'theme_root'      => $theme_data->get_theme_root_uri(),
2190
				'parent'          => $theme_data->parent(),
2191
				'headers'         => $theme_headers,
2192
			);
2193
		}
2194
2195
		return $themes;
2196
	}
2197
2198
	/**
2199
	 * Checks whether a specific plugin is active.
2200
	 *
2201
	 * We don't want to store these in a static variable, in case
2202
	 * there are switch_to_blog() calls involved.
2203
	 */
2204
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2205
		return in_array( $plugin, self::get_active_plugins() );
2206
	}
2207
2208
	/**
2209
	 * Check if Jetpack's Open Graph tags should be used.
2210
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2211
	 *
2212
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2213
	 * @action plugins_loaded
2214
	 * @return null
2215
	 */
2216
	public function check_open_graph() {
2217
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2218
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2219
		}
2220
2221
		$active_plugins = self::get_active_plugins();
2222
2223
		if ( ! empty( $active_plugins ) ) {
2224
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2225
				if ( in_array( $plugin, $active_plugins ) ) {
2226
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2227
					break;
2228
				}
2229
			}
2230
		}
2231
2232
		/**
2233
		 * Allow the addition of Open Graph Meta Tags to all pages.
2234
		 *
2235
		 * @since 2.0.3
2236
		 *
2237
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2238
		 */
2239
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2240
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2241
		}
2242
	}
2243
2244
	/**
2245
	 * Check if Jetpack's Twitter tags should be used.
2246
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2247
	 *
2248
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2249
	 * @action plugins_loaded
2250
	 * @return null
2251
	 */
2252
	public function check_twitter_tags() {
2253
2254
		$active_plugins = self::get_active_plugins();
2255
2256
		if ( ! empty( $active_plugins ) ) {
2257
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2258
				if ( in_array( $plugin, $active_plugins ) ) {
2259
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2260
					break;
2261
				}
2262
			}
2263
		}
2264
2265
		/**
2266
		 * Allow Twitter Card Meta tags to be disabled.
2267
		 *
2268
		 * @since 2.6.0
2269
		 *
2270
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2271
		 */
2272
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2273
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2274
		}
2275
	}
2276
2277
	/**
2278
	 * Allows plugins to submit security reports.
2279
	 *
2280
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2281
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2282
	 * @param array  $args         See definitions above
2283
	 */
2284
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2285
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2286
	}
2287
2288
	/* Jetpack Options API */
2289
2290
	public static function get_option_names( $type = 'compact' ) {
2291
		return Jetpack_Options::get_option_names( $type );
2292
	}
2293
2294
	/**
2295
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2296
	 *
2297
	 * @param string $name    Option name
2298
	 * @param mixed  $default (optional)
2299
	 */
2300
	public static function get_option( $name, $default = false ) {
2301
		return Jetpack_Options::get_option( $name, $default );
2302
	}
2303
2304
	/**
2305
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2306
	 *
2307
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2308
	 * @param string $name  Option name
2309
	 * @param mixed  $value Option value
2310
	 */
2311
	public static function update_option( $name, $value ) {
2312
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2313
		return Jetpack_Options::update_option( $name, $value );
2314
	}
2315
2316
	/**
2317
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2318
	 *
2319
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2320
	 * @param array $array array( option name => option value, ... )
2321
	 */
2322
	public static function update_options( $array ) {
2323
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2324
		return Jetpack_Options::update_options( $array );
2325
	}
2326
2327
	/**
2328
	 * Deletes the given option.  May be passed multiple option names as an array.
2329
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2330
	 *
2331
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2332
	 * @param string|array $names
2333
	 */
2334
	public static function delete_option( $names ) {
2335
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2336
		return Jetpack_Options::delete_option( $names );
2337
	}
2338
2339
	/**
2340
	 * Enters a user token into the user_tokens option
2341
	 *
2342
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2343
	 *
2344
	 * @param int    $user_id The user id.
2345
	 * @param string $token The user token.
2346
	 * @param bool   $is_master_user Whether the user is the master user.
2347
	 * @return bool
2348
	 */
2349
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2350
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2351
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2352
	}
2353
2354
	/**
2355
	 * Returns an array of all PHP files in the specified absolute path.
2356
	 * Equivalent to glob( "$absolute_path/*.php" ).
2357
	 *
2358
	 * @param string $absolute_path The absolute path of the directory to search.
2359
	 * @return array Array of absolute paths to the PHP files.
2360
	 */
2361
	public static function glob_php( $absolute_path ) {
2362
		if ( function_exists( 'glob' ) ) {
2363
			return glob( "$absolute_path/*.php" );
2364
		}
2365
2366
		$absolute_path = untrailingslashit( $absolute_path );
2367
		$files         = array();
2368
		if ( ! $dir = @opendir( $absolute_path ) ) {
2369
			return $files;
2370
		}
2371
2372
		while ( false !== $file = readdir( $dir ) ) {
2373
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2374
				continue;
2375
			}
2376
2377
			$file = "$absolute_path/$file";
2378
2379
			if ( ! is_file( $file ) ) {
2380
				continue;
2381
			}
2382
2383
			$files[] = $file;
2384
		}
2385
2386
		closedir( $dir );
2387
2388
		return $files;
2389
	}
2390
2391
	public static function activate_new_modules( $redirect = false ) {
2392
		if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2393
			return;
2394
		}
2395
2396
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2397 View Code Duplication
		if ( ! $jetpack_old_version ) {
2398
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2399
			/** This action is documented in class.jetpack.php */
2400
			do_action( 'updating_jetpack_version', $version, false );
2401
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2402
		}
2403
2404
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2405
2406
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2407
			return;
2408
		}
2409
2410
		$active_modules     = self::get_active_modules();
2411
		$reactivate_modules = array();
2412
		foreach ( $active_modules as $active_module ) {
2413
			$module = self::get_module( $active_module );
2414
			if ( ! isset( $module['changed'] ) ) {
2415
				continue;
2416
			}
2417
2418
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2419
				continue;
2420
			}
2421
2422
			$reactivate_modules[] = $active_module;
2423
			self::deactivate_module( $active_module );
2424
		}
2425
2426
		$new_version = JETPACK__VERSION . ':' . time();
2427
		/** This action is documented in class.jetpack.php */
2428
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2429
		Jetpack_Options::update_options(
2430
			array(
2431
				'version'     => $new_version,
2432
				'old_version' => $jetpack_old_version,
2433
			)
2434
		);
2435
2436
		self::state( 'message', 'modules_activated' );
2437
2438
		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...
2439
2440
		if ( $redirect ) {
2441
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2442
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2443
				$page = $_GET['page'];
2444
			}
2445
2446
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2447
			exit;
2448
		}
2449
	}
2450
2451
	/**
2452
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2453
	 * Make sure to tuck away module "library" files in a sub-directory.
2454
	 *
2455
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2456
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2457
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2458
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2459
	 *
2460
	 * @return array $modules Array of module slugs
2461
	 */
2462
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2463
		static $modules = null;
2464
2465
		if ( ! isset( $modules ) ) {
2466
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2467
			// Use the cache if we're on the front-end and it's available...
2468
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2469
				$modules = $available_modules_option[ JETPACK__VERSION ];
2470
			} else {
2471
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2472
2473
				$modules = array();
2474
2475
				foreach ( $files as $file ) {
2476
					if ( ! $headers = self::get_module( $file ) ) {
2477
						continue;
2478
					}
2479
2480
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2481
				}
2482
2483
				Jetpack_Options::update_option(
2484
					'available_modules',
2485
					array(
2486
						JETPACK__VERSION => $modules,
2487
					)
2488
				);
2489
			}
2490
		}
2491
2492
		/**
2493
		 * Filters the array of modules available to be activated.
2494
		 *
2495
		 * @since 2.4.0
2496
		 *
2497
		 * @param array $modules Array of available modules.
2498
		 * @param string $min_version Minimum version number required to use modules.
2499
		 * @param string $max_version Maximum version number required to use modules.
2500
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2501
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2502
		 */
2503
		$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...
2504
2505
		if ( ! $min_version && ! $max_version && is_null( $requires_connection ) && is_null( $requires_user_connection ) ) {
2506
			return array_keys( $mods );
2507
		}
2508
2509
		$r = array();
2510
		foreach ( $mods as $slug => $introduced ) {
2511
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2512
				continue;
2513
			}
2514
2515
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2516
				continue;
2517
			}
2518
2519
			$mod_details = self::get_module( $slug );
2520
2521
			if ( null !== $requires_connection && (bool) $requires_connection !== $mod_details['requires_connection'] ) {
2522
				continue;
2523
			}
2524
2525
			if ( null !== $requires_user_connection && (bool) $requires_user_connection !== $mod_details['requires_user_connection'] ) {
2526
				continue;
2527
			}
2528
2529
			$r[] = $slug;
2530
		}
2531
2532
		return $r;
2533
	}
2534
2535
	/**
2536
	 * Get default modules loaded on activation.
2537
	 *
2538
	 * @param bool|string $min_version Onlu return modules introduced in this version or later. Default is false, do not filter.
2539
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2540
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2541
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2542
	 *
2543
	 * @return array $modules Array of module slugs
2544
	 */
2545
	public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2546
		$return = array();
2547
2548
		foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2549
			$module_data = self::get_module( $module );
2550
2551
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2552
				case 'yes':
2553
					$return[] = $module;
2554
					break;
2555
				case 'public':
2556
					if ( Jetpack_Options::get_option( 'public' ) ) {
2557
						$return[] = $module;
2558
					}
2559
					break;
2560
				case 'no':
2561
				default:
2562
					break;
2563
			}
2564
		}
2565
		/**
2566
		 * Filters the array of default modules.
2567
		 *
2568
		 * @since 2.5.0
2569
		 *
2570
		 * @param array $return Array of default modules.
2571
		 * @param string $min_version Minimum version number required to use modules.
2572
		 * @param string $max_version Maximum version number required to use modules.
2573
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2574
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2575
		 */
2576
		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...
2577
	}
2578
2579
	/**
2580
	 * Checks activated modules during auto-activation to determine
2581
	 * if any of those modules are being deprecated.  If so, close
2582
	 * them out, and add any replacement modules.
2583
	 *
2584
	 * Runs at priority 99 by default.
2585
	 *
2586
	 * This is run late, so that it can still activate a module if
2587
	 * the new module is a replacement for another that the user
2588
	 * currently has active, even if something at the normal priority
2589
	 * would kibosh everything.
2590
	 *
2591
	 * @since 2.6
2592
	 * @uses jetpack_get_default_modules filter
2593
	 * @param array $modules
2594
	 * @return array
2595
	 */
2596
	function handle_deprecated_modules( $modules ) {
2597
		$deprecated_modules = array(
2598
			'debug'            => null,  // Closed out and moved to the debugger library.
2599
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2600
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2601
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2602
		);
2603
2604
		// Don't activate SSO if they never completed activating WPCC.
2605
		if ( self::is_module_active( 'wpcc' ) ) {
2606
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2607
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2608
				$deprecated_modules['wpcc'] = null;
2609
			}
2610
		}
2611
2612
		foreach ( $deprecated_modules as $module => $replacement ) {
2613
			if ( self::is_module_active( $module ) ) {
2614
				self::deactivate_module( $module );
2615
				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...
2616
					$modules[] = $replacement;
2617
				}
2618
			}
2619
		}
2620
2621
		return array_unique( $modules );
2622
	}
2623
2624
	/**
2625
	 * Checks activated plugins during auto-activation to determine
2626
	 * if any of those plugins are in the list with a corresponding module
2627
	 * that is not compatible with the plugin. The module will not be allowed
2628
	 * to auto-activate.
2629
	 *
2630
	 * @since 2.6
2631
	 * @uses jetpack_get_default_modules filter
2632
	 * @param array $modules
2633
	 * @return array
2634
	 */
2635
	function filter_default_modules( $modules ) {
2636
2637
		$active_plugins = self::get_active_plugins();
2638
2639
		if ( ! empty( $active_plugins ) ) {
2640
2641
			// For each module we'd like to auto-activate...
2642
			foreach ( $modules as $key => $module ) {
2643
				// If there are potential conflicts for it...
2644
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2645
					// For each potential conflict...
2646
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2647
						// If that conflicting plugin is active...
2648
						if ( in_array( $plugin, $active_plugins ) ) {
2649
							// Remove that item from being auto-activated.
2650
							unset( $modules[ $key ] );
2651
						}
2652
					}
2653
				}
2654
			}
2655
		}
2656
2657
		return $modules;
2658
	}
2659
2660
	/**
2661
	 * Extract a module's slug from its full path.
2662
	 */
2663
	public static function get_module_slug( $file ) {
2664
		return str_replace( '.php', '', basename( $file ) );
2665
	}
2666
2667
	/**
2668
	 * Generate a module's path from its slug.
2669
	 */
2670
	public static function get_module_path( $slug ) {
2671
		/**
2672
		 * Filters the path of a modules.
2673
		 *
2674
		 * @since 7.4.0
2675
		 *
2676
		 * @param array $return The absolute path to a module's root php file
2677
		 * @param string $slug The module slug
2678
		 */
2679
		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...
2680
	}
2681
2682
	/**
2683
	 * Load module data from module file. Headers differ from WordPress
2684
	 * plugin headers to avoid them being identified as standalone
2685
	 * plugins on the WordPress plugins page.
2686
	 */
2687
	public static function get_module( $module ) {
2688
		$headers = array(
2689
			'name'                      => 'Module Name',
2690
			'description'               => 'Module Description',
2691
			'sort'                      => 'Sort Order',
2692
			'recommendation_order'      => 'Recommendation Order',
2693
			'introduced'                => 'First Introduced',
2694
			'changed'                   => 'Major Changes In',
2695
			'deactivate'                => 'Deactivate',
2696
			'free'                      => 'Free',
2697
			'requires_connection'       => 'Requires Connection',
2698
			'requires_user_connection'  => 'Requires User Connection',
2699
			'auto_activate'             => 'Auto Activate',
2700
			'module_tags'               => 'Module Tags',
2701
			'feature'                   => 'Feature',
2702
			'additional_search_queries' => 'Additional Search Queries',
2703
			'plan_classes'              => 'Plans',
2704
		);
2705
2706
		static $modules_details;
2707
		$file = self::get_module_path( self::get_module_slug( $module ) );
2708
2709
		if ( isset( $modules_details[ $module ] ) ) {
2710
			$mod = $modules_details[ $module ];
2711
		} else {
2712
2713
			$mod = self::get_file_data( $file, $headers );
2714
			if ( empty( $mod['name'] ) ) {
2715
				return false;
2716
			}
2717
2718
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2719
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2720
			$mod['deactivate']               = empty( $mod['deactivate'] );
2721
			$mod['free']                     = empty( $mod['free'] );
2722
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2723
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2724
2725
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2726
				$mod['auto_activate'] = 'No';
2727
			} else {
2728
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2729
			}
2730
2731
			if ( $mod['module_tags'] ) {
2732
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2733
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2734
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2735
			} else {
2736
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2737
			}
2738
2739 View Code Duplication
			if ( $mod['plan_classes'] ) {
2740
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2741
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2742
			} else {
2743
				$mod['plan_classes'] = array( 'free' );
2744
			}
2745
2746 View Code Duplication
			if ( $mod['feature'] ) {
2747
				$mod['feature'] = explode( ',', $mod['feature'] );
2748
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2749
			} else {
2750
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2751
			}
2752
2753
			$modules_details[ $module ] = $mod;
2754
2755
		}
2756
2757
		/**
2758
		 * Filters the feature array on a module.
2759
		 *
2760
		 * This filter allows you to control where each module is filtered: Recommended,
2761
		 * and the default "Other" listing.
2762
		 *
2763
		 * @since 3.5.0
2764
		 *
2765
		 * @param array   $mod['feature'] The areas to feature this module:
2766
		 *     'Recommended' shows on the main Jetpack admin screen.
2767
		 *     'Other' should be the default if no other value is in the array.
2768
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2769
		 * @param array   $mod All the currently assembled module data.
2770
		 */
2771
		$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...
2772
2773
		/**
2774
		 * Filter the returned data about a module.
2775
		 *
2776
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2777
		 * so please be careful.
2778
		 *
2779
		 * @since 3.6.0
2780
		 *
2781
		 * @param array   $mod    The details of the requested module.
2782
		 * @param string  $module The slug of the module, e.g. sharedaddy
2783
		 * @param string  $file   The path to the module source file.
2784
		 */
2785
		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...
2786
	}
2787
2788
	/**
2789
	 * Like core's get_file_data implementation, but caches the result.
2790
	 */
2791
	public static function get_file_data( $file, $headers ) {
2792
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2793
		$file_name = basename( $file );
2794
2795
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2796
2797
		$file_data_option = get_transient( $cache_key );
2798
2799
		if ( ! is_array( $file_data_option ) ) {
2800
			delete_transient( $cache_key );
2801
			$file_data_option = false;
2802
		}
2803
2804
		if ( false === $file_data_option ) {
2805
			$file_data_option = array();
2806
		}
2807
2808
		$key           = md5( $file_name . serialize( $headers ) );
2809
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2810
2811
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2812
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2813
			return $file_data_option[ $key ];
2814
		}
2815
2816
		$data = get_file_data( $file, $headers );
2817
2818
		$file_data_option[ $key ] = $data;
2819
2820
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2821
2822
		return $data;
2823
	}
2824
2825
	/**
2826
	 * Return translated module tag.
2827
	 *
2828
	 * @param string $tag Tag as it appears in each module heading.
2829
	 *
2830
	 * @return mixed
2831
	 */
2832
	public static function translate_module_tag( $tag ) {
2833
		return jetpack_get_module_i18n_tag( $tag );
2834
	}
2835
2836
	/**
2837
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2838
	 *
2839
	 * @since 3.9.2
2840
	 *
2841
	 * @param array $modules
2842
	 *
2843
	 * @return string|void
2844
	 */
2845
	public static function get_translated_modules( $modules ) {
2846
		foreach ( $modules as $index => $module ) {
2847
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2848
			if ( isset( $module['name'] ) ) {
2849
				$modules[ $index ]['name'] = $i18n_module['name'];
2850
			}
2851
			if ( isset( $module['description'] ) ) {
2852
				$modules[ $index ]['description']       = $i18n_module['description'];
2853
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2854
			}
2855
		}
2856
		return $modules;
2857
	}
2858
2859
	/**
2860
	 * Get a list of activated modules as an array of module slugs.
2861
	 */
2862
	public static function get_active_modules() {
2863
		$active = Jetpack_Options::get_option( 'active_modules' );
2864
2865
		if ( ! is_array( $active ) ) {
2866
			$active = array();
2867
		}
2868
2869
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2870
			$active[] = 'vaultpress';
2871
		} else {
2872
			$active = array_diff( $active, array( 'vaultpress' ) );
2873
		}
2874
2875
		// If protect is active on the main site of a multisite, it should be active on all sites.
2876
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2877
			$active[] = 'protect';
2878
		}
2879
2880
		/**
2881
		 * Allow filtering of the active modules.
2882
		 *
2883
		 * Gives theme and plugin developers the power to alter the modules that
2884
		 * are activated on the fly.
2885
		 *
2886
		 * @since 5.8.0
2887
		 *
2888
		 * @param array $active Array of active module slugs.
2889
		 */
2890
		$active = apply_filters( 'jetpack_active_modules', $active );
2891
2892
		return array_unique( $active );
2893
	}
2894
2895
	/**
2896
	 * Check whether or not a Jetpack module is active.
2897
	 *
2898
	 * @param string $module The slug of a Jetpack module.
2899
	 * @return bool
2900
	 *
2901
	 * @static
2902
	 */
2903
	public static function is_module_active( $module ) {
2904
		return in_array( $module, self::get_active_modules() );
2905
	}
2906
2907
	public static function is_module( $module ) {
2908
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2909
	}
2910
2911
	/**
2912
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2913
	 *
2914
	 * @param bool $catch True to start catching, False to stop.
2915
	 *
2916
	 * @static
2917
	 */
2918
	public static function catch_errors( $catch ) {
2919
		static $display_errors, $error_reporting;
2920
2921
		if ( $catch ) {
2922
			$display_errors  = @ini_set( 'display_errors', 1 );
2923
			$error_reporting = @error_reporting( E_ALL );
2924
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2925
		} else {
2926
			@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...
2927
			@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...
2928
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2929
		}
2930
	}
2931
2932
	/**
2933
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2934
	 */
2935
	public static function catch_errors_on_shutdown() {
2936
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2937
	}
2938
2939
	/**
2940
	 * Rewrite any string to make paths easier to read.
2941
	 *
2942
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2943
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2944
	 *
2945
	 * @param $string
2946
	 * @return mixed
2947
	 */
2948
	public static function alias_directories( $string ) {
2949
		// ABSPATH has a trailing slash.
2950
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2951
		// WP_CONTENT_DIR does not have a trailing slash.
2952
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2953
2954
		return $string;
2955
	}
2956
2957
	public static function activate_default_modules(
2958
		$min_version = false,
2959
		$max_version = false,
2960
		$other_modules = array(),
2961
		$redirect = null,
2962
		$send_state_messages = null,
2963
		$requires_connection = null,
2964
		$requires_user_connection = null
2965
	) {
2966
		$jetpack = self::init();
2967
2968
		if ( is_null( $redirect ) ) {
2969
			if (
2970
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2971
			||
2972
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2973
			||
2974
				( defined( 'WP_CLI' ) && WP_CLI )
2975
			||
2976
				( defined( 'DOING_CRON' ) && DOING_CRON )
2977
			||
2978
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2979
			) {
2980
				$redirect = false;
2981
			} elseif ( is_admin() ) {
2982
				$redirect = true;
2983
			} else {
2984
				$redirect = false;
2985
			}
2986
		}
2987
2988
		if ( is_null( $send_state_messages ) ) {
2989
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2990
		}
2991
2992
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2993
		$modules = array_merge( $other_modules, $modules );
2994
2995
		// Look for standalone plugins and disable if active.
2996
2997
		$to_deactivate = array();
2998
		foreach ( $modules as $module ) {
2999
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3000
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
3001
			}
3002
		}
3003
3004
		$deactivated = array();
3005
		foreach ( $to_deactivate as $module => $deactivate_me ) {
3006
			list( $probable_file, $probable_title ) = $deactivate_me;
3007
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
3008
				$deactivated[] = $module;
3009
			}
3010
		}
3011
3012
		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...
3013
			if ( $send_state_messages ) {
3014
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
3015
			}
3016
3017
			if ( $redirect ) {
3018
				$url = add_query_arg(
3019
					array(
3020
						'action'   => 'activate_default_modules',
3021
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
3022
					),
3023
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
3024
				);
3025
				wp_safe_redirect( $url );
3026
				exit;
3027
			}
3028
		}
3029
3030
		/**
3031
		 * Fires before default modules are activated.
3032
		 *
3033
		 * @since 1.9.0
3034
		 *
3035
		 * @param string    $min_version Minimum version number required to use modules.
3036
		 * @param string    $max_version Maximum version number required to use modules.
3037
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3038
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3039
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3040
		 */
3041
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3042
3043
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3044
		if ( $send_state_messages ) {
3045
			self::restate();
3046
			self::catch_errors( true );
3047
		}
3048
3049
		$active = self::get_active_modules();
3050
3051
		foreach ( $modules as $module ) {
3052
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3053
				$active[] = $module;
3054
				self::update_active_modules( $active );
3055
				continue;
3056
			}
3057
3058
			if ( $send_state_messages && in_array( $module, $active ) ) {
3059
				$module_info = self::get_module( $module );
3060 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3061
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3062
					if ( $active_state = self::state( $state ) ) {
3063
						$active_state = explode( ',', $active_state );
3064
					} else {
3065
						$active_state = array();
3066
					}
3067
					$active_state[] = $module;
3068
					self::state( $state, implode( ',', $active_state ) );
3069
				}
3070
				continue;
3071
			}
3072
3073
			$file = self::get_module_path( $module );
3074
			if ( ! file_exists( $file ) ) {
3075
				continue;
3076
			}
3077
3078
			// we'll override this later if the plugin can be included without fatal error
3079
			if ( $redirect ) {
3080
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3081
			}
3082
3083
			if ( $send_state_messages ) {
3084
				self::state( 'error', 'module_activation_failed' );
3085
				self::state( 'module', $module );
3086
			}
3087
3088
			ob_start();
3089
			require_once $file;
3090
3091
			$active[] = $module;
3092
3093 View Code Duplication
			if ( $send_state_messages ) {
3094
3095
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3096
				if ( $active_state = self::state( $state ) ) {
3097
					$active_state = explode( ',', $active_state );
3098
				} else {
3099
					$active_state = array();
3100
				}
3101
				$active_state[] = $module;
3102
				self::state( $state, implode( ',', $active_state ) );
3103
			}
3104
3105
			self::update_active_modules( $active );
3106
3107
			ob_end_clean();
3108
		}
3109
3110
		if ( $send_state_messages ) {
3111
			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...
3112
			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...
3113
		}
3114
3115
		self::catch_errors( false );
3116
		/**
3117
		 * Fires when default modules are activated.
3118
		 *
3119
		 * @since 1.9.0
3120
		 *
3121
		 * @param string    $min_version Minimum version number required to use modules.
3122
		 * @param string    $max_version Maximum version number required to use modules.
3123
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3124
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3125
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3126
		 */
3127
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3128
	}
3129
3130
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3131
		/**
3132
		 * Fires before a module is activated.
3133
		 *
3134
		 * @since 2.6.0
3135
		 *
3136
		 * @param string $module Module slug.
3137
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3138
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3139
		 */
3140
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3141
3142
		$jetpack = self::init();
3143
3144
		if ( ! strlen( $module ) ) {
3145
			return false;
3146
		}
3147
3148
		if ( ! self::is_module( $module ) ) {
3149
			return false;
3150
		}
3151
3152
		// If it's already active, then don't do it again
3153
		$active = self::get_active_modules();
3154
		foreach ( $active as $act ) {
3155
			if ( $act == $module ) {
3156
				return true;
3157
			}
3158
		}
3159
3160
		$module_data = self::get_module( $module );
3161
3162
		$is_offline_mode = ( new Status() )->is_offline_mode();
3163
		if ( ! self::is_connection_ready() ) {
3164
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3165
				return false;
3166
			}
3167
3168
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3169
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3170
				return false;
3171
			}
3172
		}
3173
3174
		// Check and see if the old plugin is active
3175
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3176
			// Deactivate the old plugin
3177
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3178
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3179
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3180
				self::state( 'deactivated_plugins', $module );
3181
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3182
				exit;
3183
			}
3184
		}
3185
3186
		// Protect won't work with mis-configured IPs
3187
		if ( 'protect' === $module ) {
3188
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3189
			if ( ! jetpack_protect_get_ip() ) {
3190
				self::state( 'message', 'protect_misconfigured_ip' );
3191
				return false;
3192
			}
3193
		}
3194
3195
		if ( ! Jetpack_Plan::supports( $module ) ) {
3196
			return false;
3197
		}
3198
3199
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3200
		self::state( 'module', $module );
3201
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3202
3203
		self::catch_errors( true );
3204
		ob_start();
3205
		require self::get_module_path( $module );
3206
		/** This action is documented in class.jetpack.php */
3207
		do_action( 'jetpack_activate_module', $module );
3208
		$active[] = $module;
3209
		self::update_active_modules( $active );
3210
3211
		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...
3212
		ob_end_clean();
3213
		self::catch_errors( false );
3214
3215
		if ( $redirect ) {
3216
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3217
		}
3218
		if ( $exit ) {
3219
			exit;
3220
		}
3221
		return true;
3222
	}
3223
3224
	function activate_module_actions( $module ) {
3225
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3226
	}
3227
3228
	public static function deactivate_module( $module ) {
3229
		/**
3230
		 * Fires when a module is deactivated.
3231
		 *
3232
		 * @since 1.9.0
3233
		 *
3234
		 * @param string $module Module slug.
3235
		 */
3236
		do_action( 'jetpack_pre_deactivate_module', $module );
3237
3238
		$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...
3239
3240
		$active = self::get_active_modules();
3241
		$new    = array_filter( array_diff( $active, (array) $module ) );
3242
3243
		return self::update_active_modules( $new );
3244
	}
3245
3246
	public static function enable_module_configurable( $module ) {
3247
		$module = self::get_module_slug( $module );
3248
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3249
	}
3250
3251
	/**
3252
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3253
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3254
	 *
3255
	 * @param string $module Module slug
3256
	 * @return string $url module configuration URL
3257
	 */
3258
	public static function module_configuration_url( $module ) {
3259
		$module      = self::get_module_slug( $module );
3260
		$default_url = self::admin_url() . "#/settings?term=$module";
3261
		/**
3262
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3263
		 *
3264
		 * @since 6.9.0
3265
		 *
3266
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3267
		 */
3268
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3269
3270
		return $url;
3271
	}
3272
3273
	/* Installation */
3274
	public static function bail_on_activation( $message, $deactivate = true ) {
3275
		?>
3276
<!doctype html>
3277
<html>
3278
<head>
3279
<meta charset="<?php bloginfo( 'charset' ); ?>">
3280
<style>
3281
* {
3282
	text-align: center;
3283
	margin: 0;
3284
	padding: 0;
3285
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3286
}
3287
p {
3288
	margin-top: 1em;
3289
	font-size: 18px;
3290
}
3291
</style>
3292
<body>
3293
<p><?php echo esc_html( $message ); ?></p>
3294
</body>
3295
</html>
3296
		<?php
3297
		if ( $deactivate ) {
3298
			$plugins = get_option( 'active_plugins' );
3299
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3300
			$update  = false;
3301
			foreach ( $plugins as $i => $plugin ) {
3302
				if ( $plugin === $jetpack ) {
3303
					$plugins[ $i ] = false;
3304
					$update        = true;
3305
				}
3306
			}
3307
3308
			if ( $update ) {
3309
				update_option( 'active_plugins', array_filter( $plugins ) );
3310
			}
3311
		}
3312
		exit;
3313
	}
3314
3315
	/**
3316
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3317
	 *
3318
	 * @static
3319
	 */
3320
	public static function plugin_activation( $network_wide ) {
3321
		Jetpack_Options::update_option( 'activated', 1 );
3322
3323
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3324
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3325
		}
3326
3327
		if ( $network_wide ) {
3328
			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...
3329
		}
3330
3331
		// For firing one-off events (notices) immediately after activation
3332
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3333
3334
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3335
3336
		Health::on_jetpack_activated();
3337
3338
		self::plugin_initialize();
3339
	}
3340
3341
	public static function get_activation_source( $referer_url ) {
3342
3343
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3344
			return array( 'wp-cli', null );
3345
		}
3346
3347
		$referer = wp_parse_url( $referer_url );
3348
3349
		$source_type  = 'unknown';
3350
		$source_query = null;
3351
3352
		if ( ! is_array( $referer ) ) {
3353
			return array( $source_type, $source_query );
3354
		}
3355
3356
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3357
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3358
3359
		if ( isset( $referer['query'] ) ) {
3360
			parse_str( $referer['query'], $query_parts );
3361
		} else {
3362
			$query_parts = array();
3363
		}
3364
3365
		if ( $plugins_path === $referer['path'] ) {
3366
			$source_type = 'list';
3367
		} elseif ( $plugins_install_path === $referer['path'] ) {
3368
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3369
			switch ( $tab ) {
3370
				case 'popular':
3371
					$source_type = 'popular';
3372
					break;
3373
				case 'recommended':
3374
					$source_type = 'recommended';
3375
					break;
3376
				case 'favorites':
3377
					$source_type = 'favorites';
3378
					break;
3379
				case 'search':
3380
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3381
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3382
					break;
3383
				default:
3384
					$source_type = 'featured';
3385
			}
3386
		}
3387
3388
		return array( $source_type, $source_query );
3389
	}
3390
3391
	/**
3392
	 * Runs before bumping version numbers up to a new version
3393
	 *
3394
	 * @param string $version    Version:timestamp.
3395
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3396
	 */
3397
	public static function do_version_bump( $version, $old_version ) {
3398
		if ( $old_version ) { // For existing Jetpack installations.
3399
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3400
3401
			// If a front end page is visited after the update, the 'wp' action will fire.
3402
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3403
3404
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3405
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3406
		}
3407
	}
3408
3409
	/**
3410
	 * Sets the display_update_modal state.
3411
	 */
3412
	public static function set_update_modal_display() {
3413
		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...
3414
3415
	}
3416
3417
	/**
3418
	 * Enqueues the block library styles.
3419
	 *
3420
	 * @param string $hook The current admin page.
3421
	 */
3422
	public static function enqueue_block_style( $hook ) {
3423
		if ( 'toplevel_page_jetpack' === $hook ) {
3424
			wp_enqueue_style( 'wp-block-library' );
3425
		}
3426
	}
3427
3428
	/**
3429
	 * Sets the internal version number and activation state.
3430
	 *
3431
	 * @static
3432
	 */
3433
	public static function plugin_initialize() {
3434
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3435
			Jetpack_Options::update_option( 'activated', 2 );
3436
		}
3437
3438 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3439
			$version = $old_version = JETPACK__VERSION . ':' . time();
3440
			/** This action is documented in class.jetpack.php */
3441
			do_action( 'updating_jetpack_version', $version, false );
3442
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3443
		}
3444
3445
		self::load_modules();
3446
3447
		Jetpack_Options::delete_option( 'do_activate' );
3448
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3449
	}
3450
3451
	/**
3452
	 * Removes all connection options
3453
	 *
3454
	 * @static
3455
	 */
3456
	public static function plugin_deactivation() {
3457
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3458
		$tracking = new Tracking();
3459
		$tracking->record_user_event( 'deactivate_plugin', array() );
3460
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3461
			Jetpack_Network::init()->deactivate();
3462
		} else {
3463
			self::disconnect( false );
3464
			// Jetpack_Heartbeat::init()->deactivate();
3465
		}
3466
	}
3467
3468
	/**
3469
	 * Disconnects from the Jetpack servers.
3470
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3471
	 *
3472
	 * @static
3473
	 */
3474
	public static function disconnect( $update_activated_state = true ) {
3475
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3476
3477
		$connection = self::connection();
3478
3479
		( new Nonce_Handler() )->clean_all();
3480
3481
		// If the site is in an IDC because sync is not allowed,
3482
		// let's make sure to not disconnect the production site.
3483
		if ( ! self::validate_sync_error_idc_option() ) {
3484
			$tracking = new Tracking();
3485
			$tracking->record_user_event( 'disconnect_site', array() );
3486
3487
			$connection->disconnect_site_wpcom( true );
3488
		}
3489
3490
		$connection->delete_all_connection_tokens( true );
3491
		Jetpack_IDC::clear_all_idc_options();
3492
3493
		if ( $update_activated_state ) {
3494
			Jetpack_Options::update_option( 'activated', 4 );
3495
		}
3496
3497
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3498
			// Check then record unique disconnection if site has never been disconnected previously
3499
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3500
				$jetpack_unique_connection['disconnected'] = 1;
3501
			} else {
3502
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3503
					// track unique disconnect
3504
					$jetpack = self::init();
3505
3506
					$jetpack->stat( 'connections', 'unique-disconnect' );
3507
					$jetpack->do_stats( 'server_side' );
3508
				}
3509
				// increment number of times disconnected
3510
				$jetpack_unique_connection['disconnected'] += 1;
3511
			}
3512
3513
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3514
		}
3515
3516
		// Delete all the sync related data. Since it could be taking up space.
3517
		Sender::get_instance()->uninstall();
3518
3519
	}
3520
3521
	/**
3522
	 * Disconnects the user
3523
	 *
3524
	 * @param int $user_id The user ID to disconnect.
3525
	 */
3526
	public function disconnect_user( $user_id ) {
3527
		$this->connection_manager->disconnect_user( $user_id );
3528
	}
3529
3530
	/**
3531
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3532
	 *
3533
	 * @deprecated since Jetpack 9.7.0
3534
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
3535
	 *
3536
	 * @return bool|WP_Error
3537
	 */
3538
	public static function try_registration() {
3539
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
3540
		return static::connection()->try_registration();
3541
	}
3542
3543
	/**
3544
	 * Checking the domain names in beta versions.
3545
	 * If this is a development version, before attempting to connect, let's make sure that the domains are viable.
3546
	 *
3547
	 * @param null|\WP_Error $error The domain validation error, or `null` if everything's fine.
3548
	 *
3549
	 * @return null|\WP_Error The domain validation error, or `null` if everything's fine.
3550
	 */
3551
	public static function registration_check_domains( $error ) {
3552
		if ( static::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3553
			$domains_to_check = array_unique(
3554
				array(
3555
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3556
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3557
				)
3558
			);
3559
			foreach ( $domains_to_check as $domain ) {
3560
				$result = static::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3559 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...
3561
				if ( is_wp_error( $result ) ) {
3562
					return $result;
3563
				}
3564
			}
3565
		}
3566
3567
		return $error;
3568
	}
3569
3570
	/**
3571
	 * Tracking an internal event log. Try not to put too much chaff in here.
3572
	 *
3573
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3574
	 */
3575
	public static function log( $code, $data = null ) {
3576
		// only grab the latest 200 entries
3577
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3578
3579
		// Append our event to the log
3580
		$log_entry = array(
3581
			'time'    => time(),
3582
			'user_id' => get_current_user_id(),
3583
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3584
			'code'    => $code,
3585
		);
3586
		// Don't bother storing it unless we've got some.
3587
		if ( ! is_null( $data ) ) {
3588
			$log_entry['data'] = $data;
3589
		}
3590
		$log[] = $log_entry;
3591
3592
		// Try add_option first, to make sure it's not autoloaded.
3593
		// @todo: Add an add_option method to Jetpack_Options
3594
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3595
			Jetpack_Options::update_option( 'log', $log );
3596
		}
3597
3598
		/**
3599
		 * Fires when Jetpack logs an internal event.
3600
		 *
3601
		 * @since 3.0.0
3602
		 *
3603
		 * @param array $log_entry {
3604
		 *  Array of details about the log entry.
3605
		 *
3606
		 *  @param string time Time of the event.
3607
		 *  @param int user_id ID of the user who trigerred the event.
3608
		 *  @param int blog_id Jetpack Blog ID.
3609
		 *  @param string code Unique name for the event.
3610
		 *  @param string data Data about the event.
3611
		 * }
3612
		 */
3613
		do_action( 'jetpack_log_entry', $log_entry );
3614
	}
3615
3616
	/**
3617
	 * Get the internal event log.
3618
	 *
3619
	 * @param $event (string) - only return the specific log events
3620
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3621
	 *
3622
	 * @return array of log events || WP_Error for invalid params
3623
	 */
3624
	public static function get_log( $event = false, $num = false ) {
3625
		if ( $event && ! is_string( $event ) ) {
3626
			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...
3627
		}
3628
3629
		if ( $num && ! is_numeric( $num ) ) {
3630
			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...
3631
		}
3632
3633
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3634
3635
		// If nothing set - act as it did before, otherwise let's start customizing the output
3636
		if ( ! $num && ! $event ) {
3637
			return $entire_log;
3638
		} else {
3639
			$entire_log = array_reverse( $entire_log );
3640
		}
3641
3642
		$custom_log_output = array();
3643
3644
		if ( $event ) {
3645
			foreach ( $entire_log as $log_event ) {
3646
				if ( $event == $log_event['code'] ) {
3647
					$custom_log_output[] = $log_event;
3648
				}
3649
			}
3650
		} else {
3651
			$custom_log_output = $entire_log;
3652
		}
3653
3654
		if ( $num ) {
3655
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3656
		}
3657
3658
		return $custom_log_output;
3659
	}
3660
3661
	/**
3662
	 * Log modification of important settings.
3663
	 */
3664
	public static function log_settings_change( $option, $old_value, $value ) {
3665
		switch ( $option ) {
3666
			case 'jetpack_sync_non_public_post_stati':
3667
				self::log( $option, $value );
3668
				break;
3669
		}
3670
	}
3671
3672
	/**
3673
	 * Return stat data for WPCOM sync
3674
	 */
3675
	public static function get_stat_data( $encode = true, $extended = true ) {
3676
		$data = Jetpack_Heartbeat::generate_stats_array();
3677
3678
		if ( $extended ) {
3679
			$additional_data = self::get_additional_stat_data();
3680
			$data            = array_merge( $data, $additional_data );
3681
		}
3682
3683
		if ( $encode ) {
3684
			return json_encode( $data );
3685
		}
3686
3687
		return $data;
3688
	}
3689
3690
	/**
3691
	 * Get additional stat data to sync to WPCOM
3692
	 */
3693
	public static function get_additional_stat_data( $prefix = '' ) {
3694
		$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...
3695
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3696
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3697
		$return[ "{$prefix}site-count" ]    = 0;
3698
3699
		if ( function_exists( 'get_blog_count' ) ) {
3700
			$return[ "{$prefix}site-count" ] = get_blog_count();
3701
		}
3702
		return $return;
3703
	}
3704
3705
	private static function get_site_user_count() {
3706
		global $wpdb;
3707
3708
		if ( function_exists( 'wp_is_large_network' ) ) {
3709
			if ( wp_is_large_network( 'users' ) ) {
3710
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3711
			}
3712
		}
3713
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3714
			// It wasn't there, so regenerate the data and save the transient
3715
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3716
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3717
		}
3718
		return $user_count;
3719
	}
3720
3721
	/* Admin Pages */
3722
3723
	function admin_init() {
3724
		// If the plugin is not connected, display a connect message.
3725
		if (
3726
			// the plugin was auto-activated and needs its candy
3727
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3728
		||
3729
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3730
			! Jetpack_Options::get_option( 'activated' )
3731
		) {
3732
			self::plugin_initialize();
3733
		}
3734
3735
		$is_offline_mode              = ( new Status() )->is_offline_mode();
3736
		$fallback_no_verify_ssl_certs = Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
3737
		/** Already documented in automattic/jetpack-connection::src/class-client.php */
3738
		$client_verify_ssl_certs = apply_filters( 'jetpack_client_verify_ssl_certs', false );
3739
3740
		if ( ! $is_offline_mode ) {
3741
			Jetpack_Connection_Banner::init();
3742
		}
3743
3744
		if ( ( self::is_connection_ready() || $is_offline_mode ) && false === $fallback_no_verify_ssl_certs && ! $client_verify_ssl_certs ) {
3745
			// Upgrade: 1.1 -> 1.1.1
3746
			// Check and see if host can verify the Jetpack servers' SSL certificate
3747
			$args = array();
3748
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3749
		}
3750
3751
		Jetpack_Recommendations_Banner::init();
3752
3753
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3754
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3755
		}
3756
3757
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3758
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3759
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3760
3761
		if ( isset( $_COOKIE['jetpackState']['display_update_modal'] ) ) {
3762
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3763
		}
3764
3765
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3766
3767
		if ( self::is_connection_ready() || $is_offline_mode ) {
3768
			// Artificially throw errors in certain specific cases during plugin activation.
3769
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3770
		}
3771
3772
		// Add custom column in wp-admin/users.php to show whether user is linked.
3773
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3774
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3775
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3776
	}
3777
3778
	function admin_body_class( $admin_body_class = '' ) {
3779
		$classes = explode( ' ', trim( $admin_body_class ) );
3780
3781
		$classes[] = self::is_connection_ready() ? 'jetpack-connected' : 'jetpack-disconnected';
3782
3783
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3784
		return " $admin_body_class ";
3785
	}
3786
3787
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3788
		return $admin_body_class . ' jetpack-pagestyles ';
3789
	}
3790
3791
	/**
3792
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3793
	 * This function artificially throws errors for such cases (per a specific list).
3794
	 *
3795
	 * @param string $plugin The activated plugin.
3796
	 */
3797
	function throw_error_on_activate_plugin( $plugin ) {
3798
		$active_modules = self::get_active_modules();
3799
3800
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3801
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3802
			$throw = false;
3803
3804
			// Try and make sure it really was the stats plugin
3805
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3806
				if ( 'stats.php' == basename( $plugin ) ) {
3807
					$throw = true;
3808
				}
3809
			} else {
3810
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3811
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3812
					$throw = true;
3813
				}
3814
			}
3815
3816
			if ( $throw ) {
3817
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3818
			}
3819
		}
3820
	}
3821
3822
	function intercept_plugin_error_scrape_init() {
3823
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3824
	}
3825
3826
	function intercept_plugin_error_scrape( $action, $result ) {
3827
		if ( ! $result ) {
3828
			return;
3829
		}
3830
3831
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3832
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3833
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3834
			}
3835
		}
3836
	}
3837
3838
	/**
3839
	 * Register the remote file upload request handlers, if needed.
3840
	 *
3841
	 * @access public
3842
	 */
3843
	public function add_remote_request_handlers() {
3844
		// Remote file uploads are allowed only via AJAX requests.
3845
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3846
			return;
3847
		}
3848
3849
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3850
		$remote_request_actions = array(
3851
			'jetpack_upload_file',
3852
			'jetpack_update_file',
3853
		);
3854
3855
		// phpcs:ignore WordPress.Security.NonceVerification
3856
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3857
			return;
3858
		}
3859
3860
		// Require Jetpack authentication for the remote file upload AJAX requests.
3861
		if ( ! $this->connection_manager ) {
3862
			$this->connection_manager = new Connection_Manager();
3863
		}
3864
3865
		$this->connection_manager->require_jetpack_authentication();
3866
3867
		// Register the remote file upload AJAX handlers.
3868
		foreach ( $remote_request_actions as $action ) {
3869
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3870
		}
3871
	}
3872
3873
	/**
3874
	 * Handler for Jetpack remote file uploads.
3875
	 *
3876
	 * @access public
3877
	 */
3878
	public function remote_request_handlers() {
3879
		$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...
3880
3881
		switch ( current_filter() ) {
3882
			case 'wp_ajax_nopriv_jetpack_upload_file':
3883
				$response = $this->upload_handler();
3884
				break;
3885
3886
			case 'wp_ajax_nopriv_jetpack_update_file':
3887
				$response = $this->upload_handler( true );
3888
				break;
3889
			default:
3890
				$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...
3891
				break;
3892
		}
3893
3894
		if ( ! $response ) {
3895
			$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...
3896
		}
3897
3898
		if ( is_wp_error( $response ) ) {
3899
			$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...
3900
			$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...
3901
			$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...
3902
3903
			if ( ! is_int( $status_code ) ) {
3904
				$status_code = 400;
3905
			}
3906
3907
			status_header( $status_code );
3908
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3909
		}
3910
3911
		status_header( 200 );
3912
		if ( true === $response ) {
3913
			exit;
3914
		}
3915
3916
		die( json_encode( (object) $response ) );
3917
	}
3918
3919
	/**
3920
	 * Uploads a file gotten from the global $_FILES.
3921
	 * If `$update_media_item` is true and `post_id` is defined
3922
	 * the attachment file of the media item (gotten through of the post_id)
3923
	 * will be updated instead of add a new one.
3924
	 *
3925
	 * @param  boolean $update_media_item - update media attachment
3926
	 * @return array - An array describing the uploadind files process
3927
	 */
3928
	function upload_handler( $update_media_item = false ) {
3929
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3930
			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...
3931
		}
3932
3933
		$user = wp_authenticate( '', '' );
3934
		if ( ! $user || is_wp_error( $user ) ) {
3935
			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...
3936
		}
3937
3938
		wp_set_current_user( $user->ID );
3939
3940
		if ( ! current_user_can( 'upload_files' ) ) {
3941
			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 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...
3942
		}
3943
3944
		if ( empty( $_FILES ) ) {
3945
			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...
3946
		}
3947
3948
		foreach ( array_keys( $_FILES ) as $files_key ) {
3949
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3950
				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...
3951
			}
3952
		}
3953
3954
		$media_keys = array_keys( $_FILES['media'] );
3955
3956
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3957
		if ( ! $token || is_wp_error( $token ) ) {
3958
			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...
3959
		}
3960
3961
		$uploaded_files = array();
3962
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3963
		unset( $GLOBALS['post'] );
3964
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3965
			$file = array();
3966
			foreach ( $media_keys as $media_key ) {
3967
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3968
			}
3969
3970
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3971
3972
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3973
			if ( $hmac_provided !== $hmac_file ) {
3974
				$uploaded_files[ $index ] = (object) array(
3975
					'error'             => 'invalid_hmac',
3976
					'error_description' => 'The corresponding HMAC for this file does not match',
3977
				);
3978
				continue;
3979
			}
3980
3981
			$_FILES['.jetpack.upload.'] = $file;
3982
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3983
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3984
				$post_id = 0;
3985
			}
3986
3987
			if ( $update_media_item ) {
3988
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3989
					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...
3990
				}
3991
3992
				$media_array = $_FILES['media'];
3993
3994
				$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...
3995
				$file_array['type']     = $media_array['type'][0];
3996
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3997
				$file_array['error']    = $media_array['error'][0];
3998
				$file_array['size']     = $media_array['size'][0];
3999
4000
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
4001
4002
				if ( is_wp_error( $edited_media_item ) ) {
4003
					return $edited_media_item;
4004
				}
4005
4006
				$response = (object) array(
4007
					'id'   => (string) $post_id,
4008
					'file' => (string) $edited_media_item->post_title,
4009
					'url'  => (string) wp_get_attachment_url( $post_id ),
4010
					'type' => (string) $edited_media_item->post_mime_type,
4011
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
4012
				);
4013
4014
				return (array) array( $response );
4015
			}
4016
4017
			$attachment_id = media_handle_upload(
4018
				'.jetpack.upload.',
4019
				$post_id,
4020
				array(),
4021
				array(
4022
					'action' => 'jetpack_upload_file',
4023
				)
4024
			);
4025
4026
			if ( ! $attachment_id ) {
4027
				$uploaded_files[ $index ] = (object) array(
4028
					'error'             => 'unknown',
4029
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
4030
				);
4031
			} elseif ( is_wp_error( $attachment_id ) ) {
4032
				$uploaded_files[ $index ] = (object) array(
4033
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
4034
					'error_description' => $attachment_id->get_error_message(),
4035
				);
4036
			} else {
4037
				$attachment               = get_post( $attachment_id );
4038
				$uploaded_files[ $index ] = (object) array(
4039
					'id'   => (string) $attachment_id,
4040
					'file' => $attachment->post_title,
4041
					'url'  => wp_get_attachment_url( $attachment_id ),
4042
					'type' => $attachment->post_mime_type,
4043
					'meta' => wp_get_attachment_metadata( $attachment_id ),
4044
				);
4045
				// Zip files uploads are not supported unless they are done for installation purposed
4046
				// lets delete them in case something goes wrong in this whole process
4047
				if ( 'application/zip' === $attachment->post_mime_type ) {
4048
					// Schedule a cleanup for 2 hours from now in case of failed install.
4049
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
4050
				}
4051
			}
4052
		}
4053
		if ( ! is_null( $global_post ) ) {
4054
			$GLOBALS['post'] = $global_post;
4055
		}
4056
4057
		return $uploaded_files;
4058
	}
4059
4060
	/**
4061
	 * Add help to the Jetpack page
4062
	 *
4063
	 * @since Jetpack (1.2.3)
4064
	 * @return false if not the Jetpack page
4065
	 */
4066
	function admin_help() {
4067
		$current_screen = get_current_screen();
4068
4069
		// Overview
4070
		$current_screen->add_help_tab(
4071
			array(
4072
				'id'      => 'home',
4073
				'title'   => __( 'Home', 'jetpack' ),
4074
				'content' =>
4075
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4076
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4077
					'<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>',
4078
			)
4079
		);
4080
4081
		// Screen Content
4082
		if ( current_user_can( 'manage_options' ) ) {
4083
			$current_screen->add_help_tab(
4084
				array(
4085
					'id'      => 'settings',
4086
					'title'   => __( 'Settings', 'jetpack' ),
4087
					'content' =>
4088
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4089
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4090
						'<ol>' .
4091
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4092
							'<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>' .
4093
						'</ol>' .
4094
						'<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>',
4095
				)
4096
			);
4097
		}
4098
4099
		// Help Sidebar
4100
		$support_url = Redirect::get_url( 'jetpack-support' );
4101
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4102
		$current_screen->set_help_sidebar(
4103
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4104
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4105
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4106
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4107
		);
4108
	}
4109
4110
	function admin_menu_css() {
4111
		wp_enqueue_style( 'jetpack-icons' );
4112
	}
4113
4114
	function admin_menu_order() {
4115
		return true;
4116
	}
4117
4118
	function jetpack_menu_order( $menu_order ) {
4119
		$jp_menu_order = array();
4120
4121
		foreach ( $menu_order as $index => $item ) {
4122
			if ( $item != 'jetpack' ) {
4123
				$jp_menu_order[] = $item;
4124
			}
4125
4126
			if ( $index == 0 ) {
4127
				$jp_menu_order[] = 'jetpack';
4128
			}
4129
		}
4130
4131
		return $jp_menu_order;
4132
	}
4133
4134
	function admin_banner_styles() {
4135
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4136
4137 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4138
			wp_register_style(
4139
				'jetpack-dops-style',
4140
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4141
				array(),
4142
				JETPACK__VERSION
4143
			);
4144
		}
4145
4146
		wp_enqueue_style(
4147
			'jetpack',
4148
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4149
			array( 'jetpack-dops-style' ),
4150
			JETPACK__VERSION . '-20121016'
4151
		);
4152
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4153
		wp_style_add_data( 'jetpack', 'suffix', $min );
4154
	}
4155
4156
	function plugin_action_links( $actions ) {
4157
4158
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4159
4160
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
4161
			return array_merge(
4162
				$jetpack_home,
4163
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4164
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4165
				$actions
4166
			);
4167
		}
4168
4169
		return array_merge( $jetpack_home, $actions );
4170
	}
4171
4172
	/**
4173
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4174
	 *
4175
	 * @param string $hook The current admin page.
4176
	 *
4177
	 * @return void
4178
	 */
4179
	public function deactivate_dialog( $hook ) {
4180
		if (
4181
			'plugins.php' === $hook
4182
			&& self::is_connection_ready()
4183
		) {
4184
4185
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4186
4187
			if ( count( $active_plugins_using_connection ) > 1 ) {
4188
4189
				add_thickbox();
4190
4191
				// Register jp-tracks-functions dependency.
4192
				Tracking::register_tracks_functions_scripts();
4193
4194
				wp_enqueue_script(
4195
					'jetpack-deactivate-dialog-js',
4196
					Assets::get_file_url_for_environment(
4197
						'_inc/build/jetpack-deactivate-dialog.min.js',
4198
						'_inc/jetpack-deactivate-dialog.js'
4199
					),
4200
					array( 'jquery', 'jp-tracks-functions' ),
4201
					JETPACK__VERSION,
4202
					true
4203
				);
4204
4205
				wp_localize_script(
4206
					'jetpack-deactivate-dialog-js',
4207
					'deactivate_dialog',
4208
					array(
4209
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4210
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4211
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4212
					)
4213
				);
4214
4215
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4216
4217
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4218
			}
4219
		}
4220
	}
4221
4222
	/**
4223
	 * Outputs the content of the deactivation modal
4224
	 *
4225
	 * @return void
4226
	 */
4227
	public function deactivate_dialog_content() {
4228
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4229
		unset( $active_plugins_using_connection['jetpack'] );
4230
		$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 4228 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...
4231
	}
4232
4233
	/**
4234
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4235
	 *
4236
	 * @param string $login_url The wp-login URL.
4237
	 * @param string $redirect  URL to redirect users after logging in.
4238
	 * @since Jetpack 8.4
4239
	 * @return string
4240
	 */
4241
	public function login_url( $login_url, $redirect ) {
4242
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4243
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4244
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4245
		}
4246
		return $login_url;
4247
	}
4248
4249
	/**
4250
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4251
	 *
4252
	 * @since Jetpack 8.4
4253
	 */
4254
	public function login_init() {
4255
		// phpcs:ignore WordPress.Security.NonceVerification
4256
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4257
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4258
			wp_safe_redirect(
4259
				add_query_arg(
4260
					array(
4261
						'forceInstall' => 1,
4262
						'url'          => rawurlencode( get_site_url() ),
4263
					),
4264
					// @todo provide way to go to specific calypso env.
4265
					self::get_calypso_host() . 'jetpack/connect'
4266
				)
4267
			);
4268
			exit;
4269
		}
4270
	}
4271
4272
	/*
4273
	 * Registration flow:
4274
	 * 1 - ::admin_page_load() action=register
4275
	 * 2 - ::try_registration()
4276
	 * 3 - ::register()
4277
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4278
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4279
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4280
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4281
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4282
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4283
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4284
	 *       jetpack_id, jetpack_secret, jetpack_public
4285
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4286
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4287
	 * 5 - user logs in with WP.com account
4288
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4289
	 *		- Manager::authorize()
4290
	 *		- Manager::get_token()
4291
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4292
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4293
	 *			- which responds with access_token, token_type, scope
4294
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4295
	 *		- Jetpack::activate_default_modules()
4296
	 *     		- Deactivates deprecated plugins
4297
	 *     		- Activates all default modules
4298
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4299
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4300
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4301
	 *     Done!
4302
	 */
4303
4304
	/**
4305
	 * Handles the page load events for the Jetpack admin page
4306
	 */
4307
	function admin_page_load() {
4308
		$error = false;
4309
4310
		// Make sure we have the right body class to hook stylings for subpages off of.
4311
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4312
4313
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4314
			// Should only be used in intermediate redirects to preserve state across redirects
4315
			self::restate();
4316
		}
4317
4318
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4319
			// @todo: Add validation against a known allowed list.
4320
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4321
			// User clicked in the iframe to link their accounts
4322
			if ( ! self::connection()->is_user_connected() ) {
4323
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4324
4325
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4326
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4327
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4328
4329
				if ( isset( $_GET['notes_iframe'] ) ) {
4330
					$connect_url .= '&notes_iframe';
4331
				}
4332
				wp_redirect( $connect_url );
4333
				exit;
4334
			} else {
4335
				if ( ! isset( $_GET['calypso_env'] ) ) {
4336
					self::state( 'message', 'already_authorized' );
4337
					wp_safe_redirect( self::admin_url() );
4338
					exit;
4339
				} else {
4340
					$connect_url  = $this->build_connect_url( true, false, $from );
4341
					$connect_url .= '&already_authorized=true';
4342
					wp_redirect( $connect_url );
4343
					exit;
4344
				}
4345
			}
4346
		}
4347
4348
		if ( isset( $_GET['action'] ) ) {
4349
			switch ( $_GET['action'] ) {
4350
				case 'authorize_redirect':
4351
					self::log( 'authorize_redirect' );
4352
4353
					add_filter(
4354
						'allowed_redirect_hosts',
4355
						function ( $domains ) {
4356
							$domains[] = 'jetpack.com';
4357
							$domains[] = 'jetpack.wordpress.com';
4358
							$domains[] = 'wordpress.com';
4359
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4360
							return array_unique( $domains );
4361
						}
4362
					);
4363
4364
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4365
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4366
4367
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4368
						// The destination URL is missing or invalid, nothing to do here.
4369
						exit;
4370
					}
4371
4372
					if ( static::connection()->is_connected() && static::connection()->is_user_connected() ) {
4373
						// The user is either already connected, or finished the connection process.
4374
						wp_safe_redirect( $dest_url );
4375
						exit;
4376
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4377
						// The user decided not to proceed with setting up the connection.
4378
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4379
						exit;
4380
					}
4381
4382
					$redirect_url = self::admin_url(
4383
						array(
4384
							'page'     => 'jetpack',
4385
							'action'   => 'authorize_redirect',
4386
							'dest_url' => rawurlencode( $dest_url ),
4387
							'done'     => '1',
4388
						)
4389
					);
4390
4391
					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...
4392
					exit;
4393
				case 'authorize':
4394
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4395
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4396
					exit;
4397
				case 'register':
4398
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4399
						$error = 'cheatin';
4400
						break;
4401
					}
4402
					check_admin_referer( 'jetpack-register' );
4403
					self::log( 'register' );
4404
					self::maybe_set_version_option();
4405
					$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4406
					if ( $from ) {
4407
						static::connection()->add_register_request_param( 'from', (string) $from );
4408
					}
4409
					$registered = static::connection()->try_registration();
4410
					if ( is_wp_error( $registered ) ) {
4411
						$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...
4412
						self::state( 'error', $error );
4413
						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...
4414
4415
						/**
4416
						 * Jetpack registration Error.
4417
						 *
4418
						 * @since 7.5.0
4419
						 *
4420
						 * @param string|int $error The error code.
4421
						 * @param \WP_Error $registered The error object.
4422
						 */
4423
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4424
						break;
4425
					}
4426
4427
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4428
4429
					/**
4430
					 * Jetpack registration Success.
4431
					 *
4432
					 * @since 7.5.0
4433
					 *
4434
					 * @param string $from 'from' GET parameter;
4435
					 */
4436
					do_action( 'jetpack_connection_register_success', $from );
4437
4438
					$url = $this->build_connect_url( true, $redirect, $from );
4439
4440
					if ( ! empty( $_GET['onboarding'] ) ) {
4441
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4442
					}
4443
4444
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4445
						$url = add_query_arg( 'auth_approved', 'true', $url );
4446
					}
4447
4448
					wp_redirect( $url );
4449
					exit;
4450
				case 'activate':
4451
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4452
						$error = 'cheatin';
4453
						break;
4454
					}
4455
4456
					$module = stripslashes( $_GET['module'] );
4457
					check_admin_referer( "jetpack_activate-$module" );
4458
					self::log( 'activate', $module );
4459
					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...
4460
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4461
					}
4462
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4463
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4464
					exit;
4465
				case 'activate_default_modules':
4466
					check_admin_referer( 'activate_default_modules' );
4467
					self::log( 'activate_default_modules' );
4468
					self::restate();
4469
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4470
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4471
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4472
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4473
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4474
					exit;
4475 View Code Duplication
				case 'disconnect':
4476
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4477
						$error = 'cheatin';
4478
						break;
4479
					}
4480
4481
					check_admin_referer( 'jetpack-disconnect' );
4482
					self::log( 'disconnect' );
4483
					self::disconnect();
4484
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4485
					exit;
4486 View Code Duplication
				case 'reconnect':
4487
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4488
						$error = 'cheatin';
4489
						break;
4490
					}
4491
4492
					check_admin_referer( 'jetpack-reconnect' );
4493
					self::log( 'reconnect' );
4494
					self::disconnect();
4495
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4496
					exit;
4497 View Code Duplication
				case 'deactivate':
4498
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4499
						$error = 'cheatin';
4500
						break;
4501
					}
4502
4503
					$modules = stripslashes( $_GET['module'] );
4504
					check_admin_referer( "jetpack_deactivate-$modules" );
4505
					foreach ( explode( ',', $modules ) as $module ) {
4506
						self::log( 'deactivate', $module );
4507
						self::deactivate_module( $module );
4508
						self::state( 'message', 'module_deactivated' );
4509
					}
4510
					self::state( 'module', $modules );
4511
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4512
					exit;
4513
				case 'unlink':
4514
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4515
					check_admin_referer( 'jetpack-unlink' );
4516
					self::log( 'unlink' );
4517
					$this->connection_manager->disconnect_user();
4518
					self::state( 'message', 'unlinked' );
4519
					if ( 'sub-unlink' == $redirect ) {
4520
						wp_safe_redirect( admin_url() );
4521
					} else {
4522
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4523
					}
4524
					exit;
4525
				case 'onboard':
4526
					if ( ! current_user_can( 'manage_options' ) ) {
4527
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4528
					} else {
4529
						self::create_onboarding_token();
4530
						$url = $this->build_connect_url( true );
4531
4532
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4533
							$url = add_query_arg( 'onboarding', $token, $url );
4534
						}
4535
4536
						$calypso_env = $this->get_calypso_env();
4537
						if ( ! empty( $calypso_env ) ) {
4538
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4539
						}
4540
4541
						wp_redirect( $url );
4542
						exit;
4543
					}
4544
					exit;
4545
				default:
4546
					/**
4547
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4548
					 *
4549
					 * @since 2.6.0
4550
					 *
4551
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4552
					 */
4553
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4554
			}
4555
		}
4556
4557
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4558
			self::activate_new_modules( true );
4559
		}
4560
4561
		$message_code = self::state( 'message' );
4562
		if ( self::state( 'optin-manage' ) ) {
4563
			$activated_manage = $message_code;
4564
			$message_code     = 'jetpack-manage';
4565
		}
4566
4567
		switch ( $message_code ) {
4568
			case 'jetpack-manage':
4569
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4570
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4571
				$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>';
4572
				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...
4573
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4574
				}
4575
				break;
4576
4577
		}
4578
4579
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4580
4581
		if ( ! empty( $deactivated_plugins ) ) {
4582
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4583
			$deactivated_titles  = array();
4584
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4585
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4586
					continue;
4587
				}
4588
4589
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4590
			}
4591
4592
			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...
4593
				if ( $this->message ) {
4594
					$this->message .= "<br /><br />\n";
4595
				}
4596
4597
				$this->message .= wp_sprintf(
4598
					_n(
4599
						'Jetpack contains the most recent version of the old %l plugin.',
4600
						'Jetpack contains the most recent versions of the old %l plugins.',
4601
						count( $deactivated_titles ),
4602
						'jetpack'
4603
					),
4604
					$deactivated_titles
4605
				);
4606
4607
				$this->message .= "<br />\n";
4608
4609
				$this->message .= _n(
4610
					'The old version has been deactivated and can be removed from your site.',
4611
					'The old versions have been deactivated and can be removed from your site.',
4612
					count( $deactivated_titles ),
4613
					'jetpack'
4614
				);
4615
			}
4616
		}
4617
4618
		$this->privacy_checks = self::state( 'privacy_checks' );
4619
4620
		if ( $this->message || $this->error || $this->privacy_checks ) {
4621
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4622
		}
4623
4624
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4625
	}
4626
4627
	function admin_notices() {
4628
4629
		if ( $this->error ) {
4630
			?>
4631
<div id="message" class="jetpack-message jetpack-err">
4632
	<div class="squeezer">
4633
		<h2>
4634
			<?php
4635
			echo wp_kses(
4636
				$this->error,
4637
				array(
4638
					'a'      => array( 'href' => array() ),
4639
					'small'  => true,
4640
					'code'   => true,
4641
					'strong' => true,
4642
					'br'     => true,
4643
					'b'      => true,
4644
				)
4645
			);
4646
			?>
4647
			</h2>
4648
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4649
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4650
<?php	endif; ?>
4651
	</div>
4652
</div>
4653
			<?php
4654
		}
4655
4656
		if ( $this->message ) {
4657
			?>
4658
<div id="message" class="jetpack-message">
4659
	<div class="squeezer">
4660
		<h2>
4661
			<?php
4662
			echo wp_kses(
4663
				$this->message,
4664
				array(
4665
					'strong' => array(),
4666
					'a'      => array( 'href' => true ),
4667
					'br'     => true,
4668
				)
4669
			);
4670
			?>
4671
			</h2>
4672
	</div>
4673
</div>
4674
			<?php
4675
		}
4676
4677
		if ( $this->privacy_checks ) :
4678
			$module_names = $module_slugs = array();
4679
4680
			$privacy_checks = explode( ',', $this->privacy_checks );
4681
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4682
			foreach ( $privacy_checks as $module_slug ) {
4683
				$module = self::get_module( $module_slug );
4684
				if ( ! $module ) {
4685
					continue;
4686
				}
4687
4688
				$module_slugs[] = $module_slug;
4689
				$module_names[] = "<strong>{$module['name']}</strong>";
4690
			}
4691
4692
			$module_slugs = join( ',', $module_slugs );
4693
			?>
4694
<div id="message" class="jetpack-message jetpack-err">
4695
	<div class="squeezer">
4696
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4697
		<p>
4698
			<?php
4699
			echo wp_kses(
4700
				wptexturize(
4701
					wp_sprintf(
4702
						_nx(
4703
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4704
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4705
							count( $privacy_checks ),
4706
							'%l = list of Jetpack module/feature names',
4707
							'jetpack'
4708
						),
4709
						$module_names
4710
					)
4711
				),
4712
				array( 'strong' => true )
4713
			);
4714
4715
			echo "\n<br />\n";
4716
4717
			echo wp_kses(
4718
				sprintf(
4719
					_nx(
4720
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4721
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4722
						count( $privacy_checks ),
4723
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4724
						'jetpack'
4725
					),
4726
					wp_nonce_url(
4727
						self::admin_url(
4728
							array(
4729
								'page'   => 'jetpack',
4730
								'action' => 'deactivate',
4731
								'module' => urlencode( $module_slugs ),
4732
							)
4733
						),
4734
						"jetpack_deactivate-$module_slugs"
4735
					),
4736
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4737
				),
4738
				array(
4739
					'a' => array(
4740
						'href'  => true,
4741
						'title' => true,
4742
					),
4743
				)
4744
			);
4745
			?>
4746
		</p>
4747
	</div>
4748
</div>
4749
			<?php
4750
endif;
4751
	}
4752
4753
	/**
4754
	 * We can't always respond to a signed XML-RPC request with a
4755
	 * helpful error message. In some circumstances, doing so could
4756
	 * leak information.
4757
	 *
4758
	 * Instead, track that the error occurred via a Jetpack_Option,
4759
	 * and send that data back in the heartbeat.
4760
	 * All this does is increment a number, but it's enough to find
4761
	 * trends.
4762
	 *
4763
	 * @param WP_Error $xmlrpc_error The error produced during
4764
	 *                               signature validation.
4765
	 */
4766
	function track_xmlrpc_error( $xmlrpc_error ) {
4767
		$code = is_wp_error( $xmlrpc_error )
4768
			? $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...
4769
			: 'should-not-happen';
4770
4771
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4772
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4773
			// No need to update the option if we already have
4774
			// this code stored.
4775
			return;
4776
		}
4777
		$xmlrpc_errors[ $code ] = true;
4778
4779
		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...
4780
	}
4781
4782
	/**
4783
	 * Initialize the jetpack stats instance only when needed
4784
	 *
4785
	 * @return void
4786
	 */
4787
	private function initialize_stats() {
4788
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4789
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4790
		}
4791
	}
4792
4793
	/**
4794
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4795
	 */
4796
	function stat( $group, $detail ) {
4797
		$this->initialize_stats();
4798
		$this->a8c_mc_stats_instance->add( $group, $detail );
4799
4800
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4801
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4802
	}
4803
4804
	/**
4805
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4806
	 */
4807
	function do_stats( $method = '' ) {
4808
		$this->initialize_stats();
4809
		if ( 'server_side' === $method ) {
4810
			$this->a8c_mc_stats_instance->do_server_side_stats();
4811
		} else {
4812
			$this->a8c_mc_stats_instance->do_stats();
4813
		}
4814
4815
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4816
		$this->stats = array();
4817
	}
4818
4819
	/**
4820
	 * Runs stats code for a one-off, server-side.
4821
	 *
4822
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4823
	 *
4824
	 * @return bool If it worked.
4825
	 */
4826
	static function do_server_side_stat( $args ) {
4827
		$url                   = self::build_stats_url( $args );
4828
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4829
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4830
	}
4831
4832
	/**
4833
	 * Builds the stats url.
4834
	 *
4835
	 * @param $args array|string The arguments to append to the URL.
4836
	 *
4837
	 * @return string The URL to be pinged.
4838
	 */
4839
	static function build_stats_url( $args ) {
4840
4841
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4842
		return $a8c_mc_stats_instance->build_stats_url( $args );
4843
4844
	}
4845
4846
	/**
4847
	 * Builds a URL to the Jetpack connection auth page
4848
	 *
4849
	 * @since 3.9.5
4850
	 *
4851
	 * @param bool        $raw If true, URL will not be escaped.
4852
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4853
	 *                              If string, will be a custom redirect.
4854
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4855
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4856
	 *
4857
	 * @return string Connect URL
4858
	 */
4859
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4860
		$site_id    = Jetpack_Options::get_option( 'id' );
4861
		$blog_token = ( new Tokens() )->get_access_token();
4862
4863
		if ( $register || ! $blog_token || ! $site_id ) {
4864
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4865
4866
			if ( ! empty( $redirect ) ) {
4867
				$url = add_query_arg(
4868
					'redirect',
4869
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4870
					$url
4871
				);
4872
			}
4873
4874
			if ( is_network_admin() ) {
4875
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4876
			}
4877
4878
			$calypso_env = self::get_calypso_env();
4879
4880
			if ( ! empty( $calypso_env ) ) {
4881
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4882
			}
4883
		} else {
4884
4885
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4886
			// because otherwise this logic can get us in to a loop.
4887
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4888
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4889
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4890
4891
				$response = Client::wpcom_json_api_request_as_blog(
4892
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4893
					'1.1'
4894
				);
4895
4896
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4897
4898
					// Generating a register URL instead to refresh the existing token
4899
					return $this->build_connect_url( $raw, $redirect, $from, true );
4900
				}
4901
			}
4902
4903
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4859 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...
4904
		}
4905
4906
		if ( $from ) {
4907
			$url = add_query_arg( 'from', $from, $url );
4908
		}
4909
4910
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4911
		/**
4912
		 * Filter the URL used when connecting a user to a WordPress.com account.
4913
		 *
4914
		 * @since 8.1.0
4915
		 *
4916
		 * @param string $url Connection URL.
4917
		 * @param bool   $raw If true, URL will not be escaped.
4918
		 */
4919
		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...
4920
	}
4921
4922
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4923
4924
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4925
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4926
4927
		if ( $iframe ) {
4928
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4929
		}
4930
4931
		$c8n = self::connection();
4932
		$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...
4933
4934
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4935
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4936
4937
		if ( $iframe ) {
4938
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4939
		}
4940
4941
		/**
4942
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4943
		 *
4944
		 * @since 8.9.0
4945
		 *
4946
		 * @param string $url Connection URL.
4947
		 */
4948
		return apply_filters( 'jetpack_build_authorize_url', $url );
4949
	}
4950
4951
	/**
4952
	 * Filters the connection URL parameter array.
4953
	 *
4954
	 * @param array $args default URL parameters used by the package.
4955
	 * @return array the modified URL arguments array.
4956
	 */
4957
	public static function filter_connect_request_body( $args ) {
4958
		if (
4959
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4960
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4961
		) {
4962
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4963
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4964
				? $gp_locale->slug
4965
				: '';
4966
		}
4967
4968
		$tracking        = new Tracking();
4969
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4970
4971
		$args = array_merge(
4972
			$args,
4973
			array(
4974
				'_ui' => $tracks_identity['_ui'],
4975
				'_ut' => $tracks_identity['_ut'],
4976
			)
4977
		);
4978
4979
		$calypso_env = self::get_calypso_env();
4980
4981
		if ( ! empty( $calypso_env ) ) {
4982
			$args['calypso_env'] = $calypso_env;
4983
		}
4984
4985
		return $args;
4986
	}
4987
4988
	/**
4989
	 * Filters the URL that will process the connection data. It can be different from the URL
4990
	 * that we send the user to after everything is done.
4991
	 *
4992
	 * @param String $processing_url the default redirect URL used by the package.
4993
	 * @return String the modified URL.
4994
	 *
4995
	 * @deprecated since Jetpack 9.5.0
4996
	 */
4997
	public static function filter_connect_processing_url( $processing_url ) {
4998
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4999
5000
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
5001
		return $processing_url;
5002
	}
5003
5004
	/**
5005
	 * Filters the redirection URL that is used for connect requests. The redirect
5006
	 * URL should return the user back to the Jetpack console.
5007
	 *
5008
	 * @param String $redirect the default redirect URL used by the package.
5009
	 * @return String the modified URL.
5010
	 */
5011
	public static function filter_connect_redirect_url( $redirect ) {
5012
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
5013
		$redirect           = $redirect
5014
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
5015
			: $jetpack_admin_page;
5016
5017
		if ( isset( $_REQUEST['is_multisite'] ) ) {
5018
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
5019
		}
5020
5021
		return $redirect;
5022
	}
5023
5024
	/**
5025
	 * This action fires at the beginning of the Manager::authorize method.
5026
	 */
5027
	public static function authorize_starting() {
5028
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
5029
		// Checking if site has been active/connected previously before recording unique connection.
5030
		if ( ! $jetpack_unique_connection ) {
5031
			// jetpack_unique_connection option has never been set.
5032
			$jetpack_unique_connection = array(
5033
				'connected'    => 0,
5034
				'disconnected' => 0,
5035
				'version'      => '3.6.1',
5036
			);
5037
5038
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
5039
5040
			// Track unique connection.
5041
			$jetpack = self::init();
5042
5043
			$jetpack->stat( 'connections', 'unique-connection' );
5044
			$jetpack->do_stats( 'server_side' );
5045
		}
5046
5047
		// Increment number of times connected.
5048
		$jetpack_unique_connection['connected'] += 1;
5049
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5050
	}
5051
5052
	/**
5053
	 * This action fires when the site is registered (connected at a site level).
5054
	 */
5055
	public function handle_unique_registrations_stats() {
5056
		$jetpack_unique_registrations = Jetpack_Options::get_option( 'unique_registrations' );
5057
		// Checking if site has been registered previously before recording unique connection.
5058
		if ( ! $jetpack_unique_registrations ) {
5059
5060
			$jetpack_unique_registrations = 0;
5061
5062
			$this->stat( 'connections', 'unique-registrations' );
5063
			$this->do_stats( 'server_side' );
5064
		}
5065
5066
		// Increment number of times connected.
5067
		$jetpack_unique_registrations ++;
5068
		Jetpack_Options::update_option( 'unique_registrations', $jetpack_unique_registrations );
5069
	}
5070
5071
	/**
5072
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5073
	 * linked.
5074
	 */
5075
	public static function authorize_ending_linked() {
5076
		// Don't activate anything since we are just connecting a user.
5077
		self::state( 'message', 'linked' );
5078
	}
5079
5080
	/**
5081
	 * This action fires at the end of the Manager::authorize method when the master user is
5082
	 * authorized.
5083
	 *
5084
	 * @param array $data The request data.
5085
	 */
5086
	public static function authorize_ending_authorized( $data ) {
5087
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5088
		self::invalidate_onboarding_token();
5089
5090
		// If redirect_uri is SSO, ensure SSO module is enabled.
5091
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5092
5093
		/** This filter is documented in class.jetpack-cli.php */
5094
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5095
5096
		$activate_sso = (
5097
			isset( $redirect_options['action'] ) &&
5098
			'jetpack-sso' === $redirect_options['action'] &&
5099
			$jetpack_start_enable_sso
5100
		);
5101
5102
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5103
5104
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5105
	}
5106
5107
	/**
5108
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5109
	 */
5110
	public static function activate_default_modules_on_site_register() {
5111
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5112
		if ( $active_modules ) {
5113
			self::delete_active_modules();
5114
5115
			// 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.
5116
			self::activate_default_modules( 999, 1, $active_modules, false );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
5117
		} else {
5118
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5119
			self::activate_default_modules( false, false, array(), false, null, null, false );
5120
		}
5121
5122
		// Since this is a fresh connection, be sure to clear out IDC options.
5123
		Jetpack_IDC::clear_all_idc_options();
5124
	}
5125
5126
	/**
5127
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5128
	 * reconnect process is completed.
5129
	 * Note that this currently only happens when we don't need the user to re-authorize
5130
	 * their WP.com account, eg in cases where we are restoring a connection with
5131
	 * unhealthy blog token.
5132
	 */
5133
	public static function reconnection_completed() {
5134
		self::state( 'message', 'reconnection_completed' );
5135
	}
5136
5137
	/**
5138
	 * Get our assumed site creation date.
5139
	 * Calculated based on the earlier date of either:
5140
	 * - Earliest admin user registration date.
5141
	 * - Earliest date of post of any post type.
5142
	 *
5143
	 * @since 7.2.0
5144
	 * @deprecated since 7.8.0
5145
	 *
5146
	 * @return string Assumed site creation date and time.
5147
	 */
5148
	public static function get_assumed_site_creation_date() {
5149
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5150
		return self::connection()->get_assumed_site_creation_date();
5151
	}
5152
5153 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5154
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5155
5156
		if ( $activation_source_name ) {
5157
			$args['_as'] = urlencode( $activation_source_name );
5158
		}
5159
5160
		if ( $activation_source_keyword ) {
5161
			$args['_ak'] = urlencode( $activation_source_keyword );
5162
		}
5163
	}
5164
5165
	function build_reconnect_url( $raw = false ) {
5166
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5167
		return $raw ? $url : esc_url( $url );
5168
	}
5169
5170
	public static function admin_url( $args = null ) {
5171
		$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...
5172
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5173
		return $url;
5174
	}
5175
5176
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5177
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5178
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5179
	}
5180
5181
	function dismiss_jetpack_notice() {
5182
5183
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5184
			return;
5185
		}
5186
5187
		switch ( $_GET['jetpack-notice'] ) {
5188
			case 'dismiss':
5189
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5190
5191
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5192
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5193
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5194
				}
5195
				break;
5196
		}
5197
	}
5198
5199
	public static function sort_modules( $a, $b ) {
5200
		if ( $a['sort'] == $b['sort'] ) {
5201
			return 0;
5202
		}
5203
5204
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5205
	}
5206
5207
	function ajax_recheck_ssl() {
5208
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5209
		$result = self::permit_ssl( true );
5210
		wp_send_json(
5211
			array(
5212
				'enabled' => $result,
5213
				'message' => get_transient( 'jetpack_https_test_message' ),
5214
			)
5215
		);
5216
	}
5217
5218
	/* Client API */
5219
5220
	/**
5221
	 * Returns the requested Jetpack API URL
5222
	 *
5223
	 * @deprecated since 7.7
5224
	 * @return string
5225
	 */
5226
	public static function api_url( $relative_url ) {
5227
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5228
		$connection = self::connection();
5229
		return $connection->api_url( $relative_url );
5230
	}
5231
5232
	/**
5233
	 * @deprecated 8.0
5234
	 *
5235
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5236
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5237
	 */
5238
	public static function fix_url_for_bad_hosts( $url ) {
5239
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5240
		return $url;
5241
	}
5242
5243
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5244
		// Default to a blog token.
5245
		$token_type = 'blog';
5246
5247
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5248
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5249
			if ( ! empty( $_GET['onboarding'] ) ) {
5250
				$jpo = $_GET;
5251
			} else {
5252
				$jpo = json_decode( $request_data, true );
5253
			}
5254
5255
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5256
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5257
5258
			if (
5259
				isset( $jpo_user )
5260
				&& isset( $jpo_token )
5261
				&& is_email( $jpo_user )
5262
				&& ctype_alnum( $jpo_token )
5263
				&& isset( $_GET['rest_route'] )
5264
				&& self::validate_onboarding_token_action(
5265
					$jpo_token,
5266
					$_GET['rest_route']
5267
				)
5268
			) {
5269
				$jp_user = get_user_by( 'email', $jpo_user );
5270
				if ( is_a( $jp_user, 'WP_User' ) ) {
5271
					wp_set_current_user( $jp_user->ID );
5272
					$user_can = is_multisite()
5273
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5274
						: current_user_can( 'manage_options' );
5275
					if ( $user_can ) {
5276
						$token_type              = 'user';
5277
						$token->external_user_id = $jp_user->ID;
5278
					}
5279
				}
5280
			}
5281
5282
			$token_data['type']    = $token_type;
5283
			$token_data['user_id'] = $token->external_user_id;
5284
		}
5285
5286
		return $token_data;
5287
	}
5288
5289
	/**
5290
	 * Create a random secret for validating onboarding payload
5291
	 *
5292
	 * @return string Secret token
5293
	 */
5294
	public static function create_onboarding_token() {
5295
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5296
			$token = wp_generate_password( 32, false );
5297
			Jetpack_Options::update_option( 'onboarding', $token );
5298
		}
5299
5300
		return $token;
5301
	}
5302
5303
	/**
5304
	 * Remove the onboarding token
5305
	 *
5306
	 * @return bool True on success, false on failure
5307
	 */
5308
	public static function invalidate_onboarding_token() {
5309
		return Jetpack_Options::delete_option( 'onboarding' );
5310
	}
5311
5312
	/**
5313
	 * Validate an onboarding token for a specific action
5314
	 *
5315
	 * @return boolean True if token/action pair is accepted, false if not
5316
	 */
5317
	public static function validate_onboarding_token_action( $token, $action ) {
5318
		// Compare tokens, bail if tokens do not match
5319
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5320
			return false;
5321
		}
5322
5323
		// List of valid actions we can take
5324
		$valid_actions = array(
5325
			'/jetpack/v4/settings',
5326
		);
5327
5328
		// Only allow valid actions.
5329
		if ( ! in_array( $action, $valid_actions ) ) {
5330
			return false;
5331
		}
5332
5333
		return true;
5334
	}
5335
5336
	/**
5337
	 * Checks to see if the URL is using SSL to connect with Jetpack
5338
	 *
5339
	 * @since 2.3.3
5340
	 * @return boolean
5341
	 */
5342
	public static function permit_ssl( $force_recheck = false ) {
5343
		// Do some fancy tests to see if ssl is being supported
5344
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5345
			$message = '';
5346
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5347
				$ssl = 0;
5348
			} else {
5349
				$ssl = 1;
5350
5351
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5352
					$ssl     = 0;
5353
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5354
				} else {
5355
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5356
					if ( is_wp_error( $response ) ) {
5357
						$ssl     = 0;
5358
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5359
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5360
						$ssl     = 0;
5361
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5362
					}
5363
				}
5364
			}
5365
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5366
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5367
		}
5368
5369
		return (bool) $ssl;
5370
	}
5371
5372
	/*
5373
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5374
	 */
5375
	public function alert_auto_ssl_fail() {
5376
		if ( ! current_user_can( 'manage_options' ) ) {
5377
			return;
5378
		}
5379
5380
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5381
		?>
5382
5383
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5384
			<div class="jp-banner__content">
5385
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5386
				<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>
5387
				<p>
5388
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5389
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5390
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5391
				</p>
5392
				<p>
5393
					<?php
5394
					printf(
5395
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5396
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5397
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5398
					);
5399
					?>
5400
				</p>
5401
			</div>
5402
		</div>
5403
		<style>
5404
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5405
		</style>
5406
		<script type="text/javascript">
5407
			jQuery( document ).ready( function( $ ) {
5408
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5409
					var $this = $( this );
5410
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5411
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5412
					e.preventDefault();
5413
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5414
					$.post( ajaxurl, data )
5415
					  .done( function( response ) {
5416
						  if ( response.enabled ) {
5417
							  $( '#jetpack-ssl-warning' ).hide();
5418
						  } else {
5419
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5420
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5421
						  }
5422
					  }.bind( $this ) );
5423
				} );
5424
			} );
5425
		</script>
5426
5427
		<?php
5428
	}
5429
5430
	/**
5431
	 * Returns the Jetpack XML-RPC API
5432
	 *
5433
	 * @deprecated 8.0 Use Connection_Manager instead.
5434
	 * @return string
5435
	 */
5436
	public static function xmlrpc_api_url() {
5437
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5438
		return self::connection()->xmlrpc_api_url();
5439
	}
5440
5441
	/**
5442
	 * Returns the connection manager object.
5443
	 *
5444
	 * @return Automattic\Jetpack\Connection\Manager
5445
	 */
5446
	public static function connection() {
5447
		$jetpack = static::init();
5448
5449
		// If the connection manager hasn't been instantiated, do that now.
5450
		if ( ! $jetpack->connection_manager ) {
5451
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5452
		}
5453
5454
		return $jetpack->connection_manager;
5455
	}
5456
5457
	/**
5458
	 * Creates two secret tokens and the end of life timestamp for them.
5459
	 *
5460
	 * Note these tokens are unique per call, NOT static per site for connecting.
5461
	 *
5462
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5463
	 *
5464
	 * @since 2.6
5465
	 * @param String  $action  The action name.
5466
	 * @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...
5467
	 * @param Integer $exp     Expiration time in seconds.
5468
	 * @return array
5469
	 */
5470
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5471
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5472
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5473
	}
5474
5475
	public static function get_secrets( $action, $user_id ) {
5476
		$secrets = ( new Secrets() )->get( $action, $user_id );
5477
5478
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5479
			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...
5480
		}
5481
5482
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5483
			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...
5484
		}
5485
5486
		return $secrets;
5487
	}
5488
5489
	/**
5490
	 * Builds the timeout limit for queries talking with the wpcom servers.
5491
	 *
5492
	 * Based on local php max_execution_time in php.ini
5493
	 *
5494
	 * @since 2.6
5495
	 * @return int
5496
	 * @deprecated
5497
	 **/
5498
	public function get_remote_query_timeout_limit() {
5499
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5500
		return self::get_max_execution_time();
5501
	}
5502
5503
	/**
5504
	 * Builds the timeout limit for queries talking with the wpcom servers.
5505
	 *
5506
	 * Based on local php max_execution_time in php.ini
5507
	 *
5508
	 * @since 5.4
5509
	 * @return int
5510
	 **/
5511
	public static function get_max_execution_time() {
5512
		$timeout = (int) ini_get( 'max_execution_time' );
5513
5514
		// Ensure exec time set in php.ini
5515
		if ( ! $timeout ) {
5516
			$timeout = 30;
5517
		}
5518
		return $timeout;
5519
	}
5520
5521
	/**
5522
	 * Sets a minimum request timeout, and returns the current timeout
5523
	 *
5524
	 * @since 5.4
5525
	 **/
5526 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5527
		$timeout = self::get_max_execution_time();
5528
		if ( $timeout < $min_timeout ) {
5529
			$timeout = $min_timeout;
5530
			set_time_limit( $timeout );
5531
		}
5532
		return $timeout;
5533
	}
5534
5535
	/**
5536
	 * Takes the response from the Jetpack register new site endpoint and
5537
	 * verifies it worked properly.
5538
	 *
5539
	 * @since 2.6
5540
	 * @deprecated since 7.7.0
5541
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5542
	 **/
5543
	public function validate_remote_register_response() {
5544
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5545
	}
5546
5547
	/**
5548
	 * @deprecated since Jetpack 9.7.0
5549
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
5550
	 *
5551
	 * @return bool|WP_Error
5552
	 */
5553
	public static function register() {
5554
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
5555
		return static::connection()->try_registration( false );
5556
	}
5557
5558
	/**
5559
	 * Filters the registration request body to include tracking properties.
5560
	 *
5561
	 * @deprecated since Jetpack 9.7.0
5562
	 * @see Automattic\Jetpack\Connection\Utils::filter_register_request_body()
5563
	 *
5564
	 * @param array $properties
5565
	 * @return array amended properties.
5566
	 */
5567
	public static function filter_register_request_body( $properties ) {
5568
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Utils::filter_register_request_body' );
5569
		return Connection_Utils::filter_register_request_body( $properties );
5570
	}
5571
5572
	/**
5573
	 * Filters the token request body to include tracking properties.
5574
	 *
5575
	 * @param array $properties
5576
	 * @return array amended properties.
5577
	 */
5578 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5579
		$tracking        = new Tracking();
5580
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5581
5582
		return array_merge(
5583
			$properties,
5584
			array(
5585
				'_ui' => $tracks_identity['_ui'],
5586
				'_ut' => $tracks_identity['_ut'],
5587
			)
5588
		);
5589
	}
5590
5591
	/**
5592
	 * If the db version is showing something other that what we've got now, bump it to current.
5593
	 *
5594
	 * @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...
5595
	 */
5596
	public static function maybe_set_version_option() {
5597
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5598
		if ( JETPACK__VERSION != $version ) {
5599
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5600
5601
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5602
				/** This action is documented in class.jetpack.php */
5603
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5604
			}
5605
5606
			return true;
5607
		}
5608
		return false;
5609
	}
5610
5611
	/* Client Server API */
5612
5613
	/**
5614
	 * Loads the Jetpack XML-RPC client.
5615
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5616
	 *
5617
	 * @deprecated since 7.7.0
5618
	 */
5619
	public static function load_xml_rpc_client() {
5620
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5621
	}
5622
5623
	/**
5624
	 * Resets the saved authentication state in between testing requests.
5625
	 *
5626
	 * @deprecated since 8.9.0
5627
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5628
	 */
5629
	public function reset_saved_auth_state() {
5630
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5631
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5632
	}
5633
5634
	/**
5635
	 * Verifies the signature of the current request.
5636
	 *
5637
	 * @deprecated since 7.7.0
5638
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5639
	 *
5640
	 * @return false|array
5641
	 */
5642
	public function verify_xml_rpc_signature() {
5643
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5644
		return self::connection()->verify_xml_rpc_signature();
5645
	}
5646
5647
	/**
5648
	 * Verifies the signature of the current request.
5649
	 *
5650
	 * This function has side effects and should not be used. Instead,
5651
	 * use the memoized version `->verify_xml_rpc_signature()`.
5652
	 *
5653
	 * @deprecated since 7.7.0
5654
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5655
	 * @internal
5656
	 */
5657
	private function internal_verify_xml_rpc_signature() {
5658
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5659
	}
5660
5661
	/**
5662
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5663
	 *
5664
	 * @deprecated since 7.7.0
5665
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5666
	 *
5667
	 * @param \WP_User|mixed $user     User object if authenticated.
5668
	 * @param string         $username Username.
5669
	 * @param string         $password Password string.
5670
	 * @return \WP_User|mixed Authenticated user or error.
5671
	 */
5672 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5673
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5674
5675
		if ( ! $this->connection_manager ) {
5676
			$this->connection_manager = new Connection_Manager();
5677
		}
5678
5679
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5680
	}
5681
5682
	/**
5683
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5684
	 * Uses the existing XMLRPC request signing implementation.
5685
	 *
5686
	 * @deprecated since 8.9.0
5687
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5688
	 */
5689
	function wp_rest_authenticate( $user ) {
5690
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5691
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5692
	}
5693
5694
	/**
5695
	 * Report authentication status to the WP REST API.
5696
	 *
5697
	 * @deprecated since 8.9.0
5698
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5699
	 *
5700
	 * @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...
5701
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5702
	 */
5703
	public function wp_rest_authentication_errors( $value ) {
5704
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5705
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5706
	}
5707
5708
	/**
5709
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5710
	 * Capture it here so we can verify the signature later.
5711
	 *
5712
	 * @deprecated since 7.7.0
5713
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5714
	 *
5715
	 * @param array $methods XMLRPC methods.
5716
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5717
	 */
5718 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5719
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5720
5721
		if ( ! $this->connection_manager ) {
5722
			$this->connection_manager = new Connection_Manager();
5723
		}
5724
5725
		return $this->connection_manager->xmlrpc_methods( $methods );
5726
	}
5727
5728
	/**
5729
	 * Register additional public XMLRPC methods.
5730
	 *
5731
	 * @deprecated since 7.7.0
5732
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5733
	 *
5734
	 * @param array $methods Public XMLRPC methods.
5735
	 * @return array Public XMLRPC methods, with the getOptions one.
5736
	 */
5737 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5738
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5739
5740
		if ( ! $this->connection_manager ) {
5741
			$this->connection_manager = new Connection_Manager();
5742
		}
5743
5744
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5745
	}
5746
5747
	/**
5748
	 * Handles a getOptions XMLRPC method call.
5749
	 *
5750
	 * @deprecated since 7.7.0
5751
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5752
	 *
5753
	 * @param array $args method call arguments.
5754
	 * @return array an amended XMLRPC server options array.
5755
	 */
5756 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5757
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5758
5759
		if ( ! $this->connection_manager ) {
5760
			$this->connection_manager = new Connection_Manager();
5761
		}
5762
5763
		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...
5764
	}
5765
5766
	/**
5767
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5768
	 *
5769
	 * @deprecated since 7.7.0
5770
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5771
	 *
5772
	 * @param array $options Standard Core options.
5773
	 * @return array Amended options.
5774
	 */
5775 View Code Duplication
	public function xmlrpc_options( $options ) {
5776
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5777
5778
		if ( ! $this->connection_manager ) {
5779
			$this->connection_manager = new Connection_Manager();
5780
		}
5781
5782
		return $this->connection_manager->xmlrpc_options( $options );
5783
	}
5784
5785
	/**
5786
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5787
	 * SET: state( $key, $value );
5788
	 * GET: $value = state( $key );
5789
	 *
5790
	 * @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...
5791
	 * @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...
5792
	 * @param bool   $restate private
5793
	 */
5794
	public static function state( $key = null, $value = null, $restate = false ) {
5795
		static $state = array();
5796
		static $path, $domain;
5797
		if ( ! isset( $path ) ) {
5798
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5799
			$admin_url = self::admin_url();
5800
			$bits      = wp_parse_url( $admin_url );
5801
5802
			if ( is_array( $bits ) ) {
5803
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5804
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5805
			} else {
5806
				$path = $domain = null;
5807
			}
5808
		}
5809
5810
		// Extract state from cookies and delete cookies
5811
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5812
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5813
			unset( $_COOKIE['jetpackState'] );
5814
			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...
5815
				if ( strlen( $v ) ) {
5816
					$state[ $k ] = $v;
5817
				}
5818
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5819
			}
5820
		}
5821
5822
		if ( $restate ) {
5823
			foreach ( $state as $k => $v ) {
5824
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5825
			}
5826
			return;
5827
		}
5828
5829
		// Get a state variable.
5830
		if ( isset( $key ) && ! isset( $value ) ) {
5831
			if ( array_key_exists( $key, $state ) ) {
5832
				return $state[ $key ];
5833
			}
5834
			return null;
5835
		}
5836
5837
		// Set a state variable.
5838
		if ( isset( $key ) && isset( $value ) ) {
5839
			if ( is_array( $value ) && isset( $value[0] ) ) {
5840
				$value = $value[0];
5841
			}
5842
			$state[ $key ] = $value;
5843
			if ( ! headers_sent() ) {
5844
				if ( self::should_set_cookie( $key ) ) {
5845
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5846
				}
5847
			}
5848
		}
5849
	}
5850
5851
	public static function restate() {
5852
		self::state( null, null, true );
5853
	}
5854
5855
	/**
5856
	 * Determines whether the jetpackState[$key] value should be added to the
5857
	 * cookie.
5858
	 *
5859
	 * @param string $key The state key.
5860
	 *
5861
	 * @return boolean Whether the value should be added to the cookie.
5862
	 */
5863
	public static function should_set_cookie( $key ) {
5864
		global $current_screen;
5865
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5866
5867
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5868
			return false;
5869
		}
5870
5871
		return true;
5872
	}
5873
5874
	public static function check_privacy( $file ) {
5875
		static $is_site_publicly_accessible = null;
5876
5877
		if ( is_null( $is_site_publicly_accessible ) ) {
5878
			$is_site_publicly_accessible = false;
5879
5880
			$rpc = new Jetpack_IXR_Client();
5881
5882
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5883
			if ( $success ) {
5884
				$response = $rpc->getResponse();
5885
				if ( $response ) {
5886
					$is_site_publicly_accessible = true;
5887
				}
5888
			}
5889
5890
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5891
		}
5892
5893
		if ( $is_site_publicly_accessible ) {
5894
			return;
5895
		}
5896
5897
		$module_slug = self::get_module_slug( $file );
5898
5899
		$privacy_checks = self::state( 'privacy_checks' );
5900
		if ( ! $privacy_checks ) {
5901
			$privacy_checks = $module_slug;
5902
		} else {
5903
			$privacy_checks .= ",$module_slug";
5904
		}
5905
5906
		self::state( 'privacy_checks', $privacy_checks );
5907
	}
5908
5909
	/**
5910
	 * Helper method for multicall XMLRPC.
5911
	 *
5912
	 * @deprecated since 8.9.0
5913
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5914
	 *
5915
	 * @param ...$args Args for the async_call.
5916
	 */
5917
	public static function xmlrpc_async_call( ...$args ) {
5918
5919
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5920
5921
		global $blog_id;
5922
		static $clients = array();
5923
5924
		$client_blog_id = is_multisite() ? $blog_id : 0;
5925
5926
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5927
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5928
			if ( function_exists( 'ignore_user_abort' ) ) {
5929
				ignore_user_abort( true );
5930
			}
5931
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5932
		}
5933
5934
		if ( ! empty( $args[0] ) ) {
5935
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5936
		} elseif ( is_multisite() ) {
5937
			foreach ( $clients as $client_blog_id => $client ) {
5938
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5939
					continue;
5940
				}
5941
5942
				$switch_success = switch_to_blog( $client_blog_id, true );
5943
				if ( ! $switch_success ) {
5944
					continue;
5945
				}
5946
5947
				flush();
5948
				$client->query();
5949
5950
				restore_current_blog();
5951
			}
5952
		} else {
5953
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5954
				flush();
5955
				$clients[0]->query();
5956
			}
5957
		}
5958
	}
5959
5960
	/**
5961
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5962
	 *
5963
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5964
	 *
5965
	 * @param string $url WordPress.com static resource URL.
5966
	 */
5967
	public static function staticize_subdomain( $url ) {
5968
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5969
		return Assets::staticize_subdomain( $url );
5970
	}
5971
5972
	/* JSON API Authorization */
5973
5974
	/**
5975
	 * Handles the login action for Authorizing the JSON API
5976
	 */
5977
	function login_form_json_api_authorization() {
5978
		$this->verify_json_api_authorization_request();
5979
5980
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5981
5982
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5983
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5984
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5985
	}
5986
5987
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5988
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5989
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5990
			return $url;
5991
		}
5992
5993
		$parsed_url = wp_parse_url( $url );
5994
		$url        = strtok( $url, '?' );
5995
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5996
		if ( ! empty( $parsed_url['query'] ) ) {
5997
			$url .= "&{$parsed_url['query']}";
5998
		}
5999
6000
		return $url;
6001
	}
6002
6003
	// Make sure the POSTed request is handled by the same action
6004
	function preserve_action_in_login_form_for_json_api_authorization() {
6005
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6006
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6007
	}
6008
6009
	// If someone logs in to approve API access, store the Access Code in usermeta
6010
	function store_json_api_authorization_token( $user_login, $user ) {
6011
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6012
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6013
		$token = wp_generate_password( 32, false );
6014
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6015
	}
6016
6017
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
6018
	function allow_wpcom_public_api_domain( $domains ) {
6019
		$domains[] = 'public-api.wordpress.com';
6020
		return $domains;
6021
	}
6022
6023
	static function is_redirect_encoded( $redirect_url ) {
6024
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
6025
	}
6026
6027
	// Add all wordpress.com environments to the safe redirect allowed list.
6028
	function allow_wpcom_environments( $domains ) {
6029
		$domains[] = 'wordpress.com';
6030
		$domains[] = 'wpcalypso.wordpress.com';
6031
		$domains[] = 'horizon.wordpress.com';
6032
		$domains[] = 'calypso.localhost';
6033
		return $domains;
6034
	}
6035
6036
	// Add the Access Code details to the public-api.wordpress.com redirect
6037
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6038
		return add_query_arg(
6039
			urlencode_deep(
6040
				array(
6041
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6042
					'jetpack-user-id' => (int) $user->ID,
6043
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6044
				)
6045
			),
6046
			$redirect_to
6047
		);
6048
	}
6049
6050
	/**
6051
	 * Verifies the request by checking the signature
6052
	 *
6053
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6054
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6055
	 *
6056
	 * @param null|array $environment
6057
	 */
6058
	function verify_json_api_authorization_request( $environment = null ) {
6059
		$environment = is_null( $environment )
6060
			? $_REQUEST
6061
			: $environment;
6062
6063
		//phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
6064
		list( $env_token, $env_version, $env_user_id ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $env_version is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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

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

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

Loading history...
7544
			return false;
7545
		}
7546
		return true;
7547
	}
7548
7549
	/**
7550
	 * Checks if a Jetpack site is both active and not in offline mode.
7551
	 *
7552
	 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
7553
	 *
7554
	 * @since 8.8.0
7555
	 *
7556
	 * @return bool True if Jetpack is active and not in offline mode.
7557
	 */
7558
	public static function is_active_and_not_offline_mode() {
7559
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
7560
			return false;
7561
		}
7562
		return true;
7563
	}
7564
7565
	/**
7566
	 * Returns the list of products that we have available for purchase.
7567
	 */
7568
	public static function get_products_for_purchase() {
7569
		$products = array();
7570
		if ( ! is_multisite() ) {
7571
			$products[] = array(
7572
				'key'               => 'backup',
7573
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7574
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7575
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7576
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7577
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7578
				'options'           => array(
7579
					array(
7580
						'type'        => 'daily',
7581
						'slug'        => 'jetpack-backup-daily',
7582
						'key'         => 'jetpack_backup_daily',
7583
						'name'        => __( 'Daily Backups', 'jetpack' ),
7584
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7585
					),
7586
					array(
7587
						'type'        => 'realtime',
7588
						'slug'        => 'jetpack-backup-realtime',
7589
						'key'         => 'jetpack_backup_realtime',
7590
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7591
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7592
					),
7593
				),
7594
				'default_option'    => 'realtime',
7595
				'show_promotion'    => true,
7596
				'discount_percent'  => 70,
7597
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7598
			);
7599
7600
			$products[] = array(
7601
				'key'               => 'scan',
7602
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7603
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7604
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7605
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7606
				'show_promotion'    => true,
7607
				'discount_percent'  => 30,
7608
				'options'           => array(
7609
					array(
7610
						'type' => 'scan',
7611
						'slug' => 'jetpack-scan',
7612
						'key'  => 'jetpack_scan',
7613
						'name' => __( 'Daily Scan', 'jetpack' ),
7614
					),
7615
				),
7616
				'default_option'    => 'scan',
7617
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7618
			);
7619
		}
7620
7621
		$products[] = array(
7622
			'key'               => 'search',
7623
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7624
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7625
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7626
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7627
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7628
			'options'           => array(
7629
				array(
7630
					'type' => 'search',
7631
					'slug' => 'jetpack-search',
7632
					'key'  => 'jetpack_search',
7633
					'name' => __( 'Search', 'jetpack' ),
7634
				),
7635
			),
7636
			'tears'             => array(),
7637
			'default_option'    => 'search',
7638
			'show_promotion'    => false,
7639
			'included_in_plans' => array( 'search-plan' ),
7640
		);
7641
7642
		$products[] = array(
7643
			'key'               => 'anti-spam',
7644
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7645
			'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' ),
7646
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7647
			'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' ),
7648
			'options'           => array(
7649
				array(
7650
					'type' => 'anti-spam',
7651
					'slug' => 'jetpack-anti-spam',
7652
					'key'  => 'jetpack_anti_spam',
7653
					'name' => __( 'Anti-Spam', 'jetpack' ),
7654
				),
7655
			),
7656
			'default_option'    => 'anti-spam',
7657
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7658
		);
7659
7660
		return $products;
7661
	}
7662
}
7663