Completed
Push — update/use-identity-crisis-pac... ( cd5680...a99a98 )
by
unknown
30:03 queued 19:36
created

Jetpack::admin_banner_styles()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 21

Duplication

Lines 8
Ratio 38.1 %

Importance

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

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

Loading history...
558
	 */
559
	static function update_active_modules( $modules ) {
560
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
561
		$active_modules       = self::get_active_modules();
562
		$new_active_modules   = array_diff( $modules, $current_modules );
563
		$new_inactive_modules = array_diff( $active_modules, $modules );
564
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
565
		$reindexed_modules    = array_values( $new_current_modules );
566
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
567
568
		foreach ( $new_active_modules as $module ) {
569
			/**
570
			 * Fires when a specific module is activated.
571
			 *
572
			 * @since 1.9.0
573
			 *
574
			 * @param string $module Module slug.
575
			 * @param boolean $success whether the module was activated. @since 4.2
576
			 */
577
			do_action( 'jetpack_activate_module', $module, $success );
578
			/**
579
			 * Fires when a module is activated.
580
			 * The dynamic part of the filter, $module, is the module slug.
581
			 *
582
			 * @since 1.9.0
583
			 *
584
			 * @param string $module Module slug.
585
			 */
586
			do_action( "jetpack_activate_module_$module", $module );
587
		}
588
589
		foreach ( $new_inactive_modules as $module ) {
590
			/**
591
			 * Fired after a module has been deactivated.
592
			 *
593
			 * @since 4.2.0
594
			 *
595
			 * @param string $module Module slug.
596
			 * @param boolean $success whether the module was deactivated.
597
			 */
598
			do_action( 'jetpack_deactivate_module', $module, $success );
599
			/**
600
			 * Fires when a module is deactivated.
601
			 * The dynamic part of the filter, $module, is the module slug.
602
			 *
603
			 * @since 1.9.0
604
			 *
605
			 * @param string $module Module slug.
606
			 */
607
			do_action( "jetpack_deactivate_module_$module", $module );
608
		}
609
610
		return $success;
611
	}
612
613
	static function delete_active_modules() {
614
		self::update_active_modules( array() );
615
	}
616
617
	/**
618
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
619
	 * available.
620
	 */
621
	public function add_configure_hook() {
622
		global $wp_filter;
623
624
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
625
		if ( false !== $current_priority ) {
626
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
627
		}
628
629
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
630
		sort( $taken_priorities );
631
632
		$first_priority = array_shift( $taken_priorities );
633
634
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
635
			$new_priority = - PHP_INT_MAX;
636
		} else {
637
			$new_priority = $first_priority - 1;
638
		}
639
640
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
641
	}
642
643
	/**
644
	 * Constructor.  Initializes WordPress hooks
645
	 */
646
	private function __construct() {
647
		/*
648
		 * Check for and alert any deprecated hooks
649
		 */
650
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
651
652
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
653
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
654
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
655
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
656
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
657
658
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
659
660
		add_filter(
661
			'jetpack_signature_check_token',
662
			array( __CLASS__, 'verify_onboarding_token' ),
663
			10,
664
			3
665
		);
666
667
		/**
668
		 * Prepare Gutenberg Editor functionality
669
		 */
670
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
671
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
672
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
673
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
674
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
675
676
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
677
678
		// Unlink user before deleting the user from WP.com.
679
		add_action( 'deleted_user', array( $this, 'disconnect_user' ), 10, 1 );
680
		add_action( 'remove_user_from_blog', array( $this, 'disconnect_user' ), 10, 1 );
681
682
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
683
684
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
685
		add_action( 'login_init', array( $this, 'login_init' ) );
686
687
		// Set up the REST authentication hooks.
688
		Connection_Rest_Authentication::init();
689
690
		add_action( 'admin_init', array( $this, 'admin_init' ) );
691
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
692
693
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
694
695
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
696
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
697
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
698
699
		// returns HTTPS support status
700
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
701
702
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
703
704
		add_action( 'wp_ajax_jetpack_recommendations_banner', array( 'Jetpack_Recommendations_Banner', 'ajax_callback' ) );
705
706
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
707
708
		/**
709
		 * These actions run checks to load additional files.
710
		 * They check for external files or plugins, so they need to run as late as possible.
711
		 */
712
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
713
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
714
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
715
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
716
717
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
718
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
719
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
720
721
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
722
723
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
724
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
725
726
		// A filter to control all just in time messages
727
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
728
729
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
730
731
		require_once JETPACK__PLUGIN_DIR . 'class-jetpack-pre-connection-jitms.php';
732
		$jetpack_jitm_messages = ( new Jetpack_Pre_Connection_JITMs() );
733
		add_filter( 'jetpack_pre_connection_jitms', array( $jetpack_jitm_messages, 'add_pre_connection_jitms' ) );
734
735
		/*
736
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
737
		 * We should make sure to only do this for front end links.
738
		 */
739
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
740
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
741
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
742
743
			/*
744
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
745
			 * so they point moderation links on emails to Calypso.
746
			 */
747
			jetpack_require_lib( 'functions.wp-notify' );
748
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
749
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
750
		}
751
752
		add_action(
753
			'plugins_loaded',
754
			function () {
755
				if ( User_Agent_Info::is_mobile_app() ) {
756
					add_filter( 'get_edit_post_link', '__return_empty_string' );
757
				}
758
			}
759
		);
760
761
		// Update the site's Jetpack plan and products from API on heartbeats.
762
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
763
764
		/**
765
		 * This is the hack to concatenate all css files into one.
766
		 * For description and reasoning see the implode_frontend_css method.
767
		 *
768
		 * Super late priority so we catch all the registered styles.
769
		 */
770
		if ( ! is_admin() ) {
771
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
772
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
773
		}
774
775
		/**
776
		 * These are sync actions that we need to keep track of for jitms
777
		 */
778
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
779
780
		// Actually push the stats on shutdown.
781
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
782
			add_action( 'shutdown', array( $this, 'push_stats' ) );
783
		}
784
785
		// After a successful connection.
786
		add_action( 'jetpack_site_registered', array( $this, 'activate_default_modules_on_site_register' ) );
787
788
		// Actions for Manager::authorize().
789
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
790
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
791
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
792
793
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
794
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
795
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
796
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
797
798
		// Filters for the Manager::get_token() urls and request body.
799
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
800
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
801
802
		// Actions for successful reconnect.
803
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
804
805
		// Actions for licensing.
806
		Licensing::instance()->initialize();
807
808
		// Filters for Sync Callables.
809
		add_filter( 'jetpack_sync_callable_whitelist', array( $this, 'filter_sync_callable_whitelist' ), 10, 1 );
810
		add_filter( 'jetpack_sync_multisite_callable_whitelist', array( $this, 'filter_sync_multisite_callable_whitelist' ), 10, 1 );
811
812
		// Make resources use static domain when possible.
813
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
814
	}
815
816
	/**
817
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
818
	 * Config object.
819
	 */
820
	public function configure() {
821
		$config = new Config();
822
823
		foreach (
824
			array(
825
				'sync',
826
				'jitm',
827
			)
828
			as $feature
829
		) {
830
			$config->ensure( $feature );
831
		}
832
833
		$config->ensure(
834
			'connection',
835
			array(
836
				'slug' => 'jetpack',
837
				'name' => 'Jetpack',
838
			)
839
		);
840
841
		if ( ! $this->connection_manager ) {
842
			$this->connection_manager = new Connection_Manager( 'jetpack' );
843
844
			/**
845
			 * Filter to activate Jetpack Connection UI.
846
			 * INTERNAL USE ONLY.
847
			 *
848
			 * @since 9.5.0
849
			 *
850
			 * @param bool false Whether to activate the Connection UI.
851
			 */
852
			if ( apply_filters( 'jetpack_connection_ui_active', false ) ) {
853
				Automattic\Jetpack\ConnectionUI\Admin::init();
854
			}
855
		}
856
857
		/*
858
		 * Load things that should only be in Network Admin.
859
		 *
860
		 * For now blow away everything else until a more full
861
		 * understanding of what is needed at the network level is
862
		 * available
863
		 */
864
		if ( is_multisite() ) {
865
			$network = Jetpack_Network::init();
866
			$network->set_connection( $this->connection_manager );
867
		}
868
869
		if ( self::is_connection_ready() ) {
870
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
871
872
			Jetpack_Heartbeat::init();
873
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
874
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
875
				Jetpack_Search_Performance_Logger::init();
876
			}
877
		}
878
879
		// Initialize remote file upload request handlers.
880
		$this->add_remote_request_handlers();
881
882
		/*
883
		 * Enable enhanced handling of previewing sites in Calypso
884
		 */
885
		if ( self::is_connection_ready() ) {
886
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
887
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
888
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
889
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
890
		}
891
892
		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...
893
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
894
		} else {
895
			/**
896
			 * Initialize tracking right after the user agrees to the terms of service.
897
			 */
898
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
899
		}
900
	}
901
902
	/**
903
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
904
	 * initialization code.
905
	 *
906
	 * @action plugins_loaded
907
	 */
908
	public function late_initialization() {
909
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
910
911
		Partner::init();
912
913
		/**
914
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
915
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
916
		 *
917
		 * @since 8.1.0
918
		 *
919
		 * @param Jetpack $jetpack the main plugin class object.
920
		 */
921
		do_action( 'jetpack_loaded', $this );
922
923
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
924
	}
925
926
	/**
927
	 * Sets up the XMLRPC request handlers.
928
	 *
929
	 * @deprecated since 7.7.0
930
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
931
	 *
932
	 * @param array                 $request_params Incoming request parameters.
933
	 * @param Boolean               $is_active      Whether the connection is currently active.
934
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
935
	 * @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...
936
	 */
937 View Code Duplication
	public function setup_xmlrpc_handlers(
938
		$request_params,
939
		$is_active,
940
		$is_signed,
941
		Jetpack_XMLRPC_Server $xmlrpc_server = null
942
	) {
943
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
944
945
		if ( ! $this->connection_manager ) {
946
			$this->connection_manager = new Connection_Manager();
947
		}
948
949
		return $this->connection_manager->setup_xmlrpc_handlers(
950
			$request_params,
951
			$is_active,
952
			$is_signed,
953
			$xmlrpc_server
954
		);
955
	}
956
957
	/**
958
	 * Initialize REST API registration connector.
959
	 *
960
	 * @deprecated since 7.7.0
961
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
962
	 */
963 View Code Duplication
	public function initialize_rest_api_registration_connector() {
964
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
965
966
		if ( ! $this->connection_manager ) {
967
			$this->connection_manager = new Connection_Manager();
968
		}
969
970
		$this->connection_manager->initialize_rest_api_registration_connector();
971
	}
972
973
	/**
974
	 * This is ported over from the manage module, which has been deprecated and baked in here.
975
	 *
976
	 * @param $domains
977
	 */
978
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
979
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
980
	}
981
982
	/**
983
	 * Return $domains, with 'wordpress.com' appended.
984
	 * This is ported over from the manage module, which has been deprecated and baked in here.
985
	 *
986
	 * @param $domains
987
	 * @return array
988
	 */
989
	function allow_wpcom_domain( $domains ) {
990
		if ( empty( $domains ) ) {
991
			$domains = array();
992
		}
993
		$domains[] = 'wordpress.com';
994
		return array_unique( $domains );
995
	}
996
997
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
998
		$post = get_post( $post_id );
999
1000
		if ( empty( $post ) ) {
1001
			return $default_url;
1002
		}
1003
1004
		$post_type = $post->post_type;
1005
1006
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1007
		// https://en.support.wordpress.com/custom-post-types/
1008
		$allowed_post_types = array(
1009
			'post',
1010
			'page',
1011
			'jetpack-portfolio',
1012
			'jetpack-testimonial',
1013
		);
1014
1015
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1016
			return $default_url;
1017
		}
1018
1019
		return Redirect::get_url(
1020
			'calypso-edit-' . $post_type,
1021
			array(
1022
				'path' => $post_id,
1023
			)
1024
		);
1025
	}
1026
1027
	function point_edit_comment_links_to_calypso( $url ) {
1028
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1029
		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...
1030
1031
		return Redirect::get_url(
1032
			'calypso-edit-comment',
1033
			array(
1034
				'path' => $query_args['amp;c'],
1035
			)
1036
		);
1037
1038
	}
1039
1040
	/**
1041
	 * Extend Sync callables with Jetpack Plugin functions.
1042
	 *
1043
	 * @param array $callables list of callables.
1044
	 *
1045
	 * @return array list of callables.
1046
	 */
1047
	public function filter_sync_callable_whitelist( $callables ) {
1048
1049
		// Jetpack Functions.
1050
		$jetpack_callables = array(
1051
			'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
1052
			'updates'                  => array( 'Jetpack', 'get_updates' ),
1053
			'active_modules'           => array( 'Jetpack', 'get_active_modules' ),
1054
			'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1055
		);
1056
		$callables         = array_merge( $callables, $jetpack_callables );
1057
1058
		// Jetpack_SSO_Helpers.
1059
		if ( include_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' ) {
1060
			$sso_helpers = array(
1061
				'sso_is_two_step_required'      => array( 'Jetpack_SSO_Helpers', 'is_two_step_required' ),
1062
				'sso_should_hide_login_form'    => array( 'Jetpack_SSO_Helpers', 'should_hide_login_form' ),
1063
				'sso_match_by_email'            => array( 'Jetpack_SSO_Helpers', 'match_by_email' ),
1064
				'sso_new_user_override'         => array( 'Jetpack_SSO_Helpers', 'new_user_override' ),
1065
				'sso_bypass_default_login_form' => array( 'Jetpack_SSO_Helpers', 'bypass_login_forward_wpcom' ),
1066
			);
1067
			$callables   = array_merge( $callables, $sso_helpers );
1068
		}
1069
1070
		return $callables;
1071
	}
1072
1073
	/**
1074
	 * Extend Sync multisite callables with Jetpack Plugin functions.
1075
	 *
1076
	 * @param array $callables list of callables.
1077
	 *
1078
	 * @return array list of callables.
1079
	 */
1080
	public function filter_sync_multisite_callable_whitelist( $callables ) {
1081
1082
		// Jetpack Funtions.
1083
		$jetpack_multisite_callables = array(
1084
			'network_name'                        => array( 'Jetpack', 'network_name' ),
1085
			'network_allow_new_registrations'     => array( 'Jetpack', 'network_allow_new_registrations' ),
1086
			'network_add_new_users'               => array( 'Jetpack', 'network_add_new_users' ),
1087
			'network_site_upload_space'           => array( 'Jetpack', 'network_site_upload_space' ),
1088
			'network_upload_file_types'           => array( 'Jetpack', 'network_upload_file_types' ),
1089
			'network_enable_administration_menus' => array( 'Jetpack', 'network_enable_administration_menus' ),
1090
		);
1091
		$callables                   = array_merge( $callables, $jetpack_multisite_callables );
1092
1093
		return $callables;
1094
	}
1095
1096
	function jetpack_track_last_sync_callback( $params ) {
1097
		/**
1098
		 * Filter to turn off jitm caching
1099
		 *
1100
		 * @since 5.4.0
1101
		 *
1102
		 * @param bool false Whether to cache just in time messages
1103
		 */
1104
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1105
			return $params;
1106
		}
1107
1108
		if ( is_array( $params ) && isset( $params[0] ) ) {
1109
			$option = $params[0];
1110
			if ( 'active_plugins' === $option ) {
1111
				// use the cache if we can, but not terribly important if it gets evicted
1112
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1113
			}
1114
		}
1115
1116
		return $params;
1117
	}
1118
1119
	function jetpack_connection_banner_callback() {
1120
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1121
1122
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1123
		if (
1124
			isset( $_REQUEST['dismissBanner'] ) &&
1125
			! Jetpack_Connection_Banner::force_display()
1126
		) {
1127
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1128
			wp_send_json_success();
1129
		}
1130
1131
		wp_die();
1132
	}
1133
1134
	/**
1135
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1136
	 * Only used in our alternate XML-RPC endpoint, where we want to
1137
	 * ensure that Core and other plugins' methods are not exposed.
1138
	 *
1139
	 * @deprecated since 7.7.0
1140
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1141
	 *
1142
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1143
	 * @return array Filtered $methods
1144
	 */
1145 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1146
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1147
1148
		if ( ! $this->connection_manager ) {
1149
			$this->connection_manager = new Connection_Manager();
1150
		}
1151
1152
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1153
	}
1154
1155
	/**
1156
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1157
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1158
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1159
	 * which is accessible via a different URI. Most of the below is copied directly
1160
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1161
	 *
1162
	 * @deprecated since 7.7.0
1163
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1164
	 */
1165 View Code Duplication
	public function alternate_xmlrpc() {
1166
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1167
1168
		if ( ! $this->connection_manager ) {
1169
			$this->connection_manager = new Connection_Manager();
1170
		}
1171
1172
		$this->connection_manager->alternate_xmlrpc();
1173
	}
1174
1175
	/**
1176
	 * The callback for the JITM ajax requests.
1177
	 *
1178
	 * @deprecated since 7.9.0
1179
	 */
1180
	function jetpack_jitm_ajax_callback() {
1181
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1182
	}
1183
1184
	/**
1185
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1186
	 */
1187
	function push_stats() {
1188
		if ( ! empty( $this->stats ) ) {
1189
			$this->do_stats( 'server_side' );
1190
		}
1191
	}
1192
1193
	/**
1194
	 * Sets the Jetpack custom capabilities.
1195
	 *
1196
	 * @param string[] $caps    Array of the user's capabilities.
1197
	 * @param string   $cap     Capability name.
1198
	 * @param int      $user_id The user ID.
1199
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1200
	 */
1201
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1202
		switch ( $cap ) {
1203
			case 'jetpack_manage_modules':
1204
			case 'jetpack_activate_modules':
1205
			case 'jetpack_deactivate_modules':
1206
				$caps = array( 'manage_options' );
1207
				break;
1208
			case 'jetpack_configure_modules':
1209
				$caps = array( 'manage_options' );
1210
				break;
1211
			case 'jetpack_manage_autoupdates':
1212
				$caps = array(
1213
					'manage_options',
1214
					'update_plugins',
1215
				);
1216
				break;
1217
			case 'jetpack_network_admin_page':
1218
			case 'jetpack_network_settings_page':
1219
				$caps = array( 'manage_network_plugins' );
1220
				break;
1221
			case 'jetpack_network_sites_page':
1222
				$caps = array( 'manage_sites' );
1223
				break;
1224 View Code Duplication
			case 'jetpack_admin_page':
1225
				$is_offline_mode = ( new Status() )->is_offline_mode();
1226
				if ( $is_offline_mode ) {
1227
					$caps = array( 'manage_options' );
1228
					break;
1229
				} else {
1230
					$caps = array( 'read' );
1231
				}
1232
				break;
1233
		}
1234
		return $caps;
1235
	}
1236
1237
	/**
1238
	 * Require a Jetpack authentication.
1239
	 *
1240
	 * @deprecated since 7.7.0
1241
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1242
	 */
1243 View Code Duplication
	public function require_jetpack_authentication() {
1244
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1245
1246
		if ( ! $this->connection_manager ) {
1247
			$this->connection_manager = new Connection_Manager();
1248
		}
1249
1250
		$this->connection_manager->require_jetpack_authentication();
1251
	}
1252
1253
	/**
1254
	 * Register assets for use in various modules and the Jetpack admin page.
1255
	 *
1256
	 * @uses wp_script_is, wp_register_script, plugins_url
1257
	 * @action wp_loaded
1258
	 * @return null
1259
	 */
1260
	public function register_assets() {
1261 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1262
			wp_register_script(
1263
				'jetpack-gallery-settings',
1264
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1265
				array( 'media-views' ),
1266
				'20121225'
1267
			);
1268
		}
1269
1270
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1271
			wp_register_script(
1272
				'jetpack-twitter-timeline',
1273
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1274
				array( 'jquery' ),
1275
				'4.0.0',
1276
				true
1277
			);
1278
		}
1279
1280
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1281
			wp_register_script(
1282
				'jetpack-facebook-embed',
1283
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1284
				array(),
1285
				null,
1286
				true
1287
			);
1288
1289
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1290
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1291
			if ( ! is_numeric( $fb_app_id ) ) {
1292
				$fb_app_id = '';
1293
			}
1294
			wp_localize_script(
1295
				'jetpack-facebook-embed',
1296
				'jpfbembed',
1297
				array(
1298
					'appid'  => $fb_app_id,
1299
					'locale' => $this->get_locale(),
1300
				)
1301
			);
1302
		}
1303
1304
		/**
1305
		 * As jetpack_register_genericons is by default fired off a hook,
1306
		 * the hook may have already fired by this point.
1307
		 * So, let's just trigger it manually.
1308
		 */
1309
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1310
		jetpack_register_genericons();
1311
1312
		/**
1313
		 * Register the social logos
1314
		 */
1315
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1316
		jetpack_register_social_logos();
1317
1318 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1319
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1320
		}
1321
	}
1322
1323
	/**
1324
	 * Guess locale from language code.
1325
	 *
1326
	 * @param string $lang Language code.
1327
	 * @return string|bool
1328
	 */
1329 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1330
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1331
			return 'en_US';
1332
		}
1333
1334
		if ( ! class_exists( 'GP_Locales' ) ) {
1335
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1336
				return false;
1337
			}
1338
1339
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1340
		}
1341
1342
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1343
			// WP.com: get_locale() returns 'it'
1344
			$locale = GP_Locales::by_slug( $lang );
1345
		} else {
1346
			// Jetpack: get_locale() returns 'it_IT';
1347
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1348
		}
1349
1350
		if ( ! $locale ) {
1351
			return false;
1352
		}
1353
1354
		if ( empty( $locale->facebook_locale ) ) {
1355
			if ( empty( $locale->wp_locale ) ) {
1356
				return false;
1357
			} else {
1358
				// Facebook SDK is smart enough to fall back to en_US if a
1359
				// locale isn't supported. Since supported Facebook locales
1360
				// can fall out of sync, we'll attempt to use the known
1361
				// wp_locale value and rely on said fallback.
1362
				return $locale->wp_locale;
1363
			}
1364
		}
1365
1366
		return $locale->facebook_locale;
1367
	}
1368
1369
	/**
1370
	 * Get the locale.
1371
	 *
1372
	 * @return string|bool
1373
	 */
1374
	function get_locale() {
1375
		$locale = $this->guess_locale_from_lang( get_locale() );
1376
1377
		if ( ! $locale ) {
1378
			$locale = 'en_US';
1379
		}
1380
1381
		return $locale;
1382
	}
1383
1384
	/**
1385
	 * Return the network_site_url so that .com knows what network this site is a part of.
1386
	 *
1387
	 * @param  bool $option
1388
	 * @return string
1389
	 */
1390
	public function jetpack_main_network_site_option( $option ) {
1391
		return network_site_url();
1392
	}
1393
	/**
1394
	 * Network Name.
1395
	 */
1396
	static function network_name( $option = null ) {
1397
		global $current_site;
1398
		return $current_site->site_name;
1399
	}
1400
	/**
1401
	 * Does the network allow new user and site registrations.
1402
	 *
1403
	 * @return string
1404
	 */
1405
	static function network_allow_new_registrations( $option = null ) {
1406
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1407
	}
1408
	/**
1409
	 * Does the network allow admins to add new users.
1410
	 *
1411
	 * @return boolian
1412
	 */
1413
	static function network_add_new_users( $option = null ) {
1414
		return (bool) get_site_option( 'add_new_users' );
1415
	}
1416
	/**
1417
	 * File upload psace left per site in MB.
1418
	 *  -1 means NO LIMIT.
1419
	 *
1420
	 * @return number
1421
	 */
1422
	static function network_site_upload_space( $option = null ) {
1423
		// value in MB
1424
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1425
	}
1426
1427
	/**
1428
	 * Network allowed file types.
1429
	 *
1430
	 * @return string
1431
	 */
1432
	static function network_upload_file_types( $option = null ) {
1433
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1434
	}
1435
1436
	/**
1437
	 * Maximum file upload size set by the network.
1438
	 *
1439
	 * @return number
1440
	 */
1441
	static function network_max_upload_file_size( $option = null ) {
1442
		// value in KB
1443
		return get_site_option( 'fileupload_maxk', 300 );
1444
	}
1445
1446
	/**
1447
	 * Lets us know if a site allows admins to manage the network.
1448
	 *
1449
	 * @return array
1450
	 */
1451
	static function network_enable_administration_menus( $option = null ) {
1452
		return get_site_option( 'menu_items' );
1453
	}
1454
1455
	/**
1456
	 * If a user has been promoted to or demoted from admin, we need to clear the
1457
	 * jetpack_other_linked_admins transient.
1458
	 *
1459
	 * @since 4.3.2
1460
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1461
	 *
1462
	 * @param int    $user_id   The user ID whose role changed.
1463
	 * @param string $role      The new role.
1464
	 * @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...
1465
	 */
1466
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1467
		if ( 'administrator' == $role
1468
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1469
			|| is_null( $old_roles )
1470
		) {
1471
			delete_transient( 'jetpack_other_linked_admins' );
1472
		}
1473
	}
1474
1475
	/**
1476
	 * Checks to see if there are any other users available to become primary
1477
	 * Users must both:
1478
	 * - Be linked to wpcom
1479
	 * - Be an admin
1480
	 *
1481
	 * @return mixed False if no other users are linked, Int if there are.
1482
	 */
1483
	static function get_other_linked_admins() {
1484
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1485
1486
		if ( false === $other_linked_users ) {
1487
			$admins = get_users( array( 'role' => 'administrator' ) );
1488
			if ( count( $admins ) > 1 ) {
1489
				$available = array();
1490
				foreach ( $admins as $admin ) {
1491
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1492
						$available[] = $admin->ID;
1493
					}
1494
				}
1495
1496
				$count_connected_admins = count( $available );
1497
				if ( count( $available ) > 1 ) {
1498
					$other_linked_users = $count_connected_admins;
1499
				} else {
1500
					$other_linked_users = 0;
1501
				}
1502
			} else {
1503
				$other_linked_users = 0;
1504
			}
1505
1506
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1507
		}
1508
1509
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1510
	}
1511
1512
	/**
1513
	 * Return whether we are dealing with a multi network setup or not.
1514
	 * The reason we are type casting this is because we want to avoid the situation where
1515
	 * the result is false since when is_main_network_option return false it cases
1516
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1517
	 * database which could be set to anything as opposed to what this function returns.
1518
	 *
1519
	 * @param  bool $option
1520
	 *
1521
	 * @return boolean
1522
	 */
1523
	public function is_main_network_option( $option ) {
1524
		// return '1' or ''
1525
		return (string) (bool) self::is_multi_network();
1526
	}
1527
1528
	/**
1529
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1530
	 *
1531
	 * @param  string $option
1532
	 * @return boolean
1533
	 */
1534
	public function is_multisite( $option ) {
1535
		return (string) (bool) is_multisite();
1536
	}
1537
1538
	/**
1539
	 * Implemented since there is no core is multi network function
1540
	 * Right now there is no way to tell if we which network is the dominant network on the system
1541
	 *
1542
	 * @since  3.3
1543
	 * @return boolean
1544
	 */
1545 View Code Duplication
	public static function is_multi_network() {
1546
		global  $wpdb;
1547
1548
		// if we don't have a multi site setup no need to do any more
1549
		if ( ! is_multisite() ) {
1550
			return false;
1551
		}
1552
1553
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1554
		if ( $num_sites > 1 ) {
1555
			return true;
1556
		} else {
1557
			return false;
1558
		}
1559
	}
1560
1561
	/**
1562
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1563
	 *
1564
	 * @return null
1565
	 */
1566
	function update_jetpack_main_network_site_option() {
1567
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1568
	}
1569
	/**
1570
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1571
	 */
1572
	function update_jetpack_network_settings() {
1573
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1574
		// Only sync this info for the main network site.
1575
	}
1576
1577
	/**
1578
	 * Get back if the current site is single user site.
1579
	 *
1580
	 * @return bool
1581
	 */
1582 View Code Duplication
	public static function is_single_user_site() {
1583
		global $wpdb;
1584
1585
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1586
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1587
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1588
		}
1589
		return 1 === (int) $some_users;
1590
	}
1591
1592
	/**
1593
	 * Returns true if the site has file write access false otherwise.
1594
	 *
1595
	 * @return string ( '1' | '0' )
1596
	 **/
1597
	public static function file_system_write_access() {
1598
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1599
			require_once ABSPATH . 'wp-admin/includes/file.php';
1600
		}
1601
1602
		require_once ABSPATH . 'wp-admin/includes/template.php';
1603
1604
		$filesystem_method = get_filesystem_method();
1605
		if ( $filesystem_method === 'direct' ) {
1606
			return 1;
1607
		}
1608
1609
		ob_start();
1610
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1611
		ob_end_clean();
1612
		if ( $filesystem_credentials_are_stored ) {
1613
			return 1;
1614
		}
1615
		return 0;
1616
	}
1617
1618
	/**
1619
	 * Finds out if a site is using a version control system.
1620
	 *
1621
	 * @return string ( '1' | '0' )
1622
	 **/
1623
	public static function is_version_controlled() {
1624
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1625
		return (string) (int) Functions::is_version_controlled();
1626
	}
1627
1628
	/**
1629
	 * Determines whether the current theme supports featured images or not.
1630
	 *
1631
	 * @return string ( '1' | '0' )
1632
	 */
1633
	public static function featured_images_enabled() {
1634
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1635
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1636
	}
1637
1638
	/**
1639
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1640
	 *
1641
	 * @deprecated 4.7 use get_avatar_url instead.
1642
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1643
	 * @param int               $size Size of the avatar image
1644
	 * @param string            $default URL to a default image to use if no avatar is available
1645
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1646
	 *
1647
	 * @return array
1648
	 */
1649
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1650
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1651
		return get_avatar_url(
1652
			$id_or_email,
1653
			array(
1654
				'size'          => $size,
1655
				'default'       => $default,
1656
				'force_default' => $force_display,
1657
			)
1658
		);
1659
	}
1660
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1661
	/**
1662
	 * jetpack_updates is saved in the following schema:
1663
	 *
1664
	 * array (
1665
	 *      'plugins'                       => (int) Number of plugin updates available.
1666
	 *      'themes'                        => (int) Number of theme updates available.
1667
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1668
	 *      'translations'                  => (int) Number of translation updates available.
1669
	 *      'total'                         => (int) Total of all available updates.
1670
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1671
	 * )
1672
	 *
1673
	 * @return array
1674
	 */
1675
	public static function get_updates() {
1676
		$update_data = wp_get_update_data();
1677
1678
		// Stores the individual update counts as well as the total count.
1679
		if ( isset( $update_data['counts'] ) ) {
1680
			$updates = $update_data['counts'];
1681
		}
1682
1683
		// If we need to update WordPress core, let's find the latest version number.
1684 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1685
			$cur = get_preferred_from_update_core();
1686
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1687
				$updates['wp_update_version'] = $cur->current;
1688
			}
1689
		}
1690
		return isset( $updates ) ? $updates : array();
1691
	}
1692
	// phpcs:enable
1693
1694
	public static function get_update_details() {
1695
		$update_details = array(
1696
			'update_core'    => get_site_transient( 'update_core' ),
1697
			'update_plugins' => get_site_transient( 'update_plugins' ),
1698
			'update_themes'  => get_site_transient( 'update_themes' ),
1699
		);
1700
		return $update_details;
1701
	}
1702
1703
	public static function refresh_update_data() {
1704
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1705
1706
	}
1707
1708
	public static function refresh_theme_data() {
1709
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1710
	}
1711
1712
	/**
1713
	 * Is Jetpack active?
1714
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1715
	 *
1716
	 * This method is deprecated since 9.6.0. Please use one of the methods provided by the Manager class in the Connection package,
1717
	 * or Jetpack::is_connection_ready if you want to know when the Jetpack plugin starts considering the connection ready to be used.
1718
	 *
1719
	 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
1720
	 *
1721
	 * @deprecated 9.6.0
1722
	 *
1723
	 * @return bool
1724
	 */
1725
	public static function is_active() {
1726
		return self::connection()->is_active();
0 ignored issues
show
Deprecated Code introduced by
The method Automattic\Jetpack\Connection\Manager::is_active() has been deprecated with message: 9.6.0

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

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

Loading history...
1727
	}
1728
1729
	/**
1730
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1731
	 *
1732
	 * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1733
	 * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1734
	 * users and this option will be available by default for everybody.
1735
	 *
1736
	 * @since 9.6.0
1737
	 *
1738
	 * @return bool is the site connection ready to be used?
1739
	 */
1740
	public static function is_connection_ready() {
1741
		if ( ( new Status() )->is_no_user_testing_mode() ) {
1742
			return self::connection()->is_connected();
1743
		}
1744
		return (bool) self::connection()->has_connected_owner();
1745
	}
1746
1747
	/**
1748
	 * Make an API call to WordPress.com for plan status
1749
	 *
1750
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1751
	 *
1752
	 * @return bool True if plan is updated, false if no update
1753
	 */
1754
	public static function refresh_active_plan_from_wpcom() {
1755
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1756
		return Jetpack_Plan::refresh_from_wpcom();
1757
	}
1758
1759
	/**
1760
	 * Get the plan that this Jetpack site is currently using
1761
	 *
1762
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1763
	 * @return array Active Jetpack plan details.
1764
	 */
1765
	public static function get_active_plan() {
1766
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1767
		return Jetpack_Plan::get();
1768
	}
1769
1770
	/**
1771
	 * Determine whether the active plan supports a particular feature
1772
	 *
1773
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1774
	 * @return bool True if plan supports feature, false if not.
1775
	 */
1776
	public static function active_plan_supports( $feature ) {
1777
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1778
		return Jetpack_Plan::supports( $feature );
1779
	}
1780
1781
	/**
1782
	 * Deprecated: Is Jetpack in development (offline) mode?
1783
	 *
1784
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1785
	 * and themes still use it, and we do not want to flood them with notices.
1786
	 *
1787
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1788
	 *
1789
	 * @deprecated since 8.0.
1790
	 */
1791
	public static function is_development_mode() {
1792
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1793
		return ( new Status() )->is_offline_mode();
1794
	}
1795
1796
	/**
1797
	 * Whether the site is currently onboarding or not.
1798
	 * A site is considered as being onboarded if it currently has an onboarding token.
1799
	 *
1800
	 * @since 5.8
1801
	 *
1802
	 * @access public
1803
	 * @static
1804
	 *
1805
	 * @return bool True if the site is currently onboarding, false otherwise
1806
	 */
1807
	public static function is_onboarding() {
1808
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1809
	}
1810
1811
	/**
1812
	 * Determines reason for Jetpack offline mode.
1813
	 */
1814
	public static function development_mode_trigger_text() {
1815
		$status = new Status();
1816
1817
		if ( ! $status->is_offline_mode() ) {
1818
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1819
		}
1820
1821
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1822
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1823
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1824
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1825
		} elseif ( $status->is_local_site() ) {
1826
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1827
			/** This filter is documented in packages/status/src/class-status.php */
1828
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1829
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1830
		} else {
1831
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1832
		}
1833
1834
		return $notice;
1835
1836
	}
1837
	/**
1838
	 * Get Jetpack offline mode notice text and notice class.
1839
	 *
1840
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1841
	 */
1842
	public static function show_development_mode_notice() {
1843 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1844
			$notice = sprintf(
1845
				/* translators: %s is a URL */
1846
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1847
				Redirect::get_url( 'jetpack-support-development-mode' )
1848
			);
1849
1850
			$notice .= ' ' . self::development_mode_trigger_text();
1851
1852
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1853
		}
1854
1855
		// Throw up a notice if using a development version and as for feedback.
1856
		if ( self::is_development_version() ) {
1857
			/* translators: %s is a URL */
1858
			$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' ) );
1859
1860
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1861
		}
1862
		// Throw up a notice if using staging mode
1863 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1864
			/* translators: %s is a URL */
1865
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1866
1867
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1868
		}
1869
	}
1870
1871
	/**
1872
	 * Whether Jetpack's version maps to a public release, or a development version.
1873
	 */
1874
	public static function is_development_version() {
1875
		/**
1876
		 * Allows filtering whether this is a development version of Jetpack.
1877
		 *
1878
		 * This filter is especially useful for tests.
1879
		 *
1880
		 * @since 4.3.0
1881
		 *
1882
		 * @param bool $development_version Is this a develoment version of Jetpack?
1883
		 */
1884
		return (bool) apply_filters(
1885
			'jetpack_development_version',
1886
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1887
		);
1888
	}
1889
1890
	/**
1891
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1892
	 */
1893
	public static function is_user_connected( $user_id = false ) {
1894
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1895
		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...
1896
	}
1897
1898
	/**
1899
	 * Get the wpcom user data of the current|specified connected user.
1900
	 */
1901
	public static function get_connected_user_data( $user_id = null ) {
1902
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1903
		return self::connection()->get_connected_user_data( $user_id );
1904
	}
1905
1906
	/**
1907
	 * Get the wpcom email of the current|specified connected user.
1908
	 */
1909
	public static function get_connected_user_email( $user_id = null ) {
1910
		if ( ! $user_id ) {
1911
			$user_id = get_current_user_id();
1912
		}
1913
1914
		$xml = new Jetpack_IXR_Client(
1915
			array(
1916
				'user_id' => $user_id,
1917
			)
1918
		);
1919
		$xml->query( 'wpcom.getUserEmail' );
1920
		if ( ! $xml->isError() ) {
1921
			return $xml->getResponse();
1922
		}
1923
		return false;
1924
	}
1925
1926
	/**
1927
	 * Get the wpcom email of the master user.
1928
	 */
1929
	public static function get_master_user_email() {
1930
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1931
		if ( $master_user_id ) {
1932
			return self::get_connected_user_email( $master_user_id );
1933
		}
1934
		return '';
1935
	}
1936
1937
	/**
1938
	 * Whether the current user is the connection owner.
1939
	 *
1940
	 * @deprecated since 7.7
1941
	 *
1942
	 * @return bool Whether the current user is the connection owner.
1943
	 */
1944
	public function current_user_is_connection_owner() {
1945
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1946
		return self::connection()->is_connection_owner();
1947
	}
1948
1949
	/**
1950
	 * Gets current user IP address.
1951
	 *
1952
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1953
	 *
1954
	 * @return string                  Current user IP address.
1955
	 */
1956
	public static function current_user_ip( $check_all_headers = false ) {
1957
		if ( $check_all_headers ) {
1958
			foreach ( array(
1959
				'HTTP_CF_CONNECTING_IP',
1960
				'HTTP_CLIENT_IP',
1961
				'HTTP_X_FORWARDED_FOR',
1962
				'HTTP_X_FORWARDED',
1963
				'HTTP_X_CLUSTER_CLIENT_IP',
1964
				'HTTP_FORWARDED_FOR',
1965
				'HTTP_FORWARDED',
1966
				'HTTP_VIA',
1967
			) as $key ) {
1968
				if ( ! empty( $_SERVER[ $key ] ) ) {
1969
					return $_SERVER[ $key ];
1970
				}
1971
			}
1972
		}
1973
1974
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1975
	}
1976
1977
	/**
1978
	 * Synchronize connected user role changes
1979
	 */
1980
	function user_role_change( $user_id ) {
1981
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1982
		Users::user_role_change( $user_id );
1983
	}
1984
1985
	/**
1986
	 * Loads the currently active modules.
1987
	 */
1988
	public static function load_modules() {
1989
		$is_offline_mode = ( new Status() )->is_offline_mode();
1990
		if (
1991
			! self::is_connection_ready()
1992
			&& ! $is_offline_mode
1993
			&& ! self::is_onboarding()
1994
			&& (
1995
				! is_multisite()
1996
				|| ! get_site_option( 'jetpack_protect_active' )
1997
			)
1998
		) {
1999
			return;
2000
		}
2001
2002
		$version = Jetpack_Options::get_option( 'version' );
2003 View Code Duplication
		if ( ! $version ) {
2004
			$version = $old_version = JETPACK__VERSION . ':' . time();
2005
			/** This action is documented in class.jetpack.php */
2006
			do_action( 'updating_jetpack_version', $version, false );
2007
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2008
		}
2009
		list( $version ) = explode( ':', $version );
2010
2011
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
2012
2013
		$modules_data = array();
2014
2015
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
2016
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
2017
			$updated_modules = array();
2018
			foreach ( $modules as $module ) {
2019
				$modules_data[ $module ] = self::get_module( $module );
2020
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
2021
					continue;
2022
				}
2023
2024
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2025
					continue;
2026
				}
2027
2028
				$updated_modules[] = $module;
2029
			}
2030
2031
			$modules = array_diff( $modules, $updated_modules );
2032
		}
2033
2034
		foreach ( $modules as $index => $module ) {
2035
			// If we're in offline mode, disable modules requiring a connection.
2036
			if ( $is_offline_mode ) {
2037
				// Prime the pump if we need to
2038
				if ( empty( $modules_data[ $module ] ) ) {
2039
					$modules_data[ $module ] = self::get_module( $module );
2040
				}
2041
				// If the module requires a connection, but we're in local mode, don't include it.
2042
				if ( $modules_data[ $module ]['requires_connection'] ) {
2043
					continue;
2044
				}
2045
			}
2046
2047
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2048
				continue;
2049
			}
2050
2051
			if ( ! include_once self::get_module_path( $module ) ) {
2052
				unset( $modules[ $index ] );
2053
				self::update_active_modules( array_values( $modules ) );
2054
				continue;
2055
			}
2056
2057
			/**
2058
			 * Fires when a specific module is loaded.
2059
			 * The dynamic part of the hook, $module, is the module slug.
2060
			 *
2061
			 * @since 1.1.0
2062
			 */
2063
			do_action( 'jetpack_module_loaded_' . $module );
2064
		}
2065
2066
		/**
2067
		 * Fires when all the modules are loaded.
2068
		 *
2069
		 * @since 1.1.0
2070
		 */
2071
		do_action( 'jetpack_modules_loaded' );
2072
2073
		// Load module-specific code that is needed even when a module isn't active. Loaded here because code contained therein may need actions such as setup_theme.
2074
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2075
	}
2076
2077
	/**
2078
	 * Check if Jetpack's REST API compat file should be included
2079
	 *
2080
	 * @action plugins_loaded
2081
	 * @return null
2082
	 */
2083
	public function check_rest_api_compat() {
2084
		/**
2085
		 * Filters the list of REST API compat files to be included.
2086
		 *
2087
		 * @since 2.2.5
2088
		 *
2089
		 * @param array $args Array of REST API compat files to include.
2090
		 */
2091
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2092
2093
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2094
			require_once $_jetpack_rest_api_compat_include;
2095
		}
2096
	}
2097
2098
	/**
2099
	 * Gets all plugins currently active in values, regardless of whether they're
2100
	 * traditionally activated or network activated.
2101
	 *
2102
	 * @todo Store the result in core's object cache maybe?
2103
	 */
2104
	public static function get_active_plugins() {
2105
		$active_plugins = (array) get_option( 'active_plugins', array() );
2106
2107
		if ( is_multisite() ) {
2108
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2109
			// whereas active_plugins stores them in the values.
2110
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2111
			if ( $network_plugins ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $network_plugins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2112
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2113
			}
2114
		}
2115
2116
		sort( $active_plugins );
2117
2118
		return array_unique( $active_plugins );
2119
	}
2120
2121
	/**
2122
	 * Gets and parses additional plugin data to send with the heartbeat data
2123
	 *
2124
	 * @since 3.8.1
2125
	 *
2126
	 * @return array Array of plugin data
2127
	 */
2128
	public static function get_parsed_plugin_data() {
2129
		if ( ! function_exists( 'get_plugins' ) ) {
2130
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2131
		}
2132
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2133
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2134
		$active_plugins = self::get_active_plugins();
2135
2136
		$plugins = array();
2137
		foreach ( $all_plugins as $path => $plugin_data ) {
2138
			$plugins[ $path ] = array(
2139
				'is_active' => in_array( $path, $active_plugins ),
2140
				'file'      => $path,
2141
				'name'      => $plugin_data['Name'],
2142
				'version'   => $plugin_data['Version'],
2143
				'author'    => $plugin_data['Author'],
2144
			);
2145
		}
2146
2147
		return $plugins;
2148
	}
2149
2150
	/**
2151
	 * Gets and parses theme data to send with the heartbeat data
2152
	 *
2153
	 * @since 3.8.1
2154
	 *
2155
	 * @return array Array of theme data
2156
	 */
2157
	public static function get_parsed_theme_data() {
2158
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2159
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2160
2161
		$themes = array();
2162
		foreach ( $all_themes as $slug => $theme_data ) {
2163
			$theme_headers = array();
2164
			foreach ( $header_keys as $header_key ) {
2165
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2166
			}
2167
2168
			$themes[ $slug ] = array(
2169
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2170
				'slug'            => $slug,
2171
				'theme_root'      => $theme_data->get_theme_root_uri(),
2172
				'parent'          => $theme_data->parent(),
2173
				'headers'         => $theme_headers,
2174
			);
2175
		}
2176
2177
		return $themes;
2178
	}
2179
2180
	/**
2181
	 * Checks whether a specific plugin is active.
2182
	 *
2183
	 * We don't want to store these in a static variable, in case
2184
	 * there are switch_to_blog() calls involved.
2185
	 */
2186
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2187
		return in_array( $plugin, self::get_active_plugins() );
2188
	}
2189
2190
	/**
2191
	 * Check if Jetpack's Open Graph tags should be used.
2192
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2193
	 *
2194
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2195
	 * @action plugins_loaded
2196
	 * @return null
2197
	 */
2198
	public function check_open_graph() {
2199
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2200
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2201
		}
2202
2203
		$active_plugins = self::get_active_plugins();
2204
2205
		if ( ! empty( $active_plugins ) ) {
2206
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2207
				if ( in_array( $plugin, $active_plugins ) ) {
2208
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2209
					break;
2210
				}
2211
			}
2212
		}
2213
2214
		/**
2215
		 * Allow the addition of Open Graph Meta Tags to all pages.
2216
		 *
2217
		 * @since 2.0.3
2218
		 *
2219
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2220
		 */
2221
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2222
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2223
		}
2224
	}
2225
2226
	/**
2227
	 * Check if Jetpack's Twitter tags should be used.
2228
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2229
	 *
2230
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2231
	 * @action plugins_loaded
2232
	 * @return null
2233
	 */
2234
	public function check_twitter_tags() {
2235
2236
		$active_plugins = self::get_active_plugins();
2237
2238
		if ( ! empty( $active_plugins ) ) {
2239
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2240
				if ( in_array( $plugin, $active_plugins ) ) {
2241
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2242
					break;
2243
				}
2244
			}
2245
		}
2246
2247
		/**
2248
		 * Allow Twitter Card Meta tags to be disabled.
2249
		 *
2250
		 * @since 2.6.0
2251
		 *
2252
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2253
		 */
2254
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2255
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2256
		}
2257
	}
2258
2259
	/**
2260
	 * Allows plugins to submit security reports.
2261
	 *
2262
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2263
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2264
	 * @param array  $args         See definitions above
2265
	 */
2266
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2267
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2268
	}
2269
2270
	/* Jetpack Options API */
2271
2272
	public static function get_option_names( $type = 'compact' ) {
2273
		return Jetpack_Options::get_option_names( $type );
2274
	}
2275
2276
	/**
2277
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2278
	 *
2279
	 * @param string $name    Option name
2280
	 * @param mixed  $default (optional)
2281
	 */
2282
	public static function get_option( $name, $default = false ) {
2283
		return Jetpack_Options::get_option( $name, $default );
2284
	}
2285
2286
	/**
2287
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2288
	 *
2289
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2290
	 * @param string $name  Option name
2291
	 * @param mixed  $value Option value
2292
	 */
2293
	public static function update_option( $name, $value ) {
2294
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2295
		return Jetpack_Options::update_option( $name, $value );
2296
	}
2297
2298
	/**
2299
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2300
	 *
2301
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2302
	 * @param array $array array( option name => option value, ... )
2303
	 */
2304
	public static function update_options( $array ) {
2305
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2306
		return Jetpack_Options::update_options( $array );
2307
	}
2308
2309
	/**
2310
	 * Deletes the given option.  May be passed multiple option names as an array.
2311
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2312
	 *
2313
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2314
	 * @param string|array $names
2315
	 */
2316
	public static function delete_option( $names ) {
2317
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2318
		return Jetpack_Options::delete_option( $names );
2319
	}
2320
2321
	/**
2322
	 * Enters a user token into the user_tokens option
2323
	 *
2324
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2325
	 *
2326
	 * @param int    $user_id The user id.
2327
	 * @param string $token The user token.
2328
	 * @param bool   $is_master_user Whether the user is the master user.
2329
	 * @return bool
2330
	 */
2331
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2332
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2333
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2334
	}
2335
2336
	/**
2337
	 * Returns an array of all PHP files in the specified absolute path.
2338
	 * Equivalent to glob( "$absolute_path/*.php" ).
2339
	 *
2340
	 * @param string $absolute_path The absolute path of the directory to search.
2341
	 * @return array Array of absolute paths to the PHP files.
2342
	 */
2343
	public static function glob_php( $absolute_path ) {
2344
		if ( function_exists( 'glob' ) ) {
2345
			return glob( "$absolute_path/*.php" );
2346
		}
2347
2348
		$absolute_path = untrailingslashit( $absolute_path );
2349
		$files         = array();
2350
		if ( ! $dir = @opendir( $absolute_path ) ) {
2351
			return $files;
2352
		}
2353
2354
		while ( false !== $file = readdir( $dir ) ) {
2355
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2356
				continue;
2357
			}
2358
2359
			$file = "$absolute_path/$file";
2360
2361
			if ( ! is_file( $file ) ) {
2362
				continue;
2363
			}
2364
2365
			$files[] = $file;
2366
		}
2367
2368
		closedir( $dir );
2369
2370
		return $files;
2371
	}
2372
2373
	public static function activate_new_modules( $redirect = false ) {
2374
		if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2375
			return;
2376
		}
2377
2378
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2379 View Code Duplication
		if ( ! $jetpack_old_version ) {
2380
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2381
			/** This action is documented in class.jetpack.php */
2382
			do_action( 'updating_jetpack_version', $version, false );
2383
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2384
		}
2385
2386
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2387
2388
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2389
			return;
2390
		}
2391
2392
		$active_modules     = self::get_active_modules();
2393
		$reactivate_modules = array();
2394
		foreach ( $active_modules as $active_module ) {
2395
			$module = self::get_module( $active_module );
2396
			if ( ! isset( $module['changed'] ) ) {
2397
				continue;
2398
			}
2399
2400
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2401
				continue;
2402
			}
2403
2404
			$reactivate_modules[] = $active_module;
2405
			self::deactivate_module( $active_module );
2406
		}
2407
2408
		$new_version = JETPACK__VERSION . ':' . time();
2409
		/** This action is documented in class.jetpack.php */
2410
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2411
		Jetpack_Options::update_options(
2412
			array(
2413
				'version'     => $new_version,
2414
				'old_version' => $jetpack_old_version,
2415
			)
2416
		);
2417
2418
		self::state( 'message', 'modules_activated' );
2419
2420
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2421
2422
		if ( $redirect ) {
2423
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2424
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2425
				$page = $_GET['page'];
2426
			}
2427
2428
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2429
			exit;
2430
		}
2431
	}
2432
2433
	/**
2434
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2435
	 * Make sure to tuck away module "library" files in a sub-directory.
2436
	 *
2437
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2438
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2439
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2440
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2441
	 *
2442
	 * @return array $modules Array of module slugs
2443
	 */
2444
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2445
		static $modules = null;
2446
2447
		if ( ! isset( $modules ) ) {
2448
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2449
			// Use the cache if we're on the front-end and it's available...
2450
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2451
				$modules = $available_modules_option[ JETPACK__VERSION ];
2452
			} else {
2453
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2454
2455
				$modules = array();
2456
2457
				foreach ( $files as $file ) {
2458
					if ( ! $headers = self::get_module( $file ) ) {
2459
						continue;
2460
					}
2461
2462
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2463
				}
2464
2465
				Jetpack_Options::update_option(
2466
					'available_modules',
2467
					array(
2468
						JETPACK__VERSION => $modules,
2469
					)
2470
				);
2471
			}
2472
		}
2473
2474
		/**
2475
		 * Filters the array of modules available to be activated.
2476
		 *
2477
		 * @since 2.4.0
2478
		 *
2479
		 * @param array $modules Array of available modules.
2480
		 * @param string $min_version Minimum version number required to use modules.
2481
		 * @param string $max_version Maximum version number required to use modules.
2482
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2483
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2484
		 */
2485
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version, $requires_connection, $requires_user_connection );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

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

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

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

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

Loading history...
2559
	}
2560
2561
	/**
2562
	 * Checks activated modules during auto-activation to determine
2563
	 * if any of those modules are being deprecated.  If so, close
2564
	 * them out, and add any replacement modules.
2565
	 *
2566
	 * Runs at priority 99 by default.
2567
	 *
2568
	 * This is run late, so that it can still activate a module if
2569
	 * the new module is a replacement for another that the user
2570
	 * currently has active, even if something at the normal priority
2571
	 * would kibosh everything.
2572
	 *
2573
	 * @since 2.6
2574
	 * @uses jetpack_get_default_modules filter
2575
	 * @param array $modules
2576
	 * @return array
2577
	 */
2578
	function handle_deprecated_modules( $modules ) {
2579
		$deprecated_modules = array(
2580
			'debug'            => null,  // Closed out and moved to the debugger library.
2581
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2582
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2583
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2584
		);
2585
2586
		// Don't activate SSO if they never completed activating WPCC.
2587
		if ( self::is_module_active( 'wpcc' ) ) {
2588
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2589
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2590
				$deprecated_modules['wpcc'] = null;
2591
			}
2592
		}
2593
2594
		foreach ( $deprecated_modules as $module => $replacement ) {
2595
			if ( self::is_module_active( $module ) ) {
2596
				self::deactivate_module( $module );
2597
				if ( $replacement ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $replacement of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2598
					$modules[] = $replacement;
2599
				}
2600
			}
2601
		}
2602
2603
		return array_unique( $modules );
2604
	}
2605
2606
	/**
2607
	 * Checks activated plugins during auto-activation to determine
2608
	 * if any of those plugins are in the list with a corresponding module
2609
	 * that is not compatible with the plugin. The module will not be allowed
2610
	 * to auto-activate.
2611
	 *
2612
	 * @since 2.6
2613
	 * @uses jetpack_get_default_modules filter
2614
	 * @param array $modules
2615
	 * @return array
2616
	 */
2617
	function filter_default_modules( $modules ) {
2618
2619
		$active_plugins = self::get_active_plugins();
2620
2621
		if ( ! empty( $active_plugins ) ) {
2622
2623
			// For each module we'd like to auto-activate...
2624
			foreach ( $modules as $key => $module ) {
2625
				// If there are potential conflicts for it...
2626
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2627
					// For each potential conflict...
2628
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2629
						// If that conflicting plugin is active...
2630
						if ( in_array( $plugin, $active_plugins ) ) {
2631
							// Remove that item from being auto-activated.
2632
							unset( $modules[ $key ] );
2633
						}
2634
					}
2635
				}
2636
			}
2637
		}
2638
2639
		return $modules;
2640
	}
2641
2642
	/**
2643
	 * Extract a module's slug from its full path.
2644
	 */
2645
	public static function get_module_slug( $file ) {
2646
		return str_replace( '.php', '', basename( $file ) );
2647
	}
2648
2649
	/**
2650
	 * Generate a module's path from its slug.
2651
	 */
2652
	public static function get_module_path( $slug ) {
2653
		/**
2654
		 * Filters the path of a modules.
2655
		 *
2656
		 * @since 7.4.0
2657
		 *
2658
		 * @param array $return The absolute path to a module's root php file
2659
		 * @param string $slug The module slug
2660
		 */
2661
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $slug.

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

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

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

Loading history...
2662
	}
2663
2664
	/**
2665
	 * Load module data from module file. Headers differ from WordPress
2666
	 * plugin headers to avoid them being identified as standalone
2667
	 * plugins on the WordPress plugins page.
2668
	 */
2669
	public static function get_module( $module ) {
2670
		$headers = array(
2671
			'name'                      => 'Module Name',
2672
			'description'               => 'Module Description',
2673
			'sort'                      => 'Sort Order',
2674
			'recommendation_order'      => 'Recommendation Order',
2675
			'introduced'                => 'First Introduced',
2676
			'changed'                   => 'Major Changes In',
2677
			'deactivate'                => 'Deactivate',
2678
			'free'                      => 'Free',
2679
			'requires_connection'       => 'Requires Connection',
2680
			'requires_user_connection'  => 'Requires User Connection',
2681
			'auto_activate'             => 'Auto Activate',
2682
			'module_tags'               => 'Module Tags',
2683
			'feature'                   => 'Feature',
2684
			'additional_search_queries' => 'Additional Search Queries',
2685
			'plan_classes'              => 'Plans',
2686
		);
2687
2688
		static $modules_details;
2689
		$file = self::get_module_path( self::get_module_slug( $module ) );
2690
2691
		if ( isset( $modules_details[ $module ] ) ) {
2692
			$mod = $modules_details[ $module ];
2693
		} else {
2694
2695
			$mod = self::get_file_data( $file, $headers );
2696
			if ( empty( $mod['name'] ) ) {
2697
				return false;
2698
			}
2699
2700
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2701
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2702
			$mod['deactivate']               = empty( $mod['deactivate'] );
2703
			$mod['free']                     = empty( $mod['free'] );
2704
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2705
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2706
2707
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2708
				$mod['auto_activate'] = 'No';
2709
			} else {
2710
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2711
			}
2712
2713
			if ( $mod['module_tags'] ) {
2714
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2715
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2716
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2717
			} else {
2718
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2719
			}
2720
2721 View Code Duplication
			if ( $mod['plan_classes'] ) {
2722
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2723
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2724
			} else {
2725
				$mod['plan_classes'] = array( 'free' );
2726
			}
2727
2728 View Code Duplication
			if ( $mod['feature'] ) {
2729
				$mod['feature'] = explode( ',', $mod['feature'] );
2730
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2731
			} else {
2732
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2733
			}
2734
2735
			$modules_details[ $module ] = $mod;
2736
2737
		}
2738
2739
		/**
2740
		 * Filters the feature array on a module.
2741
		 *
2742
		 * This filter allows you to control where each module is filtered: Recommended,
2743
		 * and the default "Other" listing.
2744
		 *
2745
		 * @since 3.5.0
2746
		 *
2747
		 * @param array   $mod['feature'] The areas to feature this module:
2748
		 *     'Recommended' shows on the main Jetpack admin screen.
2749
		 *     'Other' should be the default if no other value is in the array.
2750
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2751
		 * @param array   $mod All the currently assembled module data.
2752
		 */
2753
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

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

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

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

Loading history...
2754
2755
		/**
2756
		 * Filter the returned data about a module.
2757
		 *
2758
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2759
		 * so please be careful.
2760
		 *
2761
		 * @since 3.6.0
2762
		 *
2763
		 * @param array   $mod    The details of the requested module.
2764
		 * @param string  $module The slug of the module, e.g. sharedaddy
2765
		 * @param string  $file   The path to the module source file.
2766
		 */
2767
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

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

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

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

Loading history...
2768
	}
2769
2770
	/**
2771
	 * Like core's get_file_data implementation, but caches the result.
2772
	 */
2773
	public static function get_file_data( $file, $headers ) {
2774
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2775
		$file_name = basename( $file );
2776
2777
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2778
2779
		$file_data_option = get_transient( $cache_key );
2780
2781
		if ( ! is_array( $file_data_option ) ) {
2782
			delete_transient( $cache_key );
2783
			$file_data_option = false;
2784
		}
2785
2786
		if ( false === $file_data_option ) {
2787
			$file_data_option = array();
2788
		}
2789
2790
		$key           = md5( $file_name . serialize( $headers ) );
2791
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2792
2793
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2794
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2795
			return $file_data_option[ $key ];
2796
		}
2797
2798
		$data = get_file_data( $file, $headers );
2799
2800
		$file_data_option[ $key ] = $data;
2801
2802
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2803
2804
		return $data;
2805
	}
2806
2807
	/**
2808
	 * Return translated module tag.
2809
	 *
2810
	 * @param string $tag Tag as it appears in each module heading.
2811
	 *
2812
	 * @return mixed
2813
	 */
2814
	public static function translate_module_tag( $tag ) {
2815
		return jetpack_get_module_i18n_tag( $tag );
2816
	}
2817
2818
	/**
2819
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2820
	 *
2821
	 * @since 3.9.2
2822
	 *
2823
	 * @param array $modules
2824
	 *
2825
	 * @return string|void
2826
	 */
2827
	public static function get_translated_modules( $modules ) {
2828
		foreach ( $modules as $index => $module ) {
2829
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2830
			if ( isset( $module['name'] ) ) {
2831
				$modules[ $index ]['name'] = $i18n_module['name'];
2832
			}
2833
			if ( isset( $module['description'] ) ) {
2834
				$modules[ $index ]['description']       = $i18n_module['description'];
2835
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2836
			}
2837
		}
2838
		return $modules;
2839
	}
2840
2841
	/**
2842
	 * Get a list of activated modules as an array of module slugs.
2843
	 */
2844
	public static function get_active_modules() {
2845
		$active = Jetpack_Options::get_option( 'active_modules' );
2846
2847
		if ( ! is_array( $active ) ) {
2848
			$active = array();
2849
		}
2850
2851
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2852
			$active[] = 'vaultpress';
2853
		} else {
2854
			$active = array_diff( $active, array( 'vaultpress' ) );
2855
		}
2856
2857
		// If protect is active on the main site of a multisite, it should be active on all sites.
2858
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2859
			$active[] = 'protect';
2860
		}
2861
2862
		/**
2863
		 * Allow filtering of the active modules.
2864
		 *
2865
		 * Gives theme and plugin developers the power to alter the modules that
2866
		 * are activated on the fly.
2867
		 *
2868
		 * @since 5.8.0
2869
		 *
2870
		 * @param array $active Array of active module slugs.
2871
		 */
2872
		$active = apply_filters( 'jetpack_active_modules', $active );
2873
2874
		return array_unique( $active );
2875
	}
2876
2877
	/**
2878
	 * Check whether or not a Jetpack module is active.
2879
	 *
2880
	 * @param string $module The slug of a Jetpack module.
2881
	 * @return bool
2882
	 *
2883
	 * @static
2884
	 */
2885
	public static function is_module_active( $module ) {
2886
		return in_array( $module, self::get_active_modules() );
2887
	}
2888
2889
	public static function is_module( $module ) {
2890
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2891
	}
2892
2893
	/**
2894
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2895
	 *
2896
	 * @param bool $catch True to start catching, False to stop.
2897
	 *
2898
	 * @static
2899
	 */
2900
	public static function catch_errors( $catch ) {
2901
		static $display_errors, $error_reporting;
2902
2903
		if ( $catch ) {
2904
			$display_errors  = @ini_set( 'display_errors', 1 );
2905
			$error_reporting = @error_reporting( E_ALL );
2906
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2907
		} else {
2908
			@ini_set( 'display_errors', $display_errors );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2909
			@error_reporting( $error_reporting );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2910
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2911
		}
2912
	}
2913
2914
	/**
2915
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2916
	 */
2917
	public static function catch_errors_on_shutdown() {
2918
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2919
	}
2920
2921
	/**
2922
	 * Rewrite any string to make paths easier to read.
2923
	 *
2924
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2925
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2926
	 *
2927
	 * @param $string
2928
	 * @return mixed
2929
	 */
2930
	public static function alias_directories( $string ) {
2931
		// ABSPATH has a trailing slash.
2932
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2933
		// WP_CONTENT_DIR does not have a trailing slash.
2934
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2935
2936
		return $string;
2937
	}
2938
2939
	public static function activate_default_modules(
2940
		$min_version = false,
2941
		$max_version = false,
2942
		$other_modules = array(),
2943
		$redirect = null,
2944
		$send_state_messages = null,
2945
		$requires_connection = null,
2946
		$requires_user_connection = null
2947
	) {
2948
		$jetpack = self::init();
2949
2950
		if ( is_null( $redirect ) ) {
2951
			if (
2952
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2953
			||
2954
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2955
			||
2956
				( defined( 'WP_CLI' ) && WP_CLI )
2957
			||
2958
				( defined( 'DOING_CRON' ) && DOING_CRON )
2959
			||
2960
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2961
			) {
2962
				$redirect = false;
2963
			} elseif ( is_admin() ) {
2964
				$redirect = true;
2965
			} else {
2966
				$redirect = false;
2967
			}
2968
		}
2969
2970
		if ( is_null( $send_state_messages ) ) {
2971
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2972
		}
2973
2974
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2975
		$modules = array_merge( $other_modules, $modules );
2976
2977
		// Look for standalone plugins and disable if active.
2978
2979
		$to_deactivate = array();
2980
		foreach ( $modules as $module ) {
2981
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2982
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2983
			}
2984
		}
2985
2986
		$deactivated = array();
2987
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2988
			list( $probable_file, $probable_title ) = $deactivate_me;
2989
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2990
				$deactivated[] = $module;
2991
			}
2992
		}
2993
2994
		if ( $deactivated ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2995
			if ( $send_state_messages ) {
2996
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2997
			}
2998
2999
			if ( $redirect ) {
3000
				$url = add_query_arg(
3001
					array(
3002
						'action'   => 'activate_default_modules',
3003
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
3004
					),
3005
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
3006
				);
3007
				wp_safe_redirect( $url );
3008
				exit;
3009
			}
3010
		}
3011
3012
		/**
3013
		 * Fires before default modules are activated.
3014
		 *
3015
		 * @since 1.9.0
3016
		 *
3017
		 * @param string    $min_version Minimum version number required to use modules.
3018
		 * @param string    $max_version Maximum version number required to use modules.
3019
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3020
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3021
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3022
		 */
3023
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3024
3025
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3026
		if ( $send_state_messages ) {
3027
			self::restate();
3028
			self::catch_errors( true );
3029
		}
3030
3031
		$active = self::get_active_modules();
3032
3033
		foreach ( $modules as $module ) {
3034
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3035
				$active[] = $module;
3036
				self::update_active_modules( $active );
3037
				continue;
3038
			}
3039
3040
			if ( $send_state_messages && in_array( $module, $active ) ) {
3041
				$module_info = self::get_module( $module );
3042 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3043
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3044
					if ( $active_state = self::state( $state ) ) {
3045
						$active_state = explode( ',', $active_state );
3046
					} else {
3047
						$active_state = array();
3048
					}
3049
					$active_state[] = $module;
3050
					self::state( $state, implode( ',', $active_state ) );
3051
				}
3052
				continue;
3053
			}
3054
3055
			$file = self::get_module_path( $module );
3056
			if ( ! file_exists( $file ) ) {
3057
				continue;
3058
			}
3059
3060
			// we'll override this later if the plugin can be included without fatal error
3061
			if ( $redirect ) {
3062
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3063
			}
3064
3065
			if ( $send_state_messages ) {
3066
				self::state( 'error', 'module_activation_failed' );
3067
				self::state( 'module', $module );
3068
			}
3069
3070
			ob_start();
3071
			require_once $file;
3072
3073
			$active[] = $module;
3074
3075 View Code Duplication
			if ( $send_state_messages ) {
3076
3077
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3078
				if ( $active_state = self::state( $state ) ) {
3079
					$active_state = explode( ',', $active_state );
3080
				} else {
3081
					$active_state = array();
3082
				}
3083
				$active_state[] = $module;
3084
				self::state( $state, implode( ',', $active_state ) );
3085
			}
3086
3087
			self::update_active_modules( $active );
3088
3089
			ob_end_clean();
3090
		}
3091
3092
		if ( $send_state_messages ) {
3093
			self::state( 'error', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3094
			self::state( 'module', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3095
		}
3096
3097
		self::catch_errors( false );
3098
		/**
3099
		 * Fires when default modules are activated.
3100
		 *
3101
		 * @since 1.9.0
3102
		 *
3103
		 * @param string    $min_version Minimum version number required to use modules.
3104
		 * @param string    $max_version Maximum version number required to use modules.
3105
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3106
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3107
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3108
		 */
3109
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3110
	}
3111
3112
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3113
		/**
3114
		 * Fires before a module is activated.
3115
		 *
3116
		 * @since 2.6.0
3117
		 *
3118
		 * @param string $module Module slug.
3119
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3120
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3121
		 */
3122
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3123
3124
		$jetpack = self::init();
3125
3126
		if ( ! strlen( $module ) ) {
3127
			return false;
3128
		}
3129
3130
		if ( ! self::is_module( $module ) ) {
3131
			return false;
3132
		}
3133
3134
		// If it's already active, then don't do it again
3135
		$active = self::get_active_modules();
3136
		foreach ( $active as $act ) {
3137
			if ( $act == $module ) {
3138
				return true;
3139
			}
3140
		}
3141
3142
		$module_data = self::get_module( $module );
3143
3144
		$is_offline_mode = ( new Status() )->is_offline_mode();
3145
		if ( ! self::is_connection_ready() ) {
3146
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3147
				return false;
3148
			}
3149
3150
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3151
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3152
				return false;
3153
			}
3154
		}
3155
3156
		// Check and see if the old plugin is active
3157
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3158
			// Deactivate the old plugin
3159
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3160
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3161
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3162
				self::state( 'deactivated_plugins', $module );
3163
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3164
				exit;
3165
			}
3166
		}
3167
3168
		// Protect won't work with mis-configured IPs
3169
		if ( 'protect' === $module ) {
3170
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3171
			if ( ! jetpack_protect_get_ip() ) {
3172
				self::state( 'message', 'protect_misconfigured_ip' );
3173
				return false;
3174
			}
3175
		}
3176
3177
		if ( ! Jetpack_Plan::supports( $module ) ) {
3178
			return false;
3179
		}
3180
3181
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3182
		self::state( 'module', $module );
3183
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3184
3185
		self::catch_errors( true );
3186
		ob_start();
3187
		require self::get_module_path( $module );
3188
		/** This action is documented in class.jetpack.php */
3189
		do_action( 'jetpack_activate_module', $module );
3190
		$active[] = $module;
3191
		self::update_active_modules( $active );
3192
3193
		self::state( 'error', false ); // the override
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3194
		ob_end_clean();
3195
		self::catch_errors( false );
3196
3197
		if ( $redirect ) {
3198
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3199
		}
3200
		if ( $exit ) {
3201
			exit;
3202
		}
3203
		return true;
3204
	}
3205
3206
	function activate_module_actions( $module ) {
3207
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3208
	}
3209
3210
	public static function deactivate_module( $module ) {
3211
		/**
3212
		 * Fires when a module is deactivated.
3213
		 *
3214
		 * @since 1.9.0
3215
		 *
3216
		 * @param string $module Module slug.
3217
		 */
3218
		do_action( 'jetpack_pre_deactivate_module', $module );
3219
3220
		$jetpack = self::init();
0 ignored issues
show
Unused Code introduced by
$jetpack is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3221
3222
		$active = self::get_active_modules();
3223
		$new    = array_filter( array_diff( $active, (array) $module ) );
3224
3225
		return self::update_active_modules( $new );
3226
	}
3227
3228
	public static function enable_module_configurable( $module ) {
3229
		$module = self::get_module_slug( $module );
3230
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3231
	}
3232
3233
	/**
3234
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3235
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3236
	 *
3237
	 * @param string $module Module slug
3238
	 * @return string $url module configuration URL
3239
	 */
3240
	public static function module_configuration_url( $module ) {
3241
		$module      = self::get_module_slug( $module );
3242
		$default_url = self::admin_url() . "#/settings?term=$module";
3243
		/**
3244
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3245
		 *
3246
		 * @since 6.9.0
3247
		 *
3248
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3249
		 */
3250
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3251
3252
		return $url;
3253
	}
3254
3255
	/* Installation */
3256
	public static function bail_on_activation( $message, $deactivate = true ) {
3257
		?>
3258
<!doctype html>
3259
<html>
3260
<head>
3261
<meta charset="<?php bloginfo( 'charset' ); ?>">
3262
<style>
3263
* {
3264
	text-align: center;
3265
	margin: 0;
3266
	padding: 0;
3267
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3268
}
3269
p {
3270
	margin-top: 1em;
3271
	font-size: 18px;
3272
}
3273
</style>
3274
<body>
3275
<p><?php echo esc_html( $message ); ?></p>
3276
</body>
3277
</html>
3278
		<?php
3279
		if ( $deactivate ) {
3280
			$plugins = get_option( 'active_plugins' );
3281
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3282
			$update  = false;
3283
			foreach ( $plugins as $i => $plugin ) {
3284
				if ( $plugin === $jetpack ) {
3285
					$plugins[ $i ] = false;
3286
					$update        = true;
3287
				}
3288
			}
3289
3290
			if ( $update ) {
3291
				update_option( 'active_plugins', array_filter( $plugins ) );
3292
			}
3293
		}
3294
		exit;
3295
	}
3296
3297
	/**
3298
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3299
	 *
3300
	 * @static
3301
	 */
3302
	public static function plugin_activation( $network_wide ) {
3303
		Jetpack_Options::update_option( 'activated', 1 );
3304
3305
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3306
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3307
		}
3308
3309
		if ( $network_wide ) {
3310
			self::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

Loading history...
7504
			return false;
7505
		}
7506
		return true;
7507
	}
7508
7509
	/**
7510
	 * Checks if a Jetpack site is both active and not in offline mode.
7511
	 *
7512
	 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
7513
	 *
7514
	 * @since 8.8.0
7515
	 *
7516
	 * @return bool True if Jetpack is active and not in offline mode.
7517
	 */
7518
	public static function is_active_and_not_offline_mode() {
7519
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
7520
			return false;
7521
		}
7522
		return true;
7523
	}
7524
7525
	/**
7526
	 * Returns the list of products that we have available for purchase.
7527
	 */
7528
	public static function get_products_for_purchase() {
7529
		$products = array();
7530
		if ( ! is_multisite() ) {
7531
			$products[] = array(
7532
				'key'               => 'backup',
7533
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7534
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7535
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7536
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7537
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7538
				'options'           => array(
7539
					array(
7540
						'type'        => 'daily',
7541
						'slug'        => 'jetpack-backup-daily',
7542
						'key'         => 'jetpack_backup_daily',
7543
						'name'        => __( 'Daily Backups', 'jetpack' ),
7544
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7545
					),
7546
					array(
7547
						'type'        => 'realtime',
7548
						'slug'        => 'jetpack-backup-realtime',
7549
						'key'         => 'jetpack_backup_realtime',
7550
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7551
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7552
					),
7553
				),
7554
				'default_option'    => 'realtime',
7555
				'show_promotion'    => true,
7556
				'discount_percent'  => 70,
7557
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7558
			);
7559
7560
			$products[] = array(
7561
				'key'               => 'scan',
7562
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7563
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7564
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7565
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7566
				'show_promotion'    => true,
7567
				'discount_percent'  => 30,
7568
				'options'           => array(
7569
					array(
7570
						'type' => 'scan',
7571
						'slug' => 'jetpack-scan',
7572
						'key'  => 'jetpack_scan',
7573
						'name' => __( 'Daily Scan', 'jetpack' ),
7574
					),
7575
				),
7576
				'default_option'    => 'scan',
7577
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7578
			);
7579
		}
7580
7581
		$products[] = array(
7582
			'key'               => 'search',
7583
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7584
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7585
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7586
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7587
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7588
			'options'           => array(
7589
				array(
7590
					'type' => 'search',
7591
					'slug' => 'jetpack-search',
7592
					'key'  => 'jetpack_search',
7593
					'name' => __( 'Search', 'jetpack' ),
7594
				),
7595
			),
7596
			'tears'             => array(),
7597
			'default_option'    => 'search',
7598
			'show_promotion'    => false,
7599
			'included_in_plans' => array( 'search-plan' ),
7600
		);
7601
7602
		$products[] = array(
7603
			'key'               => 'anti-spam',
7604
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7605
			'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' ),
7606
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7607
			'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' ),
7608
			'options'           => array(
7609
				array(
7610
					'type' => 'anti-spam',
7611
					'slug' => 'jetpack-anti-spam',
7612
					'key'  => 'jetpack_anti_spam',
7613
					'name' => __( 'Anti-Spam', 'jetpack' ),
7614
				),
7615
			),
7616
			'default_option'    => 'anti-spam',
7617
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7618
		);
7619
7620
		return $products;
7621
	}
7622
}
7623