Completed
Push — update/wpcom-block-editor-shor... ( 9897fe...f43ed6 )
by Jeremy
148:26 queued 138:20
created

Jetpack::get_available_modules()   D

Complexity

Conditions 19
Paths 21

Size

Total Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

Loading history...
3873
		}
3874
3875
		if ( empty( $_FILES ) ) {
3876
			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...
3877
		}
3878
3879
		foreach ( array_keys( $_FILES ) as $files_key ) {
3880
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3881
				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...
3882
			}
3883
		}
3884
3885
		$media_keys = array_keys( $_FILES['media'] );
3886
3887
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3888
		if ( ! $token || is_wp_error( $token ) ) {
3889
			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...
3890
		}
3891
3892
		$uploaded_files = array();
3893
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3894
		unset( $GLOBALS['post'] );
3895
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3896
			$file = array();
3897
			foreach ( $media_keys as $media_key ) {
3898
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3899
			}
3900
3901
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3902
3903
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3904
			if ( $hmac_provided !== $hmac_file ) {
3905
				$uploaded_files[ $index ] = (object) array(
3906
					'error'             => 'invalid_hmac',
3907
					'error_description' => 'The corresponding HMAC for this file does not match',
3908
				);
3909
				continue;
3910
			}
3911
3912
			$_FILES['.jetpack.upload.'] = $file;
3913
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3914
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3915
				$post_id = 0;
3916
			}
3917
3918
			if ( $update_media_item ) {
3919
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3920
					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...
3921
				}
3922
3923
				$media_array = $_FILES['media'];
3924
3925
				$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...
3926
				$file_array['type']     = $media_array['type'][0];
3927
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3928
				$file_array['error']    = $media_array['error'][0];
3929
				$file_array['size']     = $media_array['size'][0];
3930
3931
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3932
3933
				if ( is_wp_error( $edited_media_item ) ) {
3934
					return $edited_media_item;
3935
				}
3936
3937
				$response = (object) array(
3938
					'id'   => (string) $post_id,
3939
					'file' => (string) $edited_media_item->post_title,
3940
					'url'  => (string) wp_get_attachment_url( $post_id ),
3941
					'type' => (string) $edited_media_item->post_mime_type,
3942
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3943
				);
3944
3945
				return (array) array( $response );
3946
			}
3947
3948
			$attachment_id = media_handle_upload(
3949
				'.jetpack.upload.',
3950
				$post_id,
3951
				array(),
3952
				array(
3953
					'action' => 'jetpack_upload_file',
3954
				)
3955
			);
3956
3957
			if ( ! $attachment_id ) {
3958
				$uploaded_files[ $index ] = (object) array(
3959
					'error'             => 'unknown',
3960
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3961
				);
3962
			} elseif ( is_wp_error( $attachment_id ) ) {
3963
				$uploaded_files[ $index ] = (object) array(
3964
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3965
					'error_description' => $attachment_id->get_error_message(),
3966
				);
3967
			} else {
3968
				$attachment               = get_post( $attachment_id );
3969
				$uploaded_files[ $index ] = (object) array(
3970
					'id'   => (string) $attachment_id,
3971
					'file' => $attachment->post_title,
3972
					'url'  => wp_get_attachment_url( $attachment_id ),
3973
					'type' => $attachment->post_mime_type,
3974
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3975
				);
3976
				// Zip files uploads are not supported unless they are done for installation purposed
3977
				// lets delete them in case something goes wrong in this whole process
3978
				if ( 'application/zip' === $attachment->post_mime_type ) {
3979
					// Schedule a cleanup for 2 hours from now in case of failed install.
3980
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3981
				}
3982
			}
3983
		}
3984
		if ( ! is_null( $global_post ) ) {
3985
			$GLOBALS['post'] = $global_post;
3986
		}
3987
3988
		return $uploaded_files;
3989
	}
3990
3991
	/**
3992
	 * Add help to the Jetpack page
3993
	 *
3994
	 * @since Jetpack (1.2.3)
3995
	 * @return false if not the Jetpack page
3996
	 */
3997
	function admin_help() {
3998
		$current_screen = get_current_screen();
3999
4000
		// Overview
4001
		$current_screen->add_help_tab(
4002
			array(
4003
				'id'      => 'home',
4004
				'title'   => __( 'Home', 'jetpack' ),
4005
				'content' =>
4006
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4007
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4008
					'<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>',
4009
			)
4010
		);
4011
4012
		// Screen Content
4013
		if ( current_user_can( 'manage_options' ) ) {
4014
			$current_screen->add_help_tab(
4015
				array(
4016
					'id'      => 'settings',
4017
					'title'   => __( 'Settings', 'jetpack' ),
4018
					'content' =>
4019
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4020
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4021
						'<ol>' .
4022
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4023
							'<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>' .
4024
						'</ol>' .
4025
						'<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>',
4026
				)
4027
			);
4028
		}
4029
4030
		// Help Sidebar
4031
		$support_url = Redirect::get_url( 'jetpack-support' );
4032
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4033
		$current_screen->set_help_sidebar(
4034
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4035
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4036
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4037
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4038
		);
4039
	}
4040
4041
	function admin_menu_css() {
4042
		wp_enqueue_style( 'jetpack-icons' );
4043
	}
4044
4045
	function admin_menu_order() {
4046
		return true;
4047
	}
4048
4049
	function jetpack_menu_order( $menu_order ) {
4050
		$jp_menu_order = array();
4051
4052
		foreach ( $menu_order as $index => $item ) {
4053
			if ( $item != 'jetpack' ) {
4054
				$jp_menu_order[] = $item;
4055
			}
4056
4057
			if ( $index == 0 ) {
4058
				$jp_menu_order[] = 'jetpack';
4059
			}
4060
		}
4061
4062
		return $jp_menu_order;
4063
	}
4064
4065
	function admin_banner_styles() {
4066
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4067
4068
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4069
			wp_register_style(
4070
				'jetpack-dops-style',
4071
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4072
				array(),
4073
				JETPACK__VERSION
4074
			);
4075
		}
4076
4077
		wp_enqueue_style(
4078
			'jetpack',
4079
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4080
			array( 'jetpack-dops-style' ),
4081
			JETPACK__VERSION . '-20121016'
4082
		);
4083
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4084
		wp_style_add_data( 'jetpack', 'suffix', $min );
4085
	}
4086
4087
	function plugin_action_links( $actions ) {
4088
4089
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4090
4091
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
4092
			return array_merge(
4093
				$jetpack_home,
4094
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4095
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4096
				$actions
4097
			);
4098
		}
4099
4100
		return array_merge( $jetpack_home, $actions );
4101
	}
4102
4103
	/**
4104
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4105
	 *
4106
	 * @param string $hook The current admin page.
4107
	 *
4108
	 * @return void
4109
	 */
4110
	public function deactivate_dialog( $hook ) {
4111
		if (
4112
			'plugins.php' === $hook
4113
			&& self::is_active()
4114
		) {
4115
4116
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4117
4118
			if ( count( $active_plugins_using_connection ) > 1 ) {
4119
4120
				add_thickbox();
4121
4122
				wp_register_script(
4123
					'jp-tracks',
4124
					'//stats.wp.com/w.js',
4125
					array(),
4126
					gmdate( 'YW' ),
4127
					true
4128
				);
4129
4130
				wp_register_script(
4131
					'jp-tracks-functions',
4132
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4133
					array( 'jp-tracks' ),
4134
					JETPACK__VERSION,
4135
					false
4136
				);
4137
4138
				wp_enqueue_script(
4139
					'jetpack-deactivate-dialog-js',
4140
					Assets::get_file_url_for_environment(
4141
						'_inc/build/jetpack-deactivate-dialog.min.js',
4142
						'_inc/jetpack-deactivate-dialog.js'
4143
					),
4144
					array( 'jquery', 'jp-tracks-functions' ),
4145
					JETPACK__VERSION,
4146
					true
4147
				);
4148
4149
				wp_localize_script(
4150
					'jetpack-deactivate-dialog-js',
4151
					'deactivate_dialog',
4152
					array(
4153
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4154
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4155
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4156
					)
4157
				);
4158
4159
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4160
4161
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4162
			}
4163
		}
4164
	}
4165
4166
	/**
4167
	 * Outputs the content of the deactivation modal
4168
	 *
4169
	 * @return void
4170
	 */
4171
	public function deactivate_dialog_content() {
4172
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4173
		unset( $active_plugins_using_connection['jetpack'] );
4174
		$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 4172 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...
4175
	}
4176
4177
	/**
4178
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4179
	 *
4180
	 * @param string $login_url The wp-login URL.
4181
	 * @param string $redirect  URL to redirect users after logging in.
4182
	 * @since Jetpack 8.4
4183
	 * @return string
4184
	 */
4185
	public function login_url( $login_url, $redirect ) {
4186
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4187
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4188
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4189
		}
4190
		return $login_url;
4191
	}
4192
4193
	/**
4194
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4195
	 *
4196
	 * @since Jetpack 8.4
4197
	 */
4198
	public function login_init() {
4199
		// phpcs:ignore WordPress.Security.NonceVerification
4200
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4201
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4202
			wp_safe_redirect(
4203
				add_query_arg(
4204
					array(
4205
						'forceInstall' => 1,
4206
						'url'          => rawurlencode( get_site_url() ),
4207
					),
4208
					// @todo provide way to go to specific calypso env.
4209
					self::get_calypso_host() . 'jetpack/connect'
4210
				)
4211
			);
4212
			exit;
4213
		}
4214
	}
4215
4216
	/*
4217
	 * Registration flow:
4218
	 * 1 - ::admin_page_load() action=register
4219
	 * 2 - ::try_registration()
4220
	 * 3 - ::register()
4221
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4222
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4223
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4224
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4225
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4226
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4227
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4228
	 *       jetpack_id, jetpack_secret, jetpack_public
4229
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4230
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4231
	 * 5 - user logs in with WP.com account
4232
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4233
	 *		- Manager::authorize()
4234
	 *		- Manager::get_token()
4235
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4236
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4237
	 *			- which responds with access_token, token_type, scope
4238
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4239
	 *		- Jetpack::activate_default_modules()
4240
	 *     		- Deactivates deprecated plugins
4241
	 *     		- Activates all default modules
4242
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4243
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4244
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4245
	 *     Done!
4246
	 */
4247
4248
	/**
4249
	 * Handles the page load events for the Jetpack admin page
4250
	 */
4251
	function admin_page_load() {
4252
		$error = false;
4253
4254
		// Make sure we have the right body class to hook stylings for subpages off of.
4255
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4256
4257
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4258
			// Should only be used in intermediate redirects to preserve state across redirects
4259
			self::restate();
4260
		}
4261
4262
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4263
			// @todo: Add validation against a known allowed list.
4264
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4265
			// User clicked in the iframe to link their accounts
4266
			if ( ! self::connection()->is_user_connected() ) {
4267
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4268
4269
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4270
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4271
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4272
4273
				if ( isset( $_GET['notes_iframe'] ) ) {
4274
					$connect_url .= '&notes_iframe';
4275
				}
4276
				wp_redirect( $connect_url );
4277
				exit;
4278
			} else {
4279
				if ( ! isset( $_GET['calypso_env'] ) ) {
4280
					self::state( 'message', 'already_authorized' );
4281
					wp_safe_redirect( self::admin_url() );
4282
					exit;
4283
				} else {
4284
					$connect_url  = $this->build_connect_url( true, false, $from );
4285
					$connect_url .= '&already_authorized=true';
4286
					wp_redirect( $connect_url );
4287
					exit;
4288
				}
4289
			}
4290
		}
4291
4292
		if ( isset( $_GET['action'] ) ) {
4293
			switch ( $_GET['action'] ) {
4294
				case 'authorize_redirect':
4295
					self::log( 'authorize_redirect' );
4296
4297
					add_filter(
4298
						'allowed_redirect_hosts',
4299
						function ( $domains ) {
4300
							$domains[] = 'jetpack.com';
4301
							$domains[] = 'jetpack.wordpress.com';
4302
							$domains[] = 'wordpress.com';
4303
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4304
							return array_unique( $domains );
4305
						}
4306
					);
4307
4308
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4309
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4310
4311
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4312
						// The destination URL is missing or invalid, nothing to do here.
4313
						exit;
4314
					}
4315
4316
					if ( static::is_active() && static::connection()->is_user_connected() ) {
4317
						// The user is either already connected, or finished the connection process.
4318
						wp_safe_redirect( $dest_url );
4319
						exit;
4320
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4321
						// The user decided not to proceed with setting up the connection.
4322
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4323
						exit;
4324
					}
4325
4326
					$redirect_url = self::admin_url(
4327
						array(
4328
							'page'     => 'jetpack',
4329
							'action'   => 'authorize_redirect',
4330
							'dest_url' => rawurlencode( $dest_url ),
4331
							'done'     => '1',
4332
						)
4333
					);
4334
4335
					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...
4336
					exit;
4337
				case 'authorize':
4338
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4339
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4340
					exit;
4341
				case 'register':
4342
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4343
						$error = 'cheatin';
4344
						break;
4345
					}
4346
					check_admin_referer( 'jetpack-register' );
4347
					self::log( 'register' );
4348
					self::maybe_set_version_option();
4349
					$registered = self::try_registration();
4350
					if ( is_wp_error( $registered ) ) {
4351
						$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...
4352
						self::state( 'error', $error );
4353
						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...
4354
4355
						/**
4356
						 * Jetpack registration Error.
4357
						 *
4358
						 * @since 7.5.0
4359
						 *
4360
						 * @param string|int $error The error code.
4361
						 * @param \WP_Error $registered The error object.
4362
						 */
4363
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4364
						break;
4365
					}
4366
4367
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4368
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4369
4370
					/**
4371
					 * Jetpack registration Success.
4372
					 *
4373
					 * @since 7.5.0
4374
					 *
4375
					 * @param string $from 'from' GET parameter;
4376
					 */
4377
					do_action( 'jetpack_connection_register_success', $from );
4378
4379
					$url = $this->build_connect_url( true, $redirect, $from );
4380
4381
					if ( ! empty( $_GET['onboarding'] ) ) {
4382
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4383
					}
4384
4385
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4386
						$url = add_query_arg( 'auth_approved', 'true', $url );
4387
					}
4388
4389
					wp_redirect( $url );
4390
					exit;
4391
				case 'activate':
4392
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4393
						$error = 'cheatin';
4394
						break;
4395
					}
4396
4397
					$module = stripslashes( $_GET['module'] );
4398
					check_admin_referer( "jetpack_activate-$module" );
4399
					self::log( 'activate', $module );
4400
					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...
4401
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4402
					}
4403
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4404
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4405
					exit;
4406
				case 'activate_default_modules':
4407
					check_admin_referer( 'activate_default_modules' );
4408
					self::log( 'activate_default_modules' );
4409
					self::restate();
4410
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4411
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4412
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4413
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4414
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4415
					exit;
4416 View Code Duplication
				case 'disconnect':
4417
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4418
						$error = 'cheatin';
4419
						break;
4420
					}
4421
4422
					check_admin_referer( 'jetpack-disconnect' );
4423
					self::log( 'disconnect' );
4424
					self::disconnect();
4425
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4426
					exit;
4427 View Code Duplication
				case 'reconnect':
4428
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4429
						$error = 'cheatin';
4430
						break;
4431
					}
4432
4433
					check_admin_referer( 'jetpack-reconnect' );
4434
					self::log( 'reconnect' );
4435
					self::disconnect();
4436
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4437
					exit;
4438 View Code Duplication
				case 'deactivate':
4439
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4440
						$error = 'cheatin';
4441
						break;
4442
					}
4443
4444
					$modules = stripslashes( $_GET['module'] );
4445
					check_admin_referer( "jetpack_deactivate-$modules" );
4446
					foreach ( explode( ',', $modules ) as $module ) {
4447
						self::log( 'deactivate', $module );
4448
						self::deactivate_module( $module );
4449
						self::state( 'message', 'module_deactivated' );
4450
					}
4451
					self::state( 'module', $modules );
4452
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4453
					exit;
4454
				case 'unlink':
4455
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4456
					check_admin_referer( 'jetpack-unlink' );
4457
					self::log( 'unlink' );
4458
					$this->connection_manager->disconnect_user();
4459
					self::state( 'message', 'unlinked' );
4460
					if ( 'sub-unlink' == $redirect ) {
4461
						wp_safe_redirect( admin_url() );
4462
					} else {
4463
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4464
					}
4465
					exit;
4466
				case 'onboard':
4467
					if ( ! current_user_can( 'manage_options' ) ) {
4468
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4469
					} else {
4470
						self::create_onboarding_token();
4471
						$url = $this->build_connect_url( true );
4472
4473
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4474
							$url = add_query_arg( 'onboarding', $token, $url );
4475
						}
4476
4477
						$calypso_env = $this->get_calypso_env();
4478
						if ( ! empty( $calypso_env ) ) {
4479
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4480
						}
4481
4482
						wp_redirect( $url );
4483
						exit;
4484
					}
4485
					exit;
4486
				default:
4487
					/**
4488
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4489
					 *
4490
					 * @since 2.6.0
4491
					 *
4492
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4493
					 */
4494
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4495
			}
4496
		}
4497
4498
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4499
			self::activate_new_modules( true );
4500
		}
4501
4502
		$message_code = self::state( 'message' );
4503
		if ( self::state( 'optin-manage' ) ) {
4504
			$activated_manage = $message_code;
4505
			$message_code     = 'jetpack-manage';
4506
		}
4507
4508
		switch ( $message_code ) {
4509
			case 'jetpack-manage':
4510
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4511
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4512
				$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>';
4513
				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...
4514
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4515
				}
4516
				break;
4517
4518
		}
4519
4520
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4521
4522
		if ( ! empty( $deactivated_plugins ) ) {
4523
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4524
			$deactivated_titles  = array();
4525
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4526
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4527
					continue;
4528
				}
4529
4530
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4531
			}
4532
4533
			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...
4534
				if ( $this->message ) {
4535
					$this->message .= "<br /><br />\n";
4536
				}
4537
4538
				$this->message .= wp_sprintf(
4539
					_n(
4540
						'Jetpack contains the most recent version of the old %l plugin.',
4541
						'Jetpack contains the most recent versions of the old %l plugins.',
4542
						count( $deactivated_titles ),
4543
						'jetpack'
4544
					),
4545
					$deactivated_titles
4546
				);
4547
4548
				$this->message .= "<br />\n";
4549
4550
				$this->message .= _n(
4551
					'The old version has been deactivated and can be removed from your site.',
4552
					'The old versions have been deactivated and can be removed from your site.',
4553
					count( $deactivated_titles ),
4554
					'jetpack'
4555
				);
4556
			}
4557
		}
4558
4559
		$this->privacy_checks = self::state( 'privacy_checks' );
4560
4561
		if ( $this->message || $this->error || $this->privacy_checks ) {
4562
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4563
		}
4564
4565
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4566
	}
4567
4568
	function admin_notices() {
4569
4570
		if ( $this->error ) {
4571
			?>
4572
<div id="message" class="jetpack-message jetpack-err">
4573
	<div class="squeezer">
4574
		<h2>
4575
			<?php
4576
			echo wp_kses(
4577
				$this->error,
4578
				array(
4579
					'a'      => array( 'href' => array() ),
4580
					'small'  => true,
4581
					'code'   => true,
4582
					'strong' => true,
4583
					'br'     => true,
4584
					'b'      => true,
4585
				)
4586
			);
4587
			?>
4588
			</h2>
4589
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4590
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4591
<?php	endif; ?>
4592
	</div>
4593
</div>
4594
			<?php
4595
		}
4596
4597
		if ( $this->message ) {
4598
			?>
4599
<div id="message" class="jetpack-message">
4600
	<div class="squeezer">
4601
		<h2>
4602
			<?php
4603
			echo wp_kses(
4604
				$this->message,
4605
				array(
4606
					'strong' => array(),
4607
					'a'      => array( 'href' => true ),
4608
					'br'     => true,
4609
				)
4610
			);
4611
			?>
4612
			</h2>
4613
	</div>
4614
</div>
4615
			<?php
4616
		}
4617
4618
		if ( $this->privacy_checks ) :
4619
			$module_names = $module_slugs = array();
4620
4621
			$privacy_checks = explode( ',', $this->privacy_checks );
4622
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4623
			foreach ( $privacy_checks as $module_slug ) {
4624
				$module = self::get_module( $module_slug );
4625
				if ( ! $module ) {
4626
					continue;
4627
				}
4628
4629
				$module_slugs[] = $module_slug;
4630
				$module_names[] = "<strong>{$module['name']}</strong>";
4631
			}
4632
4633
			$module_slugs = join( ',', $module_slugs );
4634
			?>
4635
<div id="message" class="jetpack-message jetpack-err">
4636
	<div class="squeezer">
4637
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4638
		<p>
4639
			<?php
4640
			echo wp_kses(
4641
				wptexturize(
4642
					wp_sprintf(
4643
						_nx(
4644
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4645
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4646
							count( $privacy_checks ),
4647
							'%l = list of Jetpack module/feature names',
4648
							'jetpack'
4649
						),
4650
						$module_names
4651
					)
4652
				),
4653
				array( 'strong' => true )
4654
			);
4655
4656
			echo "\n<br />\n";
4657
4658
			echo wp_kses(
4659
				sprintf(
4660
					_nx(
4661
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4662
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4663
						count( $privacy_checks ),
4664
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4665
						'jetpack'
4666
					),
4667
					wp_nonce_url(
4668
						self::admin_url(
4669
							array(
4670
								'page'   => 'jetpack',
4671
								'action' => 'deactivate',
4672
								'module' => urlencode( $module_slugs ),
4673
							)
4674
						),
4675
						"jetpack_deactivate-$module_slugs"
4676
					),
4677
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4678
				),
4679
				array(
4680
					'a' => array(
4681
						'href'  => true,
4682
						'title' => true,
4683
					),
4684
				)
4685
			);
4686
			?>
4687
		</p>
4688
	</div>
4689
</div>
4690
			<?php
4691
endif;
4692
	}
4693
4694
	/**
4695
	 * We can't always respond to a signed XML-RPC request with a
4696
	 * helpful error message. In some circumstances, doing so could
4697
	 * leak information.
4698
	 *
4699
	 * Instead, track that the error occurred via a Jetpack_Option,
4700
	 * and send that data back in the heartbeat.
4701
	 * All this does is increment a number, but it's enough to find
4702
	 * trends.
4703
	 *
4704
	 * @param WP_Error $xmlrpc_error The error produced during
4705
	 *                               signature validation.
4706
	 */
4707
	function track_xmlrpc_error( $xmlrpc_error ) {
4708
		$code = is_wp_error( $xmlrpc_error )
4709
			? $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...
4710
			: 'should-not-happen';
4711
4712
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4713
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4714
			// No need to update the option if we already have
4715
			// this code stored.
4716
			return;
4717
		}
4718
		$xmlrpc_errors[ $code ] = true;
4719
4720
		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...
4721
	}
4722
4723
	/**
4724
	 * Initialize the jetpack stats instance only when needed
4725
	 *
4726
	 * @return void
4727
	 */
4728
	private function initialize_stats() {
4729
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4730
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4731
		}
4732
	}
4733
4734
	/**
4735
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4736
	 */
4737
	function stat( $group, $detail ) {
4738
		$this->initialize_stats();
4739
		$this->a8c_mc_stats_instance->add( $group, $detail );
4740
4741
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4742
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4743
	}
4744
4745
	/**
4746
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4747
	 */
4748
	function do_stats( $method = '' ) {
4749
		$this->initialize_stats();
4750
		if ( 'server_side' === $method ) {
4751
			$this->a8c_mc_stats_instance->do_server_side_stats();
4752
		} else {
4753
			$this->a8c_mc_stats_instance->do_stats();
4754
		}
4755
4756
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4757
		$this->stats = array();
4758
	}
4759
4760
	/**
4761
	 * Runs stats code for a one-off, server-side.
4762
	 *
4763
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4764
	 *
4765
	 * @return bool If it worked.
4766
	 */
4767
	static function do_server_side_stat( $args ) {
4768
		$url                   = self::build_stats_url( $args );
4769
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4770
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4771
	}
4772
4773
	/**
4774
	 * Builds the stats url.
4775
	 *
4776
	 * @param $args array|string The arguments to append to the URL.
4777
	 *
4778
	 * @return string The URL to be pinged.
4779
	 */
4780
	static function build_stats_url( $args ) {
4781
4782
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4783
		return $a8c_mc_stats_instance->build_stats_url( $args );
4784
4785
	}
4786
4787
	/**
4788
	 * Builds a URL to the Jetpack connection auth page
4789
	 *
4790
	 * @since 3.9.5
4791
	 *
4792
	 * @param bool        $raw If true, URL will not be escaped.
4793
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4794
	 *                              If string, will be a custom redirect.
4795
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4796
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4797
	 *
4798
	 * @return string Connect URL
4799
	 */
4800
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4801
		$site_id    = Jetpack_Options::get_option( 'id' );
4802
		$blog_token = ( new Tokens() )->get_access_token();
4803
4804
		if ( $register || ! $blog_token || ! $site_id ) {
4805
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4806
4807
			if ( ! empty( $redirect ) ) {
4808
				$url = add_query_arg(
4809
					'redirect',
4810
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4811
					$url
4812
				);
4813
			}
4814
4815
			if ( is_network_admin() ) {
4816
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4817
			}
4818
4819
			$calypso_env = self::get_calypso_env();
4820
4821
			if ( ! empty( $calypso_env ) ) {
4822
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4823
			}
4824
		} else {
4825
4826
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4827
			// because otherwise this logic can get us in to a loop.
4828
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4829
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4830
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4831
4832
				$response = Client::wpcom_json_api_request_as_blog(
4833
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4834
					'1.1'
4835
				);
4836
4837
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4838
4839
					// Generating a register URL instead to refresh the existing token
4840
					return $this->build_connect_url( $raw, $redirect, $from, true );
4841
				}
4842
			}
4843
4844
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4800 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...
4845
		}
4846
4847
		if ( $from ) {
4848
			$url = add_query_arg( 'from', $from, $url );
4849
		}
4850
4851
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4852
		/**
4853
		 * Filter the URL used when connecting a user to a WordPress.com account.
4854
		 *
4855
		 * @since 8.1.0
4856
		 *
4857
		 * @param string $url Connection URL.
4858
		 * @param bool   $raw If true, URL will not be escaped.
4859
		 */
4860
		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...
4861
	}
4862
4863
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4864
4865
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4866
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4867
4868
		if ( $iframe ) {
4869
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4870
		}
4871
4872
		$c8n = self::connection();
4873
		$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...
4874
4875
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4876
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4877
4878
		if ( $iframe ) {
4879
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4880
		}
4881
4882
		/**
4883
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4884
		 *
4885
		 * @since 8.9.0
4886
		 *
4887
		 * @param string $url Connection URL.
4888
		 */
4889
		return apply_filters( 'jetpack_build_authorize_url', $url );
4890
	}
4891
4892
	/**
4893
	 * Filters the connection URL parameter array.
4894
	 *
4895
	 * @param array $args default URL parameters used by the package.
4896
	 * @return array the modified URL arguments array.
4897
	 */
4898
	public static function filter_connect_request_body( $args ) {
4899
		if (
4900
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4901
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4902
		) {
4903
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4904
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4905
				? $gp_locale->slug
4906
				: '';
4907
		}
4908
4909
		$tracking        = new Tracking();
4910
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4911
4912
		$args = array_merge(
4913
			$args,
4914
			array(
4915
				'_ui' => $tracks_identity['_ui'],
4916
				'_ut' => $tracks_identity['_ut'],
4917
			)
4918
		);
4919
4920
		$calypso_env = self::get_calypso_env();
4921
4922
		if ( ! empty( $calypso_env ) ) {
4923
			$args['calypso_env'] = $calypso_env;
4924
		}
4925
4926
		return $args;
4927
	}
4928
4929
	/**
4930
	 * Filters the URL that will process the connection data. It can be different from the URL
4931
	 * that we send the user to after everything is done.
4932
	 *
4933
	 * @param String $processing_url the default redirect URL used by the package.
4934
	 * @return String the modified URL.
4935
	 *
4936
	 * @deprecated since Jetpack 9.5.0
4937
	 */
4938
	public static function filter_connect_processing_url( $processing_url ) {
4939
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4940
4941
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4942
		return $processing_url;
4943
	}
4944
4945
	/**
4946
	 * Filters the redirection URL that is used for connect requests. The redirect
4947
	 * URL should return the user back to the Jetpack console.
4948
	 *
4949
	 * @param String $redirect the default redirect URL used by the package.
4950
	 * @return String the modified URL.
4951
	 */
4952
	public static function filter_connect_redirect_url( $redirect ) {
4953
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4954
		$redirect           = $redirect
4955
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4956
			: $jetpack_admin_page;
4957
4958
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4959
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4960
		}
4961
4962
		return $redirect;
4963
	}
4964
4965
	/**
4966
	 * This action fires at the beginning of the Manager::authorize method.
4967
	 */
4968
	public static function authorize_starting() {
4969
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4970
		// Checking if site has been active/connected previously before recording unique connection.
4971
		if ( ! $jetpack_unique_connection ) {
4972
			// jetpack_unique_connection option has never been set.
4973
			$jetpack_unique_connection = array(
4974
				'connected'    => 0,
4975
				'disconnected' => 0,
4976
				'version'      => '3.6.1',
4977
			);
4978
4979
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4980
4981
			// Track unique connection.
4982
			$jetpack = self::init();
4983
4984
			$jetpack->stat( 'connections', 'unique-connection' );
4985
			$jetpack->do_stats( 'server_side' );
4986
		}
4987
4988
		// Increment number of times connected.
4989
		$jetpack_unique_connection['connected'] += 1;
4990
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4991
	}
4992
4993
	/**
4994
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4995
	 * linked.
4996
	 */
4997
	public static function authorize_ending_linked() {
4998
		// Don't activate anything since we are just connecting a user.
4999
		self::state( 'message', 'linked' );
5000
	}
5001
5002
	/**
5003
	 * This action fires at the end of the Manager::authorize method when the master user is
5004
	 * authorized.
5005
	 *
5006
	 * @param array $data The request data.
5007
	 */
5008
	public static function authorize_ending_authorized( $data ) {
5009
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5010
		self::invalidate_onboarding_token();
5011
5012
		// If redirect_uri is SSO, ensure SSO module is enabled.
5013
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5014
5015
		/** This filter is documented in class.jetpack-cli.php */
5016
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5017
5018
		$activate_sso = (
5019
			isset( $redirect_options['action'] ) &&
5020
			'jetpack-sso' === $redirect_options['action'] &&
5021
			$jetpack_start_enable_sso
5022
		);
5023
5024
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5025
5026
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5027
	}
5028
5029
	/**
5030
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5031
	 */
5032
	public static function activate_default_modules_on_site_register() {
5033
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5034
		if ( $active_modules ) {
5035
			self::delete_active_modules();
5036
5037
			// 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.
5038
			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...
5039
		} else {
5040
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5041
			self::activate_default_modules( false, false, array(), false, null, null, false );
5042
		}
5043
5044
		// Since this is a fresh connection, be sure to clear out IDC options.
5045
		Jetpack_IDC::clear_all_idc_options();
5046
	}
5047
5048
	/**
5049
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5050
	 * reconnect process is completed.
5051
	 * Note that this currently only happens when we don't need the user to re-authorize
5052
	 * their WP.com account, eg in cases where we are restoring a connection with
5053
	 * unhealthy blog token.
5054
	 */
5055
	public static function reconnection_completed() {
5056
		self::state( 'message', 'reconnection_completed' );
5057
	}
5058
5059
	/**
5060
	 * Get our assumed site creation date.
5061
	 * Calculated based on the earlier date of either:
5062
	 * - Earliest admin user registration date.
5063
	 * - Earliest date of post of any post type.
5064
	 *
5065
	 * @since 7.2.0
5066
	 * @deprecated since 7.8.0
5067
	 *
5068
	 * @return string Assumed site creation date and time.
5069
	 */
5070
	public static function get_assumed_site_creation_date() {
5071
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5072
		return self::connection()->get_assumed_site_creation_date();
5073
	}
5074
5075 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5076
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5077
5078
		if ( $activation_source_name ) {
5079
			$args['_as'] = urlencode( $activation_source_name );
5080
		}
5081
5082
		if ( $activation_source_keyword ) {
5083
			$args['_ak'] = urlencode( $activation_source_keyword );
5084
		}
5085
	}
5086
5087
	function build_reconnect_url( $raw = false ) {
5088
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5089
		return $raw ? $url : esc_url( $url );
5090
	}
5091
5092
	public static function admin_url( $args = null ) {
5093
		$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...
5094
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5095
		return $url;
5096
	}
5097
5098
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5099
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5100
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5101
	}
5102
5103
	function dismiss_jetpack_notice() {
5104
5105
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5106
			return;
5107
		}
5108
5109
		switch ( $_GET['jetpack-notice'] ) {
5110
			case 'dismiss':
5111
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5112
5113
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5114
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5115
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5116
				}
5117
				break;
5118
		}
5119
	}
5120
5121
	public static function sort_modules( $a, $b ) {
5122
		if ( $a['sort'] == $b['sort'] ) {
5123
			return 0;
5124
		}
5125
5126
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5127
	}
5128
5129
	function ajax_recheck_ssl() {
5130
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5131
		$result = self::permit_ssl( true );
5132
		wp_send_json(
5133
			array(
5134
				'enabled' => $result,
5135
				'message' => get_transient( 'jetpack_https_test_message' ),
5136
			)
5137
		);
5138
	}
5139
5140
	/* Client API */
5141
5142
	/**
5143
	 * Returns the requested Jetpack API URL
5144
	 *
5145
	 * @deprecated since 7.7
5146
	 * @return string
5147
	 */
5148
	public static function api_url( $relative_url ) {
5149
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5150
		$connection = self::connection();
5151
		return $connection->api_url( $relative_url );
5152
	}
5153
5154
	/**
5155
	 * @deprecated 8.0
5156
	 *
5157
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5158
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5159
	 */
5160
	public static function fix_url_for_bad_hosts( $url ) {
5161
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5162
		return $url;
5163
	}
5164
5165
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5166
		// Default to a blog token.
5167
		$token_type = 'blog';
5168
5169
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5170
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5171
			if ( ! empty( $_GET['onboarding'] ) ) {
5172
				$jpo = $_GET;
5173
			} else {
5174
				$jpo = json_decode( $request_data, true );
5175
			}
5176
5177
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5178
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5179
5180
			if (
5181
				isset( $jpo_user )
5182
				&& isset( $jpo_token )
5183
				&& is_email( $jpo_user )
5184
				&& ctype_alnum( $jpo_token )
5185
				&& isset( $_GET['rest_route'] )
5186
				&& self::validate_onboarding_token_action(
5187
					$jpo_token,
5188
					$_GET['rest_route']
5189
				)
5190
			) {
5191
				$jp_user = get_user_by( 'email', $jpo_user );
5192
				if ( is_a( $jp_user, 'WP_User' ) ) {
5193
					wp_set_current_user( $jp_user->ID );
5194
					$user_can = is_multisite()
5195
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5196
						: current_user_can( 'manage_options' );
5197
					if ( $user_can ) {
5198
						$token_type              = 'user';
5199
						$token->external_user_id = $jp_user->ID;
5200
					}
5201
				}
5202
			}
5203
5204
			$token_data['type']    = $token_type;
5205
			$token_data['user_id'] = $token->external_user_id;
5206
		}
5207
5208
		return $token_data;
5209
	}
5210
5211
	/**
5212
	 * Create a random secret for validating onboarding payload
5213
	 *
5214
	 * @return string Secret token
5215
	 */
5216
	public static function create_onboarding_token() {
5217
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5218
			$token = wp_generate_password( 32, false );
5219
			Jetpack_Options::update_option( 'onboarding', $token );
5220
		}
5221
5222
		return $token;
5223
	}
5224
5225
	/**
5226
	 * Remove the onboarding token
5227
	 *
5228
	 * @return bool True on success, false on failure
5229
	 */
5230
	public static function invalidate_onboarding_token() {
5231
		return Jetpack_Options::delete_option( 'onboarding' );
5232
	}
5233
5234
	/**
5235
	 * Validate an onboarding token for a specific action
5236
	 *
5237
	 * @return boolean True if token/action pair is accepted, false if not
5238
	 */
5239
	public static function validate_onboarding_token_action( $token, $action ) {
5240
		// Compare tokens, bail if tokens do not match
5241
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5242
			return false;
5243
		}
5244
5245
		// List of valid actions we can take
5246
		$valid_actions = array(
5247
			'/jetpack/v4/settings',
5248
		);
5249
5250
		// Only allow valid actions.
5251
		if ( ! in_array( $action, $valid_actions ) ) {
5252
			return false;
5253
		}
5254
5255
		return true;
5256
	}
5257
5258
	/**
5259
	 * Checks to see if the URL is using SSL to connect with Jetpack
5260
	 *
5261
	 * @since 2.3.3
5262
	 * @return boolean
5263
	 */
5264
	public static function permit_ssl( $force_recheck = false ) {
5265
		// Do some fancy tests to see if ssl is being supported
5266
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5267
			$message = '';
5268
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5269
				$ssl = 0;
5270
			} else {
5271
				$ssl = 1;
5272
5273
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5274
					$ssl     = 0;
5275
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5276
				} else {
5277
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5278
					if ( is_wp_error( $response ) ) {
5279
						$ssl     = 0;
5280
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5281
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5282
						$ssl     = 0;
5283
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5284
					}
5285
				}
5286
			}
5287
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5288
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5289
		}
5290
5291
		return (bool) $ssl;
5292
	}
5293
5294
	/*
5295
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5296
	 */
5297
	public function alert_auto_ssl_fail() {
5298
		if ( ! current_user_can( 'manage_options' ) ) {
5299
			return;
5300
		}
5301
5302
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5303
		?>
5304
5305
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5306
			<div class="jp-banner__content">
5307
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5308
				<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>
5309
				<p>
5310
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5311
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5312
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5313
				</p>
5314
				<p>
5315
					<?php
5316
					printf(
5317
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5318
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5319
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5320
					);
5321
					?>
5322
				</p>
5323
			</div>
5324
		</div>
5325
		<style>
5326
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5327
		</style>
5328
		<script type="text/javascript">
5329
			jQuery( document ).ready( function( $ ) {
5330
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5331
					var $this = $( this );
5332
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5333
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5334
					e.preventDefault();
5335
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5336
					$.post( ajaxurl, data )
5337
					  .done( function( response ) {
5338
						  if ( response.enabled ) {
5339
							  $( '#jetpack-ssl-warning' ).hide();
5340
						  } else {
5341
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5342
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5343
						  }
5344
					  }.bind( $this ) );
5345
				} );
5346
			} );
5347
		</script>
5348
5349
		<?php
5350
	}
5351
5352
	/**
5353
	 * Returns the Jetpack XML-RPC API
5354
	 *
5355
	 * @deprecated 8.0 Use Connection_Manager instead.
5356
	 * @return string
5357
	 */
5358
	public static function xmlrpc_api_url() {
5359
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5360
		return self::connection()->xmlrpc_api_url();
5361
	}
5362
5363
	/**
5364
	 * Returns the connection manager object.
5365
	 *
5366
	 * @return Automattic\Jetpack\Connection\Manager
5367
	 */
5368
	public static function connection() {
5369
		$jetpack = static::init();
5370
5371
		// If the connection manager hasn't been instantiated, do that now.
5372
		if ( ! $jetpack->connection_manager ) {
5373
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5374
		}
5375
5376
		return $jetpack->connection_manager;
5377
	}
5378
5379
	/**
5380
	 * Creates two secret tokens and the end of life timestamp for them.
5381
	 *
5382
	 * Note these tokens are unique per call, NOT static per site for connecting.
5383
	 *
5384
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5385
	 *
5386
	 * @since 2.6
5387
	 * @param String  $action  The action name.
5388
	 * @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...
5389
	 * @param Integer $exp     Expiration time in seconds.
5390
	 * @return array
5391
	 */
5392
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5393
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5394
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5395
	}
5396
5397
	public static function get_secrets( $action, $user_id ) {
5398
		$secrets = ( new Secrets() )->get( $action, $user_id );
5399
5400
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5401
			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...
5402
		}
5403
5404
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5405
			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...
5406
		}
5407
5408
		return $secrets;
5409
	}
5410
5411
	/**
5412
	 * Builds the timeout limit for queries talking with the wpcom servers.
5413
	 *
5414
	 * Based on local php max_execution_time in php.ini
5415
	 *
5416
	 * @since 2.6
5417
	 * @return int
5418
	 * @deprecated
5419
	 **/
5420
	public function get_remote_query_timeout_limit() {
5421
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5422
		return self::get_max_execution_time();
5423
	}
5424
5425
	/**
5426
	 * Builds the timeout limit for queries talking with the wpcom servers.
5427
	 *
5428
	 * Based on local php max_execution_time in php.ini
5429
	 *
5430
	 * @since 5.4
5431
	 * @return int
5432
	 **/
5433
	public static function get_max_execution_time() {
5434
		$timeout = (int) ini_get( 'max_execution_time' );
5435
5436
		// Ensure exec time set in php.ini
5437
		if ( ! $timeout ) {
5438
			$timeout = 30;
5439
		}
5440
		return $timeout;
5441
	}
5442
5443
	/**
5444
	 * Sets a minimum request timeout, and returns the current timeout
5445
	 *
5446
	 * @since 5.4
5447
	 **/
5448 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5449
		$timeout = self::get_max_execution_time();
5450
		if ( $timeout < $min_timeout ) {
5451
			$timeout = $min_timeout;
5452
			set_time_limit( $timeout );
5453
		}
5454
		return $timeout;
5455
	}
5456
5457
	/**
5458
	 * Takes the response from the Jetpack register new site endpoint and
5459
	 * verifies it worked properly.
5460
	 *
5461
	 * @since 2.6
5462
	 * @deprecated since 7.7.0
5463
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5464
	 **/
5465
	public function validate_remote_register_response() {
5466
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5467
	}
5468
5469
	/**
5470
	 * @return bool|WP_Error
5471
	 */
5472
	public static function register() {
5473
		$tracking = new Tracking();
5474
		$tracking->record_user_event( 'jpc_register_begin' );
5475
5476
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5477
5478
		$connection   = self::connection();
5479
		$registration = $connection->register();
5480
5481
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5482
5483
		if ( ! $registration || is_wp_error( $registration ) ) {
5484
			return $registration;
5485
		}
5486
5487
		return true;
5488
	}
5489
5490
	/**
5491
	 * Filters the registration request body to include tracking properties.
5492
	 *
5493
	 * @param array $properties
5494
	 * @return array amended properties.
5495
	 */
5496 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5497
		$tracking        = new Tracking();
5498
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5499
5500
		return array_merge(
5501
			$properties,
5502
			array(
5503
				'_ui' => $tracks_identity['_ui'],
5504
				'_ut' => $tracks_identity['_ut'],
5505
			)
5506
		);
5507
	}
5508
5509
	/**
5510
	 * Filters the token request body to include tracking properties.
5511
	 *
5512
	 * @param array $properties
5513
	 * @return array amended properties.
5514
	 */
5515 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5516
		$tracking        = new Tracking();
5517
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5518
5519
		return array_merge(
5520
			$properties,
5521
			array(
5522
				'_ui' => $tracks_identity['_ui'],
5523
				'_ut' => $tracks_identity['_ut'],
5524
			)
5525
		);
5526
	}
5527
5528
	/**
5529
	 * If the db version is showing something other that what we've got now, bump it to current.
5530
	 *
5531
	 * @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...
5532
	 */
5533
	public static function maybe_set_version_option() {
5534
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5535
		if ( JETPACK__VERSION != $version ) {
5536
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5537
5538
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5539
				/** This action is documented in class.jetpack.php */
5540
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5541
			}
5542
5543
			return true;
5544
		}
5545
		return false;
5546
	}
5547
5548
	/* Client Server API */
5549
5550
	/**
5551
	 * Loads the Jetpack XML-RPC client.
5552
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5553
	 *
5554
	 * @deprecated since 7.7.0
5555
	 */
5556
	public static function load_xml_rpc_client() {
5557
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5558
	}
5559
5560
	/**
5561
	 * Resets the saved authentication state in between testing requests.
5562
	 *
5563
	 * @deprecated since 8.9.0
5564
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5565
	 */
5566
	public function reset_saved_auth_state() {
5567
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5568
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5569
	}
5570
5571
	/**
5572
	 * Verifies the signature of the current request.
5573
	 *
5574
	 * @deprecated since 7.7.0
5575
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5576
	 *
5577
	 * @return false|array
5578
	 */
5579
	public function verify_xml_rpc_signature() {
5580
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5581
		return self::connection()->verify_xml_rpc_signature();
5582
	}
5583
5584
	/**
5585
	 * Verifies the signature of the current request.
5586
	 *
5587
	 * This function has side effects and should not be used. Instead,
5588
	 * use the memoized version `->verify_xml_rpc_signature()`.
5589
	 *
5590
	 * @deprecated since 7.7.0
5591
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5592
	 * @internal
5593
	 */
5594
	private function internal_verify_xml_rpc_signature() {
5595
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5596
	}
5597
5598
	/**
5599
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5600
	 *
5601
	 * @deprecated since 7.7.0
5602
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5603
	 *
5604
	 * @param \WP_User|mixed $user     User object if authenticated.
5605
	 * @param string         $username Username.
5606
	 * @param string         $password Password string.
5607
	 * @return \WP_User|mixed Authenticated user or error.
5608
	 */
5609 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5610
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5611
5612
		if ( ! $this->connection_manager ) {
5613
			$this->connection_manager = new Connection_Manager();
5614
		}
5615
5616
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5617
	}
5618
5619
	/**
5620
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5621
	 * Uses the existing XMLRPC request signing implementation.
5622
	 *
5623
	 * @deprecated since 8.9.0
5624
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5625
	 */
5626
	function wp_rest_authenticate( $user ) {
5627
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5628
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5629
	}
5630
5631
	/**
5632
	 * Report authentication status to the WP REST API.
5633
	 *
5634
	 * @deprecated since 8.9.0
5635
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5636
	 *
5637
	 * @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...
5638
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5639
	 */
5640
	public function wp_rest_authentication_errors( $value ) {
5641
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5642
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5643
	}
5644
5645
	/**
5646
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5647
	 * Capture it here so we can verify the signature later.
5648
	 *
5649
	 * @deprecated since 7.7.0
5650
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5651
	 *
5652
	 * @param array $methods XMLRPC methods.
5653
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5654
	 */
5655 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5656
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5657
5658
		if ( ! $this->connection_manager ) {
5659
			$this->connection_manager = new Connection_Manager();
5660
		}
5661
5662
		return $this->connection_manager->xmlrpc_methods( $methods );
5663
	}
5664
5665
	/**
5666
	 * Register additional public XMLRPC methods.
5667
	 *
5668
	 * @deprecated since 7.7.0
5669
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5670
	 *
5671
	 * @param array $methods Public XMLRPC methods.
5672
	 * @return array Public XMLRPC methods, with the getOptions one.
5673
	 */
5674 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5675
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5676
5677
		if ( ! $this->connection_manager ) {
5678
			$this->connection_manager = new Connection_Manager();
5679
		}
5680
5681
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5682
	}
5683
5684
	/**
5685
	 * Handles a getOptions XMLRPC method call.
5686
	 *
5687
	 * @deprecated since 7.7.0
5688
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5689
	 *
5690
	 * @param array $args method call arguments.
5691
	 * @return array an amended XMLRPC server options array.
5692
	 */
5693 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5694
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5695
5696
		if ( ! $this->connection_manager ) {
5697
			$this->connection_manager = new Connection_Manager();
5698
		}
5699
5700
		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...
5701
	}
5702
5703
	/**
5704
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5705
	 *
5706
	 * @deprecated since 7.7.0
5707
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5708
	 *
5709
	 * @param array $options Standard Core options.
5710
	 * @return array Amended options.
5711
	 */
5712 View Code Duplication
	public function xmlrpc_options( $options ) {
5713
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5714
5715
		if ( ! $this->connection_manager ) {
5716
			$this->connection_manager = new Connection_Manager();
5717
		}
5718
5719
		return $this->connection_manager->xmlrpc_options( $options );
5720
	}
5721
5722
	/**
5723
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5724
	 * SET: state( $key, $value );
5725
	 * GET: $value = state( $key );
5726
	 *
5727
	 * @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...
5728
	 * @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...
5729
	 * @param bool   $restate private
5730
	 */
5731
	public static function state( $key = null, $value = null, $restate = false ) {
5732
		static $state = array();
5733
		static $path, $domain;
5734
		if ( ! isset( $path ) ) {
5735
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5736
			$admin_url = self::admin_url();
5737
			$bits      = wp_parse_url( $admin_url );
5738
5739
			if ( is_array( $bits ) ) {
5740
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5741
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5742
			} else {
5743
				$path = $domain = null;
5744
			}
5745
		}
5746
5747
		// Extract state from cookies and delete cookies
5748
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5749
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5750
			unset( $_COOKIE['jetpackState'] );
5751
			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...
5752
				if ( strlen( $v ) ) {
5753
					$state[ $k ] = $v;
5754
				}
5755
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5756
			}
5757
		}
5758
5759
		if ( $restate ) {
5760
			foreach ( $state as $k => $v ) {
5761
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5762
			}
5763
			return;
5764
		}
5765
5766
		// Get a state variable.
5767
		if ( isset( $key ) && ! isset( $value ) ) {
5768
			if ( array_key_exists( $key, $state ) ) {
5769
				return $state[ $key ];
5770
			}
5771
			return null;
5772
		}
5773
5774
		// Set a state variable.
5775
		if ( isset( $key ) && isset( $value ) ) {
5776
			if ( is_array( $value ) && isset( $value[0] ) ) {
5777
				$value = $value[0];
5778
			}
5779
			$state[ $key ] = $value;
5780
			if ( ! headers_sent() ) {
5781
				if ( self::should_set_cookie( $key ) ) {
5782
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5783
				}
5784
			}
5785
		}
5786
	}
5787
5788
	public static function restate() {
5789
		self::state( null, null, true );
5790
	}
5791
5792
	/**
5793
	 * Determines whether the jetpackState[$key] value should be added to the
5794
	 * cookie.
5795
	 *
5796
	 * @param string $key The state key.
5797
	 *
5798
	 * @return boolean Whether the value should be added to the cookie.
5799
	 */
5800
	public static function should_set_cookie( $key ) {
5801
		global $current_screen;
5802
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5803
5804
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5805
			return false;
5806
		}
5807
5808
		return true;
5809
	}
5810
5811
	public static function check_privacy( $file ) {
5812
		static $is_site_publicly_accessible = null;
5813
5814
		if ( is_null( $is_site_publicly_accessible ) ) {
5815
			$is_site_publicly_accessible = false;
5816
5817
			$rpc = new Jetpack_IXR_Client();
5818
5819
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5820
			if ( $success ) {
5821
				$response = $rpc->getResponse();
5822
				if ( $response ) {
5823
					$is_site_publicly_accessible = true;
5824
				}
5825
			}
5826
5827
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5828
		}
5829
5830
		if ( $is_site_publicly_accessible ) {
5831
			return;
5832
		}
5833
5834
		$module_slug = self::get_module_slug( $file );
5835
5836
		$privacy_checks = self::state( 'privacy_checks' );
5837
		if ( ! $privacy_checks ) {
5838
			$privacy_checks = $module_slug;
5839
		} else {
5840
			$privacy_checks .= ",$module_slug";
5841
		}
5842
5843
		self::state( 'privacy_checks', $privacy_checks );
5844
	}
5845
5846
	/**
5847
	 * Helper method for multicall XMLRPC.
5848
	 *
5849
	 * @deprecated since 8.9.0
5850
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5851
	 *
5852
	 * @param ...$args Args for the async_call.
5853
	 */
5854
	public static function xmlrpc_async_call( ...$args ) {
5855
5856
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5857
5858
		global $blog_id;
5859
		static $clients = array();
5860
5861
		$client_blog_id = is_multisite() ? $blog_id : 0;
5862
5863
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5864
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5865
			if ( function_exists( 'ignore_user_abort' ) ) {
5866
				ignore_user_abort( true );
5867
			}
5868
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5869
		}
5870
5871
		if ( ! empty( $args[0] ) ) {
5872
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5873
		} elseif ( is_multisite() ) {
5874
			foreach ( $clients as $client_blog_id => $client ) {
5875
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5876
					continue;
5877
				}
5878
5879
				$switch_success = switch_to_blog( $client_blog_id, true );
5880
				if ( ! $switch_success ) {
5881
					continue;
5882
				}
5883
5884
				flush();
5885
				$client->query();
5886
5887
				restore_current_blog();
5888
			}
5889
		} else {
5890
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5891
				flush();
5892
				$clients[0]->query();
5893
			}
5894
		}
5895
	}
5896
5897
	/**
5898
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5899
	 *
5900
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5901
	 *
5902
	 * @param string $url WordPress.com static resource URL.
5903
	 */
5904
	public static function staticize_subdomain( $url ) {
5905
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5906
		return Assets::staticize_subdomain( $url );
5907
	}
5908
5909
	/* JSON API Authorization */
5910
5911
	/**
5912
	 * Handles the login action for Authorizing the JSON API
5913
	 */
5914
	function login_form_json_api_authorization() {
5915
		$this->verify_json_api_authorization_request();
5916
5917
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5918
5919
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5920
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5921
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5922
	}
5923
5924
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5925
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5926
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5927
			return $url;
5928
		}
5929
5930
		$parsed_url = wp_parse_url( $url );
5931
		$url        = strtok( $url, '?' );
5932
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5933
		if ( ! empty( $parsed_url['query'] ) ) {
5934
			$url .= "&{$parsed_url['query']}";
5935
		}
5936
5937
		return $url;
5938
	}
5939
5940
	// Make sure the POSTed request is handled by the same action
5941
	function preserve_action_in_login_form_for_json_api_authorization() {
5942
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5943
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5944
	}
5945
5946
	// If someone logs in to approve API access, store the Access Code in usermeta
5947
	function store_json_api_authorization_token( $user_login, $user ) {
5948
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5949
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5950
		$token = wp_generate_password( 32, false );
5951
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5952
	}
5953
5954
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5955
	function allow_wpcom_public_api_domain( $domains ) {
5956
		$domains[] = 'public-api.wordpress.com';
5957
		return $domains;
5958
	}
5959
5960
	static function is_redirect_encoded( $redirect_url ) {
5961
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5962
	}
5963
5964
	// Add all wordpress.com environments to the safe redirect allowed list.
5965
	function allow_wpcom_environments( $domains ) {
5966
		$domains[] = 'wordpress.com';
5967
		$domains[] = 'wpcalypso.wordpress.com';
5968
		$domains[] = 'horizon.wordpress.com';
5969
		$domains[] = 'calypso.localhost';
5970
		return $domains;
5971
	}
5972
5973
	// Add the Access Code details to the public-api.wordpress.com redirect
5974
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5975
		return add_query_arg(
5976
			urlencode_deep(
5977
				array(
5978
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5979
					'jetpack-user-id' => (int) $user->ID,
5980
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5981
				)
5982
			),
5983
			$redirect_to
5984
		);
5985
	}
5986
5987
	/**
5988
	 * Verifies the request by checking the signature
5989
	 *
5990
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5991
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5992
	 *
5993
	 * @param null|array $environment
5994
	 */
5995
	function verify_json_api_authorization_request( $environment = null ) {
5996
		$environment = is_null( $environment )
5997
			? $_REQUEST
5998
			: $environment;
5999
6000
		//phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
6001
		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...
6002
		$token = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
6003
		if ( ! $token || empty( $token->secret ) ) {
6004
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6005
		}
6006
6007
		$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' );
6008
6009
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6010
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6011
			/**
6012
			 * Jetpack authorisation request Error.
6013
			 *
6014
			 * @since 7.5.0
6015
			 */
6016
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6017
			$die_error = sprintf(
6018
				/* translators: %s is a URL */
6019
				__( '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' ),
6020
				Redirect::get_url( 'jetpack-support-double-encoding' )
6021
			);
6022
		}
6023
6024
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6025
6026
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6027
			$signature = $jetpack_signature->sign_request(
6028
				$environment['token'],
6029
				$environment['timestamp'],
6030
				$environment['nonce'],
6031
				'',
6032
				'GET',
6033
				$environment['jetpack_json_api_original_query'],
6034
				null,
6035
				true
6036
			);
6037
		} else {
6038
			$signature = $jetpack_signature->sign_current_request(
6039
				array(
6040
					'body'   => null,
6041
					'method' => 'GET',
6042
				)
6043
			);
6044
		}
6045
6046
		if ( ! $signature ) {
6047
			wp_die( $die_error );
6048
		} elseif ( is_wp_error( $signature ) ) {
6049
			wp_die( $die_error );
6050
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6051
			if ( is_ssl() ) {
6052
				// 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
6053
				$signature = $jetpack_signature->sign_current_request(
6054
					array(
6055
						'scheme' => 'http',
6056
						'body'   => null,
6057
						'method' => 'GET',
6058
					)
6059
				);
6060
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6061
					wp_die( $die_error );
6062
				}
6063
			} else {
6064
				wp_die( $die_error );
6065
			}
6066
		}
6067
6068
		$timestamp = (int) $environment['timestamp'];
6069
		$nonce     = stripslashes( (string) $environment['nonce'] );
6070
6071
		if ( ! $this->connection_manager ) {
6072
			$this->connection_manager = new Connection_Manager();
6073
		}
6074
6075
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
6076
			// De-nonce the nonce, at least for 5 minutes.
6077
			// 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)
6078
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6079
			if ( $old_nonce_time < time() - 300 ) {
6080
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6081
			}
6082
		}
6083
6084
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6085
		$data_filters = array(
6086
			'state'        => 'opaque',
6087
			'client_id'    => 'int',
6088
			'client_title' => 'string',
6089
			'client_image' => 'url',
6090
		);
6091
6092
		foreach ( $data_filters as $key => $sanitation ) {
6093
			if ( ! isset( $data->$key ) ) {
6094
				wp_die( $die_error );
6095
			}
6096
6097
			switch ( $sanitation ) {
6098
				case 'int':
6099
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6100
					break;
6101
				case 'opaque':
6102
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6103
					break;
6104
				case 'string':
6105
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6106
					break;
6107
				case 'url':
6108
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6109
					break;
6110
			}
6111
		}
6112
6113
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6114
			wp_die( $die_error );
6115
		}
6116
	}
6117
6118
	function login_message_json_api_authorization( $message ) {
6119
		return '<p class="message">' . sprintf(
6120
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6121
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6122
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6123
	}
6124
6125
	/**
6126
	 * Get $content_width, but with a <s>twist</s> filter.
6127
	 */
6128
	public static function get_content_width() {
6129
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6130
			? $GLOBALS['content_width']
6131
			: false;
6132
		/**
6133
		 * Filter the Content Width value.
6134
		 *
6135
		 * @since 2.2.3
6136
		 *
6137
		 * @param string $content_width Content Width value.
6138
		 */
6139
		return apply_filters( 'jetpack_content_width', $content_width );
6140
	}
6141
6142
	/**
6143
	 * Pings the WordPress.com Mirror Site for the specified options.
6144
	 *
6145
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6146
	 *
6147
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6148
	 */
6149
	public function get_cloud_site_options( $option_names ) {
6150
		$option_names = array_filter( (array) $option_names, 'is_string' );
6151
6152
		$xml = new Jetpack_IXR_Client();
6153
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6154
		if ( $xml->isError() ) {
6155
			return array(
6156
				'error_code' => $xml->getErrorCode(),
6157
				'error_msg'  => $xml->getErrorMessage(),
6158
			);
6159
		}
6160
		$cloud_site_options = $xml->getResponse();
6161
6162
		return $cloud_site_options;
6163
	}
6164
6165
	/**
6166
	 * Checks if the site is currently in an identity crisis.
6167
	 *
6168
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6169
	 */
6170
	public static function check_identity_crisis() {
6171
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6172
			return false;
6173
		}
6174
6175
		return Jetpack_Options::get_option( 'sync_error_idc' );
6176
	}
6177
6178
	/**
6179
	 * Checks whether the home and siteurl specifically are allowed.
6180
	 * Written so that we don't have re-check $key and $value params every time
6181
	 * we want to check if this site is allowed, for example in footer.php
6182
	 *
6183
	 * @since  3.8.0
6184
	 * @return bool True = already allowed False = not on the allowed list.
6185
	 */
6186
	public static function is_staging_site() {
6187
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6188
		return ( new Status() )->is_staging_site();
6189
	}
6190
6191
	/**
6192
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6193
	 *
6194
	 * @since 4.4.0
6195
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6196
	 *
6197
	 * @return bool
6198
	 */
6199
	public static function validate_sync_error_idc_option() {
6200
		$is_valid = false;
6201
6202
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6203
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6204
		if ( $sync_error && self::sync_idc_optin() ) {
6205
			$local_options = self::get_sync_error_idc_option();
6206
			// Ensure all values are set.
6207
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6208
6209
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6210
				if (
6211
						isset( $sync_error['wpcom_home'] ) &&
6212
						isset( $sync_error['wpcom_siteurl'] ) &&
6213
						$sync_error['wpcom_home'] === $local_options['home'] &&
6214
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6215
				) {
6216
					$is_valid = false;
6217
					// Enable migrate_for_idc so that sync actions are accepted.
6218
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6219
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6220
					$is_valid = true;
6221
				}
6222
			}
6223
		}
6224
6225
		/**
6226
		 * Filters whether the sync_error_idc option is valid.
6227
		 *
6228
		 * @since 4.4.0
6229
		 *
6230
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6231
		 */
6232
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6233
6234
		if ( ! $is_valid && $sync_error ) {
6235
			// Since the option exists, and did not validate, delete it
6236
			Jetpack_Options::delete_option( 'sync_error_idc' );
6237
		}
6238
6239
		return $is_valid;
6240
	}
6241
6242
	/**
6243
	 * Normalizes a url by doing three things:
6244
	 *  - Strips protocol
6245
	 *  - Strips www
6246
	 *  - Adds a trailing slash
6247
	 *
6248
	 * @since 4.4.0
6249
	 * @param string $url
6250
	 * @return WP_Error|string
6251
	 */
6252
	public static function normalize_url_protocol_agnostic( $url ) {
6253
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6254
		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...
6255
			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...
6256
		}
6257
6258
		// Strip www and protocols
6259
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6260
		return $url;
6261
	}
6262
6263
	/**
6264
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6265
	 *
6266
	 * @since 4.4.0
6267
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6268
	 *
6269
	 * @param array $response
6270
	 * @return array Array of the local urls, wpcom urls, and error code
6271
	 */
6272
	public static function get_sync_error_idc_option( $response = array() ) {
6273
		// Since the local options will hit the database directly, store the values
6274
		// in a transient to allow for autoloading and caching on subsequent views.
6275
		$local_options = get_transient( 'jetpack_idc_local' );
6276
		if ( false === $local_options ) {
6277
			$local_options = array(
6278
				'home'    => Functions::home_url(),
6279
				'siteurl' => Functions::site_url(),
6280
			);
6281
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6282
		}
6283
6284
		$options = array_merge( $local_options, $response );
6285
6286
		$returned_values = array();
6287
		foreach ( $options as $key => $option ) {
6288
			if ( 'error_code' === $key ) {
6289
				$returned_values[ $key ] = $option;
6290
				continue;
6291
			}
6292
6293
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6294
				continue;
6295
			}
6296
6297
			$returned_values[ $key ] = $normalized_url;
6298
		}
6299
6300
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6301
6302
		return $returned_values;
6303
	}
6304
6305
	/**
6306
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6307
	 * If set to true, the site will be put into staging mode.
6308
	 *
6309
	 * @since 4.3.2
6310
	 * @return bool
6311
	 */
6312
	public static function sync_idc_optin() {
6313
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6314
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6315
		} else {
6316
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6317
		}
6318
6319
		/**
6320
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
6321
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
6322
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6323
		 *
6324
		 * @since 4.3.2
6325
		 *
6326
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6327
		 */
6328
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6329
	}
6330
6331
	/**
6332
	 * Maybe Use a .min.css stylesheet, maybe not.
6333
	 *
6334
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6335
	 */
6336
	public static function maybe_min_asset( $url, $path, $plugin ) {
6337
		// Short out on things trying to find actual paths.
6338
		if ( ! $path || empty( $plugin ) ) {
6339
			return $url;
6340
		}
6341
6342
		$path = ltrim( $path, '/' );
6343
6344
		// Strip out the abspath.
6345
		$base = dirname( plugin_basename( $plugin ) );
6346
6347
		// Short out on non-Jetpack assets.
6348
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6349
			return $url;
6350
		}
6351
6352
		// File name parsing.
6353
		$file              = "{$base}/{$path}";
6354
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6355
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6356
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6357
		$extension         = array_shift( $file_name_parts_r );
6358
6359
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6360
			// Already pointing at the minified version.
6361
			if ( 'min' === $file_name_parts_r[0] ) {
6362
				return $url;
6363
			}
6364
6365
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6366
			if ( file_exists( $min_full_path ) ) {
6367
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6368
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6369
				if ( 'css' === $extension ) {
6370
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6371
					self::$min_assets[ $key ] = $path;
6372
				}
6373
			}
6374
		}
6375
6376
		return $url;
6377
	}
6378
6379
	/**
6380
	 * If the asset is minified, let's flag .min as the suffix.
6381
	 *
6382
	 * Attached to `style_loader_src` filter.
6383
	 *
6384
	 * @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...
6385
	 * @param string $handle The registered handle of the script in question.
6386
	 * @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...
6387
	 */
6388
	public static function set_suffix_on_min( $src, $handle ) {
6389
		if ( false === strpos( $src, '.min.css' ) ) {
6390
			return $src;
6391
		}
6392
6393
		if ( ! empty( self::$min_assets ) ) {
6394
			foreach ( self::$min_assets as $file => $path ) {
6395
				if ( false !== strpos( $src, $file ) ) {
6396
					wp_style_add_data( $handle, 'suffix', '.min' );
6397
					return $src;
6398
				}
6399
			}
6400
		}
6401
6402
		return $src;
6403
	}
6404
6405
	/**
6406
	 * Maybe inlines a stylesheet.
6407
	 *
6408
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6409
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6410
	 *
6411
	 * Attached to `style_loader_tag` filter.
6412
	 *
6413
	 * @param string $tag The tag that would link to the external asset.
6414
	 * @param string $handle The registered handle of the script in question.
6415
	 *
6416
	 * @return string
6417
	 */
6418
	public static function maybe_inline_style( $tag, $handle ) {
6419
		global $wp_styles;
6420
		$item = $wp_styles->registered[ $handle ];
6421
6422
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6423
			return $tag;
6424
		}
6425
6426
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6427
			$href = $matches[1];
6428
			// Strip off query string
6429
			if ( $pos = strpos( $href, '?' ) ) {
6430
				$href = substr( $href, 0, $pos );
6431
			}
6432
			// Strip off fragment
6433
			if ( $pos = strpos( $href, '#' ) ) {
6434
				$href = substr( $href, 0, $pos );
6435
			}
6436
		} else {
6437
			return $tag;
6438
		}
6439
6440
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6441
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6442
			return $tag;
6443
		}
6444
6445
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6446
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6447
			// And this isn't the pass that actually deals with the RTL version...
6448
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6449
				// Short out, as the RTL version will deal with it in a moment.
6450
				return $tag;
6451
			}
6452
		}
6453
6454
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6455
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6456
		if ( $css ) {
6457
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6458
			if ( empty( $item->extra['after'] ) ) {
6459
				wp_add_inline_style( $handle, $css );
6460
			} else {
6461
				array_unshift( $item->extra['after'], $css );
6462
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6463
			}
6464
		}
6465
6466
		return $tag;
6467
	}
6468
6469
	/**
6470
	 * Loads a view file from the views
6471
	 *
6472
	 * Data passed in with the $data parameter will be available in the
6473
	 * template file as $data['value']
6474
	 *
6475
	 * @param string $template - Template file to load
6476
	 * @param array  $data - Any data to pass along to the template
6477
	 * @return boolean - If template file was found
6478
	 **/
6479
	public function load_view( $template, $data = array() ) {
6480
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6481
6482
		if ( file_exists( $views_dir . $template ) ) {
6483
			require_once $views_dir . $template;
6484
			return true;
6485
		}
6486
6487
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6488
		return false;
6489
	}
6490
6491
	/**
6492
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6493
	 */
6494
	public function deprecated_hooks() {
6495
		$filter_deprecated_list = array(
6496
			'jetpack_bail_on_shortcode'                    => array(
6497
				'replacement' => 'jetpack_shortcodes_to_include',
6498
				'version'     => 'jetpack-3.1.0',
6499
			),
6500
			'wpl_sharing_2014_1'                           => array(
6501
				'replacement' => null,
6502
				'version'     => 'jetpack-3.6.0',
6503
			),
6504
			'jetpack-tools-to-include'                     => array(
6505
				'replacement' => 'jetpack_tools_to_include',
6506
				'version'     => 'jetpack-3.9.0',
6507
			),
6508
			'jetpack_identity_crisis_options_to_check'     => array(
6509
				'replacement' => null,
6510
				'version'     => 'jetpack-4.0.0',
6511
			),
6512
			'update_option_jetpack_single_user_site'       => array(
6513
				'replacement' => null,
6514
				'version'     => 'jetpack-4.3.0',
6515
			),
6516
			'audio_player_default_colors'                  => array(
6517
				'replacement' => null,
6518
				'version'     => 'jetpack-4.3.0',
6519
			),
6520
			'add_option_jetpack_featured_images_enabled'   => array(
6521
				'replacement' => null,
6522
				'version'     => 'jetpack-4.3.0',
6523
			),
6524
			'add_option_jetpack_update_details'            => array(
6525
				'replacement' => null,
6526
				'version'     => 'jetpack-4.3.0',
6527
			),
6528
			'add_option_jetpack_updates'                   => array(
6529
				'replacement' => null,
6530
				'version'     => 'jetpack-4.3.0',
6531
			),
6532
			'add_option_jetpack_network_name'              => array(
6533
				'replacement' => null,
6534
				'version'     => 'jetpack-4.3.0',
6535
			),
6536
			'add_option_jetpack_network_allow_new_registrations' => array(
6537
				'replacement' => null,
6538
				'version'     => 'jetpack-4.3.0',
6539
			),
6540
			'add_option_jetpack_network_add_new_users'     => array(
6541
				'replacement' => null,
6542
				'version'     => 'jetpack-4.3.0',
6543
			),
6544
			'add_option_jetpack_network_site_upload_space' => array(
6545
				'replacement' => null,
6546
				'version'     => 'jetpack-4.3.0',
6547
			),
6548
			'add_option_jetpack_network_upload_file_types' => array(
6549
				'replacement' => null,
6550
				'version'     => 'jetpack-4.3.0',
6551
			),
6552
			'add_option_jetpack_network_enable_administration_menus' => array(
6553
				'replacement' => null,
6554
				'version'     => 'jetpack-4.3.0',
6555
			),
6556
			'add_option_jetpack_is_multi_site'             => array(
6557
				'replacement' => null,
6558
				'version'     => 'jetpack-4.3.0',
6559
			),
6560
			'add_option_jetpack_is_main_network'           => array(
6561
				'replacement' => null,
6562
				'version'     => 'jetpack-4.3.0',
6563
			),
6564
			'add_option_jetpack_main_network_site'         => array(
6565
				'replacement' => null,
6566
				'version'     => 'jetpack-4.3.0',
6567
			),
6568
			'jetpack_sync_all_registered_options'          => array(
6569
				'replacement' => null,
6570
				'version'     => 'jetpack-4.3.0',
6571
			),
6572
			'jetpack_has_identity_crisis'                  => array(
6573
				'replacement' => 'jetpack_sync_error_idc_validation',
6574
				'version'     => 'jetpack-4.4.0',
6575
			),
6576
			'jetpack_is_post_mailable'                     => array(
6577
				'replacement' => null,
6578
				'version'     => 'jetpack-4.4.0',
6579
			),
6580
			'jetpack_seo_site_host'                        => array(
6581
				'replacement' => null,
6582
				'version'     => 'jetpack-5.1.0',
6583
			),
6584
			'jetpack_installed_plugin'                     => array(
6585
				'replacement' => 'jetpack_plugin_installed',
6586
				'version'     => 'jetpack-6.0.0',
6587
			),
6588
			'jetpack_holiday_snow_option_name'             => array(
6589
				'replacement' => null,
6590
				'version'     => 'jetpack-6.0.0',
6591
			),
6592
			'jetpack_holiday_chance_of_snow'               => array(
6593
				'replacement' => null,
6594
				'version'     => 'jetpack-6.0.0',
6595
			),
6596
			'jetpack_holiday_snow_js_url'                  => array(
6597
				'replacement' => null,
6598
				'version'     => 'jetpack-6.0.0',
6599
			),
6600
			'jetpack_is_holiday_snow_season'               => array(
6601
				'replacement' => null,
6602
				'version'     => 'jetpack-6.0.0',
6603
			),
6604
			'jetpack_holiday_snow_option_updated'          => array(
6605
				'replacement' => null,
6606
				'version'     => 'jetpack-6.0.0',
6607
			),
6608
			'jetpack_holiday_snowing'                      => array(
6609
				'replacement' => null,
6610
				'version'     => 'jetpack-6.0.0',
6611
			),
6612
			'jetpack_sso_auth_cookie_expirtation'          => array(
6613
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6614
				'version'     => 'jetpack-6.1.0',
6615
			),
6616
			'jetpack_cache_plans'                          => array(
6617
				'replacement' => null,
6618
				'version'     => 'jetpack-6.1.0',
6619
			),
6620
6621
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6622
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6623
				'version'     => 'jetpack-6.5.0',
6624
			),
6625
			'jetpack_enable_site_verification'             => array(
6626
				'replacement' => null,
6627
				'version'     => 'jetpack-6.5.0',
6628
			),
6629
			'can_display_jetpack_manage_notice'            => array(
6630
				'replacement' => null,
6631
				'version'     => 'jetpack-7.3.0',
6632
			),
6633
			'atd_http_post_timeout'                        => array(
6634
				'replacement' => null,
6635
				'version'     => 'jetpack-7.3.0',
6636
			),
6637
			'atd_service_domain'                           => array(
6638
				'replacement' => null,
6639
				'version'     => 'jetpack-7.3.0',
6640
			),
6641
			'atd_load_scripts'                             => array(
6642
				'replacement' => null,
6643
				'version'     => 'jetpack-7.3.0',
6644
			),
6645
			'jetpack_widget_authors_exclude'               => array(
6646
				'replacement' => 'jetpack_widget_authors_params',
6647
				'version'     => 'jetpack-7.7.0',
6648
			),
6649
			// Removed in Jetpack 7.9.0
6650
			'jetpack_pwa_manifest'                         => array(
6651
				'replacement' => null,
6652
				'version'     => 'jetpack-7.9.0',
6653
			),
6654
			'jetpack_pwa_background_color'                 => array(
6655
				'replacement' => null,
6656
				'version'     => 'jetpack-7.9.0',
6657
			),
6658
			'jetpack_check_mobile'                         => array(
6659
				'replacement' => null,
6660
				'version'     => 'jetpack-8.3.0',
6661
			),
6662
			'jetpack_mobile_stylesheet'                    => array(
6663
				'replacement' => null,
6664
				'version'     => 'jetpack-8.3.0',
6665
			),
6666
			'jetpack_mobile_template'                      => array(
6667
				'replacement' => null,
6668
				'version'     => 'jetpack-8.3.0',
6669
			),
6670
			'jetpack_mobile_theme_menu'                    => array(
6671
				'replacement' => null,
6672
				'version'     => 'jetpack-8.3.0',
6673
			),
6674
			'minileven_show_featured_images'               => array(
6675
				'replacement' => null,
6676
				'version'     => 'jetpack-8.3.0',
6677
			),
6678
			'minileven_attachment_size'                    => array(
6679
				'replacement' => null,
6680
				'version'     => 'jetpack-8.3.0',
6681
			),
6682
			'instagram_cache_oembed_api_response_body'     => array(
6683
				'replacement' => null,
6684
				'version'     => 'jetpack-9.1.0',
6685
			),
6686
			'jetpack_can_make_outbound_https'              => array(
6687
				'replacement' => null,
6688
				'version'     => 'jetpack-9.1.0',
6689
			),
6690
		);
6691
6692
		foreach ( $filter_deprecated_list as $tag => $args ) {
6693
			if ( has_filter( $tag ) ) {
6694
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6695
			}
6696
		}
6697
6698
		$action_deprecated_list = array(
6699
			'jetpack_updated_theme'        => array(
6700
				'replacement' => 'jetpack_updated_themes',
6701
				'version'     => 'jetpack-6.2.0',
6702
			),
6703
			'atd_http_post_error'          => array(
6704
				'replacement' => null,
6705
				'version'     => 'jetpack-7.3.0',
6706
			),
6707
			'mobile_reject_mobile'         => array(
6708
				'replacement' => null,
6709
				'version'     => 'jetpack-8.3.0',
6710
			),
6711
			'mobile_force_mobile'          => array(
6712
				'replacement' => null,
6713
				'version'     => 'jetpack-8.3.0',
6714
			),
6715
			'mobile_app_promo_download'    => array(
6716
				'replacement' => null,
6717
				'version'     => 'jetpack-8.3.0',
6718
			),
6719
			'mobile_setup'                 => array(
6720
				'replacement' => null,
6721
				'version'     => 'jetpack-8.3.0',
6722
			),
6723
			'jetpack_mobile_footer_before' => array(
6724
				'replacement' => null,
6725
				'version'     => 'jetpack-8.3.0',
6726
			),
6727
			'wp_mobile_theme_footer'       => array(
6728
				'replacement' => null,
6729
				'version'     => 'jetpack-8.3.0',
6730
			),
6731
			'minileven_credits'            => array(
6732
				'replacement' => null,
6733
				'version'     => 'jetpack-8.3.0',
6734
			),
6735
			'jetpack_mobile_header_before' => array(
6736
				'replacement' => null,
6737
				'version'     => 'jetpack-8.3.0',
6738
			),
6739
			'jetpack_mobile_header_after'  => array(
6740
				'replacement' => null,
6741
				'version'     => 'jetpack-8.3.0',
6742
			),
6743
		);
6744
6745
		foreach ( $action_deprecated_list as $tag => $args ) {
6746
			if ( has_action( $tag ) ) {
6747
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6748
			}
6749
		}
6750
	}
6751
6752
	/**
6753
	 * Converts any url in a stylesheet, to the correct absolute url.
6754
	 *
6755
	 * Considerations:
6756
	 *  - Normal, relative URLs     `feh.png`
6757
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6758
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6759
	 *  - Absolute URLs             `http://domain.com/feh.png`
6760
	 *  - Domain root relative URLs `/feh.png`
6761
	 *
6762
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6763
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6764
	 *
6765
	 * @return mixed|string
6766
	 */
6767
	public static function absolutize_css_urls( $css, $css_file_url ) {
6768
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6769
		$css_dir = dirname( $css_file_url );
6770
		$p       = wp_parse_url( $css_dir );
6771
		$domain  = sprintf(
6772
			'%1$s//%2$s%3$s%4$s',
6773
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6774
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6775
			$p['host'],
6776
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6777
		);
6778
6779
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6780
			$find = $replace = array();
6781
			foreach ( $matches as $match ) {
6782
				$url = trim( $match['path'], "'\" \t" );
6783
6784
				// If this is a data url, we don't want to mess with it.
6785
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6786
					continue;
6787
				}
6788
6789
				// If this is an absolute or protocol-agnostic url,
6790
				// we don't want to mess with it.
6791
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6792
					continue;
6793
				}
6794
6795
				switch ( substr( $url, 0, 1 ) ) {
6796
					case '/':
6797
						$absolute = $domain . $url;
6798
						break;
6799
					default:
6800
						$absolute = $css_dir . '/' . $url;
6801
				}
6802
6803
				$find[]    = $match[0];
6804
				$replace[] = sprintf( 'url("%s")', $absolute );
6805
			}
6806
			$css = str_replace( $find, $replace, $css );
6807
		}
6808
6809
		return $css;
6810
	}
6811
6812
	/**
6813
	 * This methods removes all of the registered css files on the front end
6814
	 * from Jetpack in favor of using a single file. In effect "imploding"
6815
	 * all the files into one file.
6816
	 *
6817
	 * Pros:
6818
	 * - Uses only ONE css asset connection instead of 15
6819
	 * - Saves a minimum of 56k
6820
	 * - Reduces server load
6821
	 * - Reduces time to first painted byte
6822
	 *
6823
	 * Cons:
6824
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6825
	 *      should not cause any issues with themes.
6826
	 * - Plugins/themes dequeuing styles no longer do anything. See
6827
	 *      jetpack_implode_frontend_css filter for a workaround
6828
	 *
6829
	 * For some situations developers may wish to disable css imploding and
6830
	 * instead operate in legacy mode where each file loads seperately and
6831
	 * can be edited individually or dequeued. This can be accomplished with
6832
	 * the following line:
6833
	 *
6834
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6835
	 *
6836
	 * @since 3.2
6837
	 **/
6838
	public function implode_frontend_css( $travis_test = false ) {
6839
		$do_implode = true;
6840
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6841
			$do_implode = false;
6842
		}
6843
6844
		// Do not implode CSS when the page loads via the AMP plugin.
6845
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6846
			$do_implode = false;
6847
		}
6848
6849
		/**
6850
		 * Allow CSS to be concatenated into a single jetpack.css file.
6851
		 *
6852
		 * @since 3.2.0
6853
		 *
6854
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6855
		 */
6856
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6857
6858
		// Do not use the imploded file when default behavior was altered through the filter
6859
		if ( ! $do_implode ) {
6860
			return;
6861
		}
6862
6863
		// We do not want to use the imploded file in dev mode, or if not connected
6864
		if ( ( new Status() )->is_offline_mode() || ! self::is_active() ) {
6865
			if ( ! $travis_test ) {
6866
				return;
6867
			}
6868
		}
6869
6870
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6871
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6872
			return;
6873
		}
6874
6875
		/*
6876
		 * Now we assume Jetpack is connected and able to serve the single
6877
		 * file.
6878
		 *
6879
		 * In the future there will be a check here to serve the file locally
6880
		 * or potentially from the Jetpack CDN
6881
		 *
6882
		 * For now:
6883
		 * - Enqueue a single imploded css file
6884
		 * - Zero out the style_loader_tag for the bundled ones
6885
		 * - Be happy, drink scotch
6886
		 */
6887
6888
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6889
6890
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6891
6892
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6893
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6894
	}
6895
6896
	function concat_remove_style_loader_tag( $tag, $handle ) {
6897
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6898
			$tag = '';
6899
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6900
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6901
			}
6902
		}
6903
6904
		return $tag;
6905
	}
6906
6907
	/**
6908
	 * @deprecated
6909
	 * @see Automattic\Jetpack\Assets\add_aync_script
6910
	 */
6911
	public function script_add_async( $tag, $handle, $src ) {
6912
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6913
	}
6914
6915
	/*
6916
	 * Check the heartbeat data
6917
	 *
6918
	 * Organizes the heartbeat data by severity.  For example, if the site
6919
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6920
	 *
6921
	 * Data will be added to "caution" array, if it either:
6922
	 *  - Out of date Jetpack version
6923
	 *  - Out of date WP version
6924
	 *  - Out of date PHP version
6925
	 *
6926
	 * $return array $filtered_data
6927
	 */
6928
	public static function jetpack_check_heartbeat_data() {
6929
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6930
6931
		$good    = array();
6932
		$caution = array();
6933
		$bad     = array();
6934
6935
		foreach ( $raw_data as $stat => $value ) {
6936
6937
			// Check jetpack version
6938
			if ( 'version' == $stat ) {
6939
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6940
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6941
					continue;
6942
				}
6943
			}
6944
6945
			// Check WP version
6946
			if ( 'wp-version' == $stat ) {
6947
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6948
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6949
					continue;
6950
				}
6951
			}
6952
6953
			// Check PHP version
6954
			if ( 'php-version' == $stat ) {
6955
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6956
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6957
					continue;
6958
				}
6959
			}
6960
6961
			// Check ID crisis
6962
			if ( 'identitycrisis' == $stat ) {
6963
				if ( 'yes' == $value ) {
6964
					$bad[ $stat ] = $value;
6965
					continue;
6966
				}
6967
			}
6968
6969
			// The rest are good :)
6970
			$good[ $stat ] = $value;
6971
		}
6972
6973
		$filtered_data = array(
6974
			'good'    => $good,
6975
			'caution' => $caution,
6976
			'bad'     => $bad,
6977
		);
6978
6979
		return $filtered_data;
6980
	}
6981
6982
	/*
6983
	 * This method is used to organize all options that can be reset
6984
	 * without disconnecting Jetpack.
6985
	 *
6986
	 * It is used in class.jetpack-cli.php to reset options
6987
	 *
6988
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6989
	 *
6990
	 * @return array of options to delete.
6991
	 */
6992
	public static function get_jetpack_options_for_reset() {
6993
		return Jetpack_Options::get_options_for_reset();
6994
	}
6995
6996
	/*
6997
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6998
	 * so we can bring them directly to their site in calypso.
6999
	 *
7000
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
7001
	 *
7002
	 * @param string | url
7003
	 * @return string | url without the guff
7004
	 */
7005
	public static function build_raw_urls( $url ) {
7006
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
7007
7008
		return ( new Status() )->get_site_suffix( $url );
7009
	}
7010
7011
	/**
7012
	 * Stores and prints out domains to prefetch for page speed optimization.
7013
	 *
7014
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
7015
	 *
7016
	 * @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...
7017
	 */
7018
	public static function dns_prefetch( $urls = null ) {
7019
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
7020
		if ( $urls ) {
7021
			Assets::add_resource_hint( $urls );
7022
		}
7023
	}
7024
7025
	public function wp_dashboard_setup() {
7026
		if ( self::is_active() ) {
7027
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
7028
		}
7029
7030
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
7031
			$jetpack_logo = new Jetpack_Logo();
7032
			$widget_title = sprintf(
7033
				/* translators: Placeholder is a Jetpack logo. */
7034
				__( 'Stats by %s', 'jetpack' ),
7035
				$jetpack_logo->get_jp_emblem( true )
7036
			);
7037
7038
			// Wrap title in span so Logo can be properly styled.
7039
			$widget_title = sprintf(
7040
				'<span>%s</span>',
7041
				$widget_title
7042
			);
7043
7044
			wp_add_dashboard_widget(
7045
				'jetpack_summary_widget',
7046
				$widget_title,
7047
				array( __CLASS__, 'dashboard_widget' )
7048
			);
7049
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
7050
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
7051
7052
			// If we're inactive and not in offline mode, sort our box to the top.
7053
			if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
7054
				global $wp_meta_boxes;
7055
7056
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7057
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7058
7059
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7060
			}
7061
		}
7062
	}
7063
7064
	/**
7065
	 * @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...
7066
	 * @return mixed
7067
	 */
7068
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7069
		if ( ! is_array( $sorted ) ) {
7070
			return $sorted;
7071
		}
7072
7073
		foreach ( $sorted as $box_context => $ids ) {
7074
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7075
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7076
				continue;
7077
			}
7078
7079
			$ids_array = explode( ',', $ids );
7080
			$key       = array_search( 'dashboard_stats', $ids_array );
7081
7082
			if ( false !== $key ) {
7083
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7084
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7085
				$sorted[ $box_context ] = implode( ',', $ids_array );
7086
				// We've found it, stop searching, and just return.
7087
				break;
7088
			}
7089
		}
7090
7091
		return $sorted;
7092
	}
7093
7094
	public static function dashboard_widget() {
7095
		/**
7096
		 * Fires when the dashboard is loaded.
7097
		 *
7098
		 * @since 3.4.0
7099
		 */
7100
		do_action( 'jetpack_dashboard_widget' );
7101
	}
7102
7103
	public static function dashboard_widget_footer() {
7104
		?>
7105
		<footer>
7106
7107
		<div class="protect">
7108
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7109
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7110
				<p class="blocked-count">
7111
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7112
				</p>
7113
				<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>
7114
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7115
				<a href="
7116
				<?php
7117
				echo esc_url(
7118
					wp_nonce_url(
7119
						self::admin_url(
7120
							array(
7121
								'action' => 'activate',
7122
								'module' => 'protect',
7123
							)
7124
						),
7125
						'jetpack_activate-protect'
7126
					)
7127
				);
7128
				?>
7129
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7130
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7131
				</a>
7132
			<?php else : ?>
7133
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7134
			<?php endif; ?>
7135
		</div>
7136
7137
		<div class="akismet">
7138
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7139
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7140
				<p class="blocked-count">
7141
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7142
				</p>
7143
				<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>
7144
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7145
				<a href="
7146
				<?php
7147
				echo esc_url(
7148
					wp_nonce_url(
7149
						add_query_arg(
7150
							array(
7151
								'action' => 'activate',
7152
								'plugin' => 'akismet/akismet.php',
7153
							),
7154
							admin_url( 'plugins.php' )
7155
						),
7156
						'activate-plugin_akismet/akismet.php'
7157
					)
7158
				);
7159
				?>
7160
							" class="button button-jetpack">
7161
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7162
				</a>
7163
			<?php else : ?>
7164
				<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>
7165
			<?php endif; ?>
7166
		</div>
7167
7168
		</footer>
7169
		<?php
7170
	}
7171
7172
	/*
7173
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7174
	 */
7175
	function jetpack_icon_user_connected( $columns ) {
7176
		$columns['user_jetpack'] = '';
7177
		return $columns;
7178
	}
7179
7180
	/*
7181
	 * Show Jetpack icon if the user is linked.
7182
	 */
7183
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7184
		if ( 'user_jetpack' === $col && self::connection()->is_user_connected( $user_id ) ) {
7185
			$jetpack_logo = new Jetpack_Logo();
7186
			$emblem_html  = sprintf(
7187
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7188
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7189
				$jetpack_logo->get_jp_emblem()
7190
			);
7191
			return $emblem_html;
7192
		}
7193
7194
		return $val;
7195
	}
7196
7197
	/*
7198
	 * Style the Jetpack user column
7199
	 */
7200
	function jetpack_user_col_style() {
7201
		global $current_screen;
7202
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7203
			?>
7204
			<style>
7205
				.fixed .column-user_jetpack {
7206
					width: 21px;
7207
				}
7208
				.jp-emblem-user-admin svg {
7209
					width: 20px;
7210
					height: 20px;
7211
				}
7212
				.jp-emblem-user-admin path {
7213
					fill: #00BE28;
7214
				}
7215
			</style>
7216
			<?php
7217
		}
7218
	}
7219
7220
	/**
7221
	 * Checks if Akismet is active and working.
7222
	 *
7223
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7224
	 * that implied usage of methods present since more recent version.
7225
	 * See https://github.com/Automattic/jetpack/pull/9585
7226
	 *
7227
	 * @since  5.1.0
7228
	 *
7229
	 * @return bool True = Akismet available. False = Aksimet not available.
7230
	 */
7231
	public static function is_akismet_active() {
7232
		static $status = null;
7233
7234
		if ( ! is_null( $status ) ) {
7235
			return $status;
7236
		}
7237
7238
		// Check if a modern version of Akismet is active.
7239
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7240
			$status = false;
7241
			return $status;
7242
		}
7243
7244
		// Make sure there is a key known to Akismet at all before verifying key.
7245
		$akismet_key = Akismet::get_api_key();
7246
		if ( ! $akismet_key ) {
7247
			$status = false;
7248
			return $status;
7249
		}
7250
7251
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7252
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7253
7254
		// 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.
7255
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7256
		// We cache the result of the Akismet key verification for ten minutes.
7257
		if ( ! $akismet_key_state || $recheck ) {
7258
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7259
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7260
		}
7261
7262
		$status = 'valid' === $akismet_key_state;
7263
7264
		return $status;
7265
	}
7266
7267
	/**
7268
	 * @deprecated
7269
	 *
7270
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7271
	 */
7272
	public static function is_function_in_backtrace() {
7273
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7274
	}
7275
7276
	/**
7277
	 * Given a minified path, and a non-minified path, will return
7278
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7279
	 *
7280
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7281
	 * root Jetpack directory.
7282
	 *
7283
	 * @since 5.6.0
7284
	 *
7285
	 * @param string $min_path
7286
	 * @param string $non_min_path
7287
	 * @return string The URL to the file
7288
	 */
7289
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7290
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7291
	}
7292
7293
	/**
7294
	 * Checks for whether Jetpack Backup is enabled.
7295
	 * Will return true if the state of Backup is anything except "unavailable".
7296
	 *
7297
	 * @return bool|int|mixed
7298
	 */
7299
	public static function is_rewind_enabled() {
7300
		if ( ! self::is_active() ) {
7301
			return false;
7302
		}
7303
7304
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7305
		if ( false === $rewind_enabled ) {
7306
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7307
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7308
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7309
				&& ! empty( $rewind_data['state'] )
7310
				&& 'active' === $rewind_data['state'] )
7311
				? 1
7312
				: 0;
7313
7314
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7315
		}
7316
		return $rewind_enabled;
7317
	}
7318
7319
	/**
7320
	 * Return Calypso environment value; used for developing Jetpack and pairing
7321
	 * it with different Calypso enrionments, such as localhost.
7322
	 *
7323
	 * @since 7.4.0
7324
	 *
7325
	 * @return string Calypso environment
7326
	 */
7327
	public static function get_calypso_env() {
7328
		if ( isset( $_GET['calypso_env'] ) ) {
7329
			return sanitize_key( $_GET['calypso_env'] );
7330
		}
7331
7332
		if ( getenv( 'CALYPSO_ENV' ) ) {
7333
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7334
		}
7335
7336
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7337
			return sanitize_key( CALYPSO_ENV );
7338
		}
7339
7340
		return '';
7341
	}
7342
7343
	/**
7344
	 * Returns the hostname with protocol for Calypso.
7345
	 * Used for developing Jetpack with Calypso.
7346
	 *
7347
	 * @since 8.4.0
7348
	 *
7349
	 * @return string Calypso host.
7350
	 */
7351
	public static function get_calypso_host() {
7352
		$calypso_env = self::get_calypso_env();
7353
		switch ( $calypso_env ) {
7354
			case 'development':
7355
				return 'http://calypso.localhost:3000/';
7356
			case 'wpcalypso':
7357
				return 'https://wpcalypso.wordpress.com/';
7358
			case 'horizon':
7359
				return 'https://horizon.wordpress.com/';
7360
			default:
7361
				return 'https://wordpress.com/';
7362
		}
7363
	}
7364
7365
	/**
7366
	 * Handles activating default modules as well general cleanup for the new connection.
7367
	 *
7368
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7369
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7370
	 * @param boolean $send_state_messages          Whether to send state messages.
7371
	 * @return void
7372
	 */
7373
	public static function handle_post_authorization_actions(
7374
		$activate_sso = false,
7375
		$redirect_on_activation_error = false,
7376
		$send_state_messages = true
7377
	) {
7378
		$other_modules = $activate_sso
7379
			? array( 'sso' )
7380
			: array();
7381
7382
		if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
7383
			$active_modules = Jetpack_Options::get_option( 'active_modules' );
7384
			self::delete_active_modules();
7385
7386
			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...
7387
		} else {
7388
			// Default modules that don't require a user were already activated on site_register.
7389
			// 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.
7390
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
7391
			Jetpack_Options::update_option( 'active_modules_initialized', true );
7392
		}
7393
7394
		// Since this is a fresh connection, be sure to clear out IDC options
7395
		Jetpack_IDC::clear_all_idc_options();
7396
7397
		if ( $send_state_messages ) {
7398
			self::state( 'message', 'authorized' );
7399
		}
7400
	}
7401
7402
	/**
7403
	 * Returns a boolean for whether backups UI should be displayed or not.
7404
	 *
7405
	 * @return bool Should backups UI be displayed?
7406
	 */
7407
	public static function show_backups_ui() {
7408
		/**
7409
		 * Whether UI for backups should be displayed.
7410
		 *
7411
		 * @since 6.5.0
7412
		 *
7413
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7414
		 */
7415
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7416
	}
7417
7418
	/*
7419
	 * Deprecated manage functions
7420
	 */
7421
	function prepare_manage_jetpack_notice() {
7422
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7423
	}
7424
	function manage_activate_screen() {
7425
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7426
	}
7427
	function admin_jetpack_manage_notice() {
7428
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7429
	}
7430
	function opt_out_jetpack_manage_url() {
7431
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7432
	}
7433
	function opt_in_jetpack_manage_url() {
7434
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7435
	}
7436
	function opt_in_jetpack_manage_notice() {
7437
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7438
	}
7439
	function can_display_jetpack_manage_notice() {
7440
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7441
	}
7442
7443
	/**
7444
	 * Clean leftoveruser meta.
7445
	 *
7446
	 * Delete Jetpack-related user meta when it is no longer needed.
7447
	 *
7448
	 * @since 7.3.0
7449
	 *
7450
	 * @param int $user_id User ID being updated.
7451
	 */
7452
	public static function user_meta_cleanup( $user_id ) {
7453
		$meta_keys = array(
7454
			// AtD removed from Jetpack 7.3
7455
			'AtD_options',
7456
			'AtD_check_when',
7457
			'AtD_guess_lang',
7458
			'AtD_ignored_phrases',
7459
		);
7460
7461
		foreach ( $meta_keys as $meta_key ) {
7462
			if ( get_user_meta( $user_id, $meta_key ) ) {
7463
				delete_user_meta( $user_id, $meta_key );
7464
			}
7465
		}
7466
	}
7467
7468
	/**
7469
	 * Checks if a Jetpack site is both active and not in offline mode.
7470
	 *
7471
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7472
	 *
7473
	 * @deprecated 8.8.0
7474
	 *
7475
	 * @return bool True if Jetpack is active and not in offline mode.
7476
	 */
7477
	public static function is_active_and_not_development_mode() {
7478
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7479
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7480
			return false;
7481
		}
7482
		return true;
7483
	}
7484
7485
	/**
7486
	 * Checks if a Jetpack site is both active and not in offline mode.
7487
	 *
7488
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7489
	 *
7490
	 * @since 8.8.0
7491
	 *
7492
	 * @return bool True if Jetpack is active and not in offline mode.
7493
	 */
7494
	public static function is_active_and_not_offline_mode() {
7495
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7496
			return false;
7497
		}
7498
		return true;
7499
	}
7500
7501
	/**
7502
	 * Returns the list of products that we have available for purchase.
7503
	 */
7504
	public static function get_products_for_purchase() {
7505
		$products = array();
7506
		if ( ! is_multisite() ) {
7507
			$products[] = array(
7508
				'key'               => 'backup',
7509
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7510
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7511
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7512
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7513
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7514
				'options'           => array(
7515
					array(
7516
						'type'        => 'daily',
7517
						'slug'        => 'jetpack-backup-daily',
7518
						'key'         => 'jetpack_backup_daily',
7519
						'name'        => __( 'Daily Backups', 'jetpack' ),
7520
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7521
					),
7522
					array(
7523
						'type'        => 'realtime',
7524
						'slug'        => 'jetpack-backup-realtime',
7525
						'key'         => 'jetpack_backup_realtime',
7526
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7527
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7528
					),
7529
				),
7530
				'default_option'    => 'realtime',
7531
				'show_promotion'    => true,
7532
				'discount_percent'  => 70,
7533
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7534
			);
7535
7536
			$products[] = array(
7537
				'key'               => 'scan',
7538
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7539
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7540
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7541
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7542
				'show_promotion'    => true,
7543
				'discount_percent'  => 30,
7544
				'options'           => array(
7545
					array(
7546
						'type' => 'scan',
7547
						'slug' => 'jetpack-scan',
7548
						'key'  => 'jetpack_scan',
7549
						'name' => __( 'Daily Scan', 'jetpack' ),
7550
					),
7551
				),
7552
				'default_option'    => 'scan',
7553
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7554
			);
7555
		}
7556
7557
		$products[] = array(
7558
			'key'               => 'search',
7559
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7560
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7561
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7562
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7563
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7564
			'options'           => array(
7565
				array(
7566
					'type' => 'search',
7567
					'slug' => 'jetpack-search',
7568
					'key'  => 'jetpack_search',
7569
					'name' => __( 'Search', 'jetpack' ),
7570
				),
7571
			),
7572
			'tears'             => array(),
7573
			'default_option'    => 'search',
7574
			'show_promotion'    => false,
7575
			'included_in_plans' => array( 'search-plan' ),
7576
		);
7577
7578
		$products[] = array(
7579
			'key'               => 'anti-spam',
7580
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7581
			'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' ),
7582
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7583
			'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' ),
7584
			'options'           => array(
7585
				array(
7586
					'type' => 'anti-spam',
7587
					'slug' => 'jetpack-anti-spam',
7588
					'key'  => 'jetpack_anti_spam',
7589
					'name' => __( 'Anti-Spam', 'jetpack' ),
7590
				),
7591
			),
7592
			'default_option'    => 'anti-spam',
7593
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7594
		);
7595
7596
		return $products;
7597
	}
7598
}
7599