Completed
Push — update/use-identity-crisis-pac... ( a99a98...fe8fff )
by
unknown
237:00 queued 228:14
created

Jetpack::dismiss_jetpack_notice()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

Loading history...
1758
	}
1759
1760
	/**
1761
	 * Make an API call to WordPress.com for plan status
1762
	 *
1763
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1764
	 *
1765
	 * @return bool True if plan is updated, false if no update
1766
	 */
1767
	public static function refresh_active_plan_from_wpcom() {
1768
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1769
		return Jetpack_Plan::refresh_from_wpcom();
1770
	}
1771
1772
	/**
1773
	 * Get the plan that this Jetpack site is currently using
1774
	 *
1775
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1776
	 * @return array Active Jetpack plan details.
1777
	 */
1778
	public static function get_active_plan() {
1779
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1780
		return Jetpack_Plan::get();
1781
	}
1782
1783
	/**
1784
	 * Determine whether the active plan supports a particular feature
1785
	 *
1786
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1787
	 * @return bool True if plan supports feature, false if not.
1788
	 */
1789
	public static function active_plan_supports( $feature ) {
1790
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1791
		return Jetpack_Plan::supports( $feature );
1792
	}
1793
1794
	/**
1795
	 * Deprecated: Is Jetpack in development (offline) mode?
1796
	 *
1797
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1798
	 * and themes still use it, and we do not want to flood them with notices.
1799
	 *
1800
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1801
	 *
1802
	 * @deprecated since 8.0.
1803
	 */
1804
	public static function is_development_mode() {
1805
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1806
		return ( new Status() )->is_offline_mode();
1807
	}
1808
1809
	/**
1810
	 * Whether the site is currently onboarding or not.
1811
	 * A site is considered as being onboarded if it currently has an onboarding token.
1812
	 *
1813
	 * @since 5.8
1814
	 *
1815
	 * @access public
1816
	 * @static
1817
	 *
1818
	 * @return bool True if the site is currently onboarding, false otherwise
1819
	 */
1820
	public static function is_onboarding() {
1821
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1822
	}
1823
1824
	/**
1825
	 * Determines reason for Jetpack offline mode.
1826
	 */
1827
	public static function development_mode_trigger_text() {
1828
		$status = new Status();
1829
1830
		if ( ! $status->is_offline_mode() ) {
1831
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1832
		}
1833
1834
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1835
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1836
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1837
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1838
		} elseif ( $status->is_local_site() ) {
1839
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1840
			/** This filter is documented in packages/status/src/class-status.php */
1841
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1842
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1843
		} else {
1844
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1845
		}
1846
1847
		return $notice;
1848
1849
	}
1850
	/**
1851
	 * Get Jetpack offline mode notice text and notice class.
1852
	 *
1853
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1854
	 */
1855
	public static function show_development_mode_notice() {
1856 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1857
			$notice = sprintf(
1858
				/* translators: %s is a URL */
1859
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1860
				Redirect::get_url( 'jetpack-support-development-mode' )
1861
			);
1862
1863
			$notice .= ' ' . self::development_mode_trigger_text();
1864
1865
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1866
		}
1867
1868
		// Throw up a notice if using a development version and as for feedback.
1869
		if ( self::is_development_version() ) {
1870
			/* translators: %s is a URL */
1871
			$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' ) );
1872
1873
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1874
		}
1875
		// Throw up a notice if using staging mode
1876 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1877
			/* translators: %s is a URL */
1878
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1879
1880
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1881
		}
1882
	}
1883
1884
	/**
1885
	 * Whether Jetpack's version maps to a public release, or a development version.
1886
	 */
1887
	public static function is_development_version() {
1888
		/**
1889
		 * Allows filtering whether this is a development version of Jetpack.
1890
		 *
1891
		 * This filter is especially useful for tests.
1892
		 *
1893
		 * @since 4.3.0
1894
		 *
1895
		 * @param bool $development_version Is this a develoment version of Jetpack?
1896
		 */
1897
		return (bool) apply_filters(
1898
			'jetpack_development_version',
1899
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1900
		);
1901
	}
1902
1903
	/**
1904
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1905
	 */
1906
	public static function is_user_connected( $user_id = false ) {
1907
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1908
		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...
1909
	}
1910
1911
	/**
1912
	 * Get the wpcom user data of the current|specified connected user.
1913
	 */
1914
	public static function get_connected_user_data( $user_id = null ) {
1915
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1916
		return self::connection()->get_connected_user_data( $user_id );
1917
	}
1918
1919
	/**
1920
	 * Get the wpcom email of the current|specified connected user.
1921
	 */
1922
	public static function get_connected_user_email( $user_id = null ) {
1923
		if ( ! $user_id ) {
1924
			$user_id = get_current_user_id();
1925
		}
1926
1927
		$xml = new Jetpack_IXR_Client(
1928
			array(
1929
				'user_id' => $user_id,
1930
			)
1931
		);
1932
		$xml->query( 'wpcom.getUserEmail' );
1933
		if ( ! $xml->isError() ) {
1934
			return $xml->getResponse();
1935
		}
1936
		return false;
1937
	}
1938
1939
	/**
1940
	 * Get the wpcom email of the master user.
1941
	 */
1942
	public static function get_master_user_email() {
1943
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1944
		if ( $master_user_id ) {
1945
			return self::get_connected_user_email( $master_user_id );
1946
		}
1947
		return '';
1948
	}
1949
1950
	/**
1951
	 * Whether the current user is the connection owner.
1952
	 *
1953
	 * @deprecated since 7.7
1954
	 *
1955
	 * @return bool Whether the current user is the connection owner.
1956
	 */
1957
	public function current_user_is_connection_owner() {
1958
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1959
		return self::connection()->is_connection_owner();
1960
	}
1961
1962
	/**
1963
	 * Gets current user IP address.
1964
	 *
1965
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1966
	 *
1967
	 * @return string                  Current user IP address.
1968
	 */
1969
	public static function current_user_ip( $check_all_headers = false ) {
1970
		if ( $check_all_headers ) {
1971
			foreach ( array(
1972
				'HTTP_CF_CONNECTING_IP',
1973
				'HTTP_CLIENT_IP',
1974
				'HTTP_X_FORWARDED_FOR',
1975
				'HTTP_X_FORWARDED',
1976
				'HTTP_X_CLUSTER_CLIENT_IP',
1977
				'HTTP_FORWARDED_FOR',
1978
				'HTTP_FORWARDED',
1979
				'HTTP_VIA',
1980
			) as $key ) {
1981
				if ( ! empty( $_SERVER[ $key ] ) ) {
1982
					return $_SERVER[ $key ];
1983
				}
1984
			}
1985
		}
1986
1987
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1988
	}
1989
1990
	/**
1991
	 * Synchronize connected user role changes
1992
	 */
1993
	function user_role_change( $user_id ) {
1994
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1995
		Users::user_role_change( $user_id );
1996
	}
1997
1998
	/**
1999
	 * Loads the currently active modules.
2000
	 */
2001
	public static function load_modules() {
2002
		$is_offline_mode = ( new Status() )->is_offline_mode();
2003
		if (
2004
			! self::is_connection_ready()
2005
			&& ! $is_offline_mode
2006
			&& ! self::is_onboarding()
2007
			&& (
2008
				! is_multisite()
2009
				|| ! get_site_option( 'jetpack_protect_active' )
2010
			)
2011
		) {
2012
			return;
2013
		}
2014
2015
		$version = Jetpack_Options::get_option( 'version' );
2016 View Code Duplication
		if ( ! $version ) {
2017
			$version = $old_version = JETPACK__VERSION . ':' . time();
2018
			/** This action is documented in class.jetpack.php */
2019
			do_action( 'updating_jetpack_version', $version, false );
2020
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2021
		}
2022
		list( $version ) = explode( ':', $version );
2023
2024
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
2025
2026
		$modules_data = array();
2027
2028
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
2029
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
2030
			$updated_modules = array();
2031
			foreach ( $modules as $module ) {
2032
				$modules_data[ $module ] = self::get_module( $module );
2033
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
2034
					continue;
2035
				}
2036
2037
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2038
					continue;
2039
				}
2040
2041
				$updated_modules[] = $module;
2042
			}
2043
2044
			$modules = array_diff( $modules, $updated_modules );
2045
		}
2046
2047
		$is_userless = self::connection()->is_userless();
2048
2049
		foreach ( $modules as $index => $module ) {
2050
			// If we're in offline/user-less mode, disable modules requiring a connection/user connection.
2051
			if ( $is_offline_mode || $is_userless ) {
2052
				// Prime the pump if we need to
2053
				if ( empty( $modules_data[ $module ] ) ) {
2054
					$modules_data[ $module ] = self::get_module( $module );
2055
				}
2056
				// If the module requires a connection, but we're in local mode, don't include it.
2057
				if ( $is_offline_mode && $modules_data[ $module ]['requires_connection'] ) {
2058
					continue;
2059
				}
2060
2061
				if ( $is_userless && $modules_data[ $module ]['requires_user_connection'] ) {
2062
					continue;
2063
				}
2064
			}
2065
2066
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2067
				continue;
2068
			}
2069
2070
			if ( ! include_once self::get_module_path( $module ) ) {
2071
				unset( $modules[ $index ] );
2072
				self::update_active_modules( array_values( $modules ) );
2073
				continue;
2074
			}
2075
2076
			/**
2077
			 * Fires when a specific module is loaded.
2078
			 * The dynamic part of the hook, $module, is the module slug.
2079
			 *
2080
			 * @since 1.1.0
2081
			 */
2082
			do_action( 'jetpack_module_loaded_' . $module );
2083
		}
2084
2085
		/**
2086
		 * Fires when all the modules are loaded.
2087
		 *
2088
		 * @since 1.1.0
2089
		 */
2090
		do_action( 'jetpack_modules_loaded' );
2091
2092
		// 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.
2093
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2094
	}
2095
2096
	/**
2097
	 * Check if Jetpack's REST API compat file should be included
2098
	 *
2099
	 * @action plugins_loaded
2100
	 * @return null
2101
	 */
2102
	public function check_rest_api_compat() {
2103
		/**
2104
		 * Filters the list of REST API compat files to be included.
2105
		 *
2106
		 * @since 2.2.5
2107
		 *
2108
		 * @param array $args Array of REST API compat files to include.
2109
		 */
2110
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2111
2112
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2113
			require_once $_jetpack_rest_api_compat_include;
2114
		}
2115
	}
2116
2117
	/**
2118
	 * Gets all plugins currently active in values, regardless of whether they're
2119
	 * traditionally activated or network activated.
2120
	 *
2121
	 * @todo Store the result in core's object cache maybe?
2122
	 */
2123
	public static function get_active_plugins() {
2124
		$active_plugins = (array) get_option( 'active_plugins', array() );
2125
2126
		if ( is_multisite() ) {
2127
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2128
			// whereas active_plugins stores them in the values.
2129
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2130
			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...
2131
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2132
			}
2133
		}
2134
2135
		sort( $active_plugins );
2136
2137
		return array_unique( $active_plugins );
2138
	}
2139
2140
	/**
2141
	 * Gets and parses additional plugin data to send with the heartbeat data
2142
	 *
2143
	 * @since 3.8.1
2144
	 *
2145
	 * @return array Array of plugin data
2146
	 */
2147
	public static function get_parsed_plugin_data() {
2148
		if ( ! function_exists( 'get_plugins' ) ) {
2149
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2150
		}
2151
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2152
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2153
		$active_plugins = self::get_active_plugins();
2154
2155
		$plugins = array();
2156
		foreach ( $all_plugins as $path => $plugin_data ) {
2157
			$plugins[ $path ] = array(
2158
				'is_active' => in_array( $path, $active_plugins ),
2159
				'file'      => $path,
2160
				'name'      => $plugin_data['Name'],
2161
				'version'   => $plugin_data['Version'],
2162
				'author'    => $plugin_data['Author'],
2163
			);
2164
		}
2165
2166
		return $plugins;
2167
	}
2168
2169
	/**
2170
	 * Gets and parses theme data to send with the heartbeat data
2171
	 *
2172
	 * @since 3.8.1
2173
	 *
2174
	 * @return array Array of theme data
2175
	 */
2176
	public static function get_parsed_theme_data() {
2177
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2178
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2179
2180
		$themes = array();
2181
		foreach ( $all_themes as $slug => $theme_data ) {
2182
			$theme_headers = array();
2183
			foreach ( $header_keys as $header_key ) {
2184
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2185
			}
2186
2187
			$themes[ $slug ] = array(
2188
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2189
				'slug'            => $slug,
2190
				'theme_root'      => $theme_data->get_theme_root_uri(),
2191
				'parent'          => $theme_data->parent(),
2192
				'headers'         => $theme_headers,
2193
			);
2194
		}
2195
2196
		return $themes;
2197
	}
2198
2199
	/**
2200
	 * Checks whether a specific plugin is active.
2201
	 *
2202
	 * We don't want to store these in a static variable, in case
2203
	 * there are switch_to_blog() calls involved.
2204
	 */
2205
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2206
		return in_array( $plugin, self::get_active_plugins() );
2207
	}
2208
2209
	/**
2210
	 * Check if Jetpack's Open Graph tags should be used.
2211
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2212
	 *
2213
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2214
	 * @action plugins_loaded
2215
	 * @return null
2216
	 */
2217
	public function check_open_graph() {
2218
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2219
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2220
		}
2221
2222
		$active_plugins = self::get_active_plugins();
2223
2224
		if ( ! empty( $active_plugins ) ) {
2225
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2226
				if ( in_array( $plugin, $active_plugins ) ) {
2227
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2228
					break;
2229
				}
2230
			}
2231
		}
2232
2233
		/**
2234
		 * Allow the addition of Open Graph Meta Tags to all pages.
2235
		 *
2236
		 * @since 2.0.3
2237
		 *
2238
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2239
		 */
2240
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2241
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2242
		}
2243
	}
2244
2245
	/**
2246
	 * Check if Jetpack's Twitter tags should be used.
2247
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2248
	 *
2249
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2250
	 * @action plugins_loaded
2251
	 * @return null
2252
	 */
2253
	public function check_twitter_tags() {
2254
2255
		$active_plugins = self::get_active_plugins();
2256
2257
		if ( ! empty( $active_plugins ) ) {
2258
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2259
				if ( in_array( $plugin, $active_plugins ) ) {
2260
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2261
					break;
2262
				}
2263
			}
2264
		}
2265
2266
		/**
2267
		 * Allow Twitter Card Meta tags to be disabled.
2268
		 *
2269
		 * @since 2.6.0
2270
		 *
2271
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2272
		 */
2273
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2274
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2275
		}
2276
	}
2277
2278
	/**
2279
	 * Allows plugins to submit security reports.
2280
	 *
2281
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2282
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2283
	 * @param array  $args         See definitions above
2284
	 */
2285
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2286
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2287
	}
2288
2289
	/* Jetpack Options API */
2290
2291
	public static function get_option_names( $type = 'compact' ) {
2292
		return Jetpack_Options::get_option_names( $type );
2293
	}
2294
2295
	/**
2296
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2297
	 *
2298
	 * @param string $name    Option name
2299
	 * @param mixed  $default (optional)
2300
	 */
2301
	public static function get_option( $name, $default = false ) {
2302
		return Jetpack_Options::get_option( $name, $default );
2303
	}
2304
2305
	/**
2306
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2307
	 *
2308
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2309
	 * @param string $name  Option name
2310
	 * @param mixed  $value Option value
2311
	 */
2312
	public static function update_option( $name, $value ) {
2313
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2314
		return Jetpack_Options::update_option( $name, $value );
2315
	}
2316
2317
	/**
2318
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2319
	 *
2320
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2321
	 * @param array $array array( option name => option value, ... )
2322
	 */
2323
	public static function update_options( $array ) {
2324
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2325
		return Jetpack_Options::update_options( $array );
2326
	}
2327
2328
	/**
2329
	 * Deletes the given option.  May be passed multiple option names as an array.
2330
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2331
	 *
2332
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2333
	 * @param string|array $names
2334
	 */
2335
	public static function delete_option( $names ) {
2336
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2337
		return Jetpack_Options::delete_option( $names );
2338
	}
2339
2340
	/**
2341
	 * Enters a user token into the user_tokens option
2342
	 *
2343
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2344
	 *
2345
	 * @param int    $user_id The user id.
2346
	 * @param string $token The user token.
2347
	 * @param bool   $is_master_user Whether the user is the master user.
2348
	 * @return bool
2349
	 */
2350
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2351
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2352
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2353
	}
2354
2355
	/**
2356
	 * Returns an array of all PHP files in the specified absolute path.
2357
	 * Equivalent to glob( "$absolute_path/*.php" ).
2358
	 *
2359
	 * @param string $absolute_path The absolute path of the directory to search.
2360
	 * @return array Array of absolute paths to the PHP files.
2361
	 */
2362
	public static function glob_php( $absolute_path ) {
2363
		if ( function_exists( 'glob' ) ) {
2364
			return glob( "$absolute_path/*.php" );
2365
		}
2366
2367
		$absolute_path = untrailingslashit( $absolute_path );
2368
		$files         = array();
2369
		if ( ! $dir = @opendir( $absolute_path ) ) {
2370
			return $files;
2371
		}
2372
2373
		while ( false !== $file = readdir( $dir ) ) {
2374
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2375
				continue;
2376
			}
2377
2378
			$file = "$absolute_path/$file";
2379
2380
			if ( ! is_file( $file ) ) {
2381
				continue;
2382
			}
2383
2384
			$files[] = $file;
2385
		}
2386
2387
		closedir( $dir );
2388
2389
		return $files;
2390
	}
2391
2392
	public static function activate_new_modules( $redirect = false ) {
2393
		if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2394
			return;
2395
		}
2396
2397
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2398 View Code Duplication
		if ( ! $jetpack_old_version ) {
2399
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2400
			/** This action is documented in class.jetpack.php */
2401
			do_action( 'updating_jetpack_version', $version, false );
2402
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2403
		}
2404
2405
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2406
2407
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2408
			return;
2409
		}
2410
2411
		$active_modules     = self::get_active_modules();
2412
		$reactivate_modules = array();
2413
		foreach ( $active_modules as $active_module ) {
2414
			$module = self::get_module( $active_module );
2415
			if ( ! isset( $module['changed'] ) ) {
2416
				continue;
2417
			}
2418
2419
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2420
				continue;
2421
			}
2422
2423
			$reactivate_modules[] = $active_module;
2424
			self::deactivate_module( $active_module );
2425
		}
2426
2427
		$new_version = JETPACK__VERSION . ':' . time();
2428
		/** This action is documented in class.jetpack.php */
2429
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2430
		Jetpack_Options::update_options(
2431
			array(
2432
				'version'     => $new_version,
2433
				'old_version' => $jetpack_old_version,
2434
			)
2435
		);
2436
2437
		self::state( 'message', 'modules_activated' );
2438
2439
		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...
2440
2441
		if ( $redirect ) {
2442
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2443
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2444
				$page = $_GET['page'];
2445
			}
2446
2447
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2448
			exit;
2449
		}
2450
	}
2451
2452
	/**
2453
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2454
	 * Make sure to tuck away module "library" files in a sub-directory.
2455
	 *
2456
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2457
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2458
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2459
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2460
	 *
2461
	 * @return array $modules Array of module slugs
2462
	 */
2463
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2464
		static $modules = null;
2465
2466
		if ( ! isset( $modules ) ) {
2467
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2468
			// Use the cache if we're on the front-end and it's available...
2469
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2470
				$modules = $available_modules_option[ JETPACK__VERSION ];
2471
			} else {
2472
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2473
2474
				$modules = array();
2475
2476
				foreach ( $files as $file ) {
2477
					if ( ! $headers = self::get_module( $file ) ) {
2478
						continue;
2479
					}
2480
2481
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2482
				}
2483
2484
				Jetpack_Options::update_option(
2485
					'available_modules',
2486
					array(
2487
						JETPACK__VERSION => $modules,
2488
					)
2489
				);
2490
			}
2491
		}
2492
2493
		/**
2494
		 * Filters the array of modules available to be activated.
2495
		 *
2496
		 * @since 2.4.0
2497
		 *
2498
		 * @param array $modules Array of available modules.
2499
		 * @param string $min_version Minimum version number required to use modules.
2500
		 * @param string $max_version Maximum version number required to use modules.
2501
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2502
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2503
		 */
2504
		$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...
2505
2506
		if ( ! $min_version && ! $max_version && is_null( $requires_connection ) && is_null( $requires_user_connection ) ) {
2507
			return array_keys( $mods );
2508
		}
2509
2510
		$r = array();
2511
		foreach ( $mods as $slug => $introduced ) {
2512
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2513
				continue;
2514
			}
2515
2516
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2517
				continue;
2518
			}
2519
2520
			$mod_details = self::get_module( $slug );
2521
2522
			if ( null !== $requires_connection && (bool) $requires_connection !== $mod_details['requires_connection'] ) {
2523
				continue;
2524
			}
2525
2526
			if ( null !== $requires_user_connection && (bool) $requires_user_connection !== $mod_details['requires_user_connection'] ) {
2527
				continue;
2528
			}
2529
2530
			$r[] = $slug;
2531
		}
2532
2533
		return $r;
2534
	}
2535
2536
	/**
2537
	 * Get default modules loaded on activation.
2538
	 *
2539
	 * @param bool|string $min_version Onlu return modules introduced in this version or later. Default is false, do not filter.
2540
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2541
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2542
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2543
	 *
2544
	 * @return array $modules Array of module slugs
2545
	 */
2546
	public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2547
		$return = array();
2548
2549
		foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2550
			$module_data = self::get_module( $module );
2551
2552
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2553
				case 'yes':
2554
					$return[] = $module;
2555
					break;
2556
				case 'public':
2557
					if ( Jetpack_Options::get_option( 'public' ) ) {
2558
						$return[] = $module;
2559
					}
2560
					break;
2561
				case 'no':
2562
				default:
2563
					break;
2564
			}
2565
		}
2566
		/**
2567
		 * Filters the array of default modules.
2568
		 *
2569
		 * @since 2.5.0
2570
		 *
2571
		 * @param array $return Array of default modules.
2572
		 * @param string $min_version Minimum version number required to use modules.
2573
		 * @param string $max_version Maximum version number required to use modules.
2574
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2575
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2576
		 */
2577
		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...
2578
	}
2579
2580
	/**
2581
	 * Checks activated modules during auto-activation to determine
2582
	 * if any of those modules are being deprecated.  If so, close
2583
	 * them out, and add any replacement modules.
2584
	 *
2585
	 * Runs at priority 99 by default.
2586
	 *
2587
	 * This is run late, so that it can still activate a module if
2588
	 * the new module is a replacement for another that the user
2589
	 * currently has active, even if something at the normal priority
2590
	 * would kibosh everything.
2591
	 *
2592
	 * @since 2.6
2593
	 * @uses jetpack_get_default_modules filter
2594
	 * @param array $modules
2595
	 * @return array
2596
	 */
2597
	function handle_deprecated_modules( $modules ) {
2598
		$deprecated_modules = array(
2599
			'debug'            => null,  // Closed out and moved to the debugger library.
2600
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2601
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2602
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2603
		);
2604
2605
		// Don't activate SSO if they never completed activating WPCC.
2606
		if ( self::is_module_active( 'wpcc' ) ) {
2607
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2608
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2609
				$deprecated_modules['wpcc'] = null;
2610
			}
2611
		}
2612
2613
		foreach ( $deprecated_modules as $module => $replacement ) {
2614
			if ( self::is_module_active( $module ) ) {
2615
				self::deactivate_module( $module );
2616
				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...
2617
					$modules[] = $replacement;
2618
				}
2619
			}
2620
		}
2621
2622
		return array_unique( $modules );
2623
	}
2624
2625
	/**
2626
	 * Checks activated plugins during auto-activation to determine
2627
	 * if any of those plugins are in the list with a corresponding module
2628
	 * that is not compatible with the plugin. The module will not be allowed
2629
	 * to auto-activate.
2630
	 *
2631
	 * @since 2.6
2632
	 * @uses jetpack_get_default_modules filter
2633
	 * @param array $modules
2634
	 * @return array
2635
	 */
2636
	function filter_default_modules( $modules ) {
2637
2638
		$active_plugins = self::get_active_plugins();
2639
2640
		if ( ! empty( $active_plugins ) ) {
2641
2642
			// For each module we'd like to auto-activate...
2643
			foreach ( $modules as $key => $module ) {
2644
				// If there are potential conflicts for it...
2645
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2646
					// For each potential conflict...
2647
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2648
						// If that conflicting plugin is active...
2649
						if ( in_array( $plugin, $active_plugins ) ) {
2650
							// Remove that item from being auto-activated.
2651
							unset( $modules[ $key ] );
2652
						}
2653
					}
2654
				}
2655
			}
2656
		}
2657
2658
		return $modules;
2659
	}
2660
2661
	/**
2662
	 * Extract a module's slug from its full path.
2663
	 */
2664
	public static function get_module_slug( $file ) {
2665
		return str_replace( '.php', '', basename( $file ) );
2666
	}
2667
2668
	/**
2669
	 * Generate a module's path from its slug.
2670
	 */
2671
	public static function get_module_path( $slug ) {
2672
		/**
2673
		 * Filters the path of a modules.
2674
		 *
2675
		 * @since 7.4.0
2676
		 *
2677
		 * @param array $return The absolute path to a module's root php file
2678
		 * @param string $slug The module slug
2679
		 */
2680
		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...
2681
	}
2682
2683
	/**
2684
	 * Load module data from module file. Headers differ from WordPress
2685
	 * plugin headers to avoid them being identified as standalone
2686
	 * plugins on the WordPress plugins page.
2687
	 */
2688
	public static function get_module( $module ) {
2689
		$headers = array(
2690
			'name'                      => 'Module Name',
2691
			'description'               => 'Module Description',
2692
			'sort'                      => 'Sort Order',
2693
			'recommendation_order'      => 'Recommendation Order',
2694
			'introduced'                => 'First Introduced',
2695
			'changed'                   => 'Major Changes In',
2696
			'deactivate'                => 'Deactivate',
2697
			'free'                      => 'Free',
2698
			'requires_connection'       => 'Requires Connection',
2699
			'requires_user_connection'  => 'Requires User Connection',
2700
			'auto_activate'             => 'Auto Activate',
2701
			'module_tags'               => 'Module Tags',
2702
			'feature'                   => 'Feature',
2703
			'additional_search_queries' => 'Additional Search Queries',
2704
			'plan_classes'              => 'Plans',
2705
		);
2706
2707
		static $modules_details;
2708
		$file = self::get_module_path( self::get_module_slug( $module ) );
2709
2710
		if ( isset( $modules_details[ $module ] ) ) {
2711
			$mod = $modules_details[ $module ];
2712
		} else {
2713
2714
			$mod = self::get_file_data( $file, $headers );
2715
			if ( empty( $mod['name'] ) ) {
2716
				return false;
2717
			}
2718
2719
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2720
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2721
			$mod['deactivate']               = empty( $mod['deactivate'] );
2722
			$mod['free']                     = empty( $mod['free'] );
2723
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2724
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2725
2726
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2727
				$mod['auto_activate'] = 'No';
2728
			} else {
2729
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2730
			}
2731
2732
			if ( $mod['module_tags'] ) {
2733
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2734
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2735
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2736
			} else {
2737
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2738
			}
2739
2740 View Code Duplication
			if ( $mod['plan_classes'] ) {
2741
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2742
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2743
			} else {
2744
				$mod['plan_classes'] = array( 'free' );
2745
			}
2746
2747 View Code Duplication
			if ( $mod['feature'] ) {
2748
				$mod['feature'] = explode( ',', $mod['feature'] );
2749
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2750
			} else {
2751
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2752
			}
2753
2754
			$modules_details[ $module ] = $mod;
2755
2756
		}
2757
2758
		/**
2759
		 * Filters the feature array on a module.
2760
		 *
2761
		 * This filter allows you to control where each module is filtered: Recommended,
2762
		 * and the default "Other" listing.
2763
		 *
2764
		 * @since 3.5.0
2765
		 *
2766
		 * @param array   $mod['feature'] The areas to feature this module:
2767
		 *     'Recommended' shows on the main Jetpack admin screen.
2768
		 *     'Other' should be the default if no other value is in the array.
2769
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2770
		 * @param array   $mod All the currently assembled module data.
2771
		 */
2772
		$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...
2773
2774
		/**
2775
		 * Filter the returned data about a module.
2776
		 *
2777
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2778
		 * so please be careful.
2779
		 *
2780
		 * @since 3.6.0
2781
		 *
2782
		 * @param array   $mod    The details of the requested module.
2783
		 * @param string  $module The slug of the module, e.g. sharedaddy
2784
		 * @param string  $file   The path to the module source file.
2785
		 */
2786
		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...
2787
	}
2788
2789
	/**
2790
	 * Like core's get_file_data implementation, but caches the result.
2791
	 */
2792
	public static function get_file_data( $file, $headers ) {
2793
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2794
		$file_name = basename( $file );
2795
2796
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2797
2798
		$file_data_option = get_transient( $cache_key );
2799
2800
		if ( ! is_array( $file_data_option ) ) {
2801
			delete_transient( $cache_key );
2802
			$file_data_option = false;
2803
		}
2804
2805
		if ( false === $file_data_option ) {
2806
			$file_data_option = array();
2807
		}
2808
2809
		$key           = md5( $file_name . serialize( $headers ) );
2810
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2811
2812
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2813
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2814
			return $file_data_option[ $key ];
2815
		}
2816
2817
		$data = get_file_data( $file, $headers );
2818
2819
		$file_data_option[ $key ] = $data;
2820
2821
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2822
2823
		return $data;
2824
	}
2825
2826
	/**
2827
	 * Return translated module tag.
2828
	 *
2829
	 * @param string $tag Tag as it appears in each module heading.
2830
	 *
2831
	 * @return mixed
2832
	 */
2833
	public static function translate_module_tag( $tag ) {
2834
		return jetpack_get_module_i18n_tag( $tag );
2835
	}
2836
2837
	/**
2838
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2839
	 *
2840
	 * @since 3.9.2
2841
	 *
2842
	 * @param array $modules
2843
	 *
2844
	 * @return string|void
2845
	 */
2846
	public static function get_translated_modules( $modules ) {
2847
		foreach ( $modules as $index => $module ) {
2848
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2849
			if ( isset( $module['name'] ) ) {
2850
				$modules[ $index ]['name'] = $i18n_module['name'];
2851
			}
2852
			if ( isset( $module['description'] ) ) {
2853
				$modules[ $index ]['description']       = $i18n_module['description'];
2854
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2855
			}
2856
		}
2857
		return $modules;
2858
	}
2859
2860
	/**
2861
	 * Get a list of activated modules as an array of module slugs.
2862
	 */
2863
	public static function get_active_modules() {
2864
		$active = Jetpack_Options::get_option( 'active_modules' );
2865
2866
		if ( ! is_array( $active ) ) {
2867
			$active = array();
2868
		}
2869
2870
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2871
			$active[] = 'vaultpress';
2872
		} else {
2873
			$active = array_diff( $active, array( 'vaultpress' ) );
2874
		}
2875
2876
		// If protect is active on the main site of a multisite, it should be active on all sites.
2877
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2878
			$active[] = 'protect';
2879
		}
2880
2881
		/**
2882
		 * Allow filtering of the active modules.
2883
		 *
2884
		 * Gives theme and plugin developers the power to alter the modules that
2885
		 * are activated on the fly.
2886
		 *
2887
		 * @since 5.8.0
2888
		 *
2889
		 * @param array $active Array of active module slugs.
2890
		 */
2891
		$active = apply_filters( 'jetpack_active_modules', $active );
2892
2893
		return array_unique( $active );
2894
	}
2895
2896
	/**
2897
	 * Check whether or not a Jetpack module is active.
2898
	 *
2899
	 * @param string $module The slug of a Jetpack module.
2900
	 * @return bool
2901
	 *
2902
	 * @static
2903
	 */
2904
	public static function is_module_active( $module ) {
2905
		return in_array( $module, self::get_active_modules() );
2906
	}
2907
2908
	public static function is_module( $module ) {
2909
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2910
	}
2911
2912
	/**
2913
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2914
	 *
2915
	 * @param bool $catch True to start catching, False to stop.
2916
	 *
2917
	 * @static
2918
	 */
2919
	public static function catch_errors( $catch ) {
2920
		static $display_errors, $error_reporting;
2921
2922
		if ( $catch ) {
2923
			$display_errors  = @ini_set( 'display_errors', 1 );
2924
			$error_reporting = @error_reporting( E_ALL );
2925
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2926
		} else {
2927
			@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...
2928
			@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...
2929
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2930
		}
2931
	}
2932
2933
	/**
2934
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2935
	 */
2936
	public static function catch_errors_on_shutdown() {
2937
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2938
	}
2939
2940
	/**
2941
	 * Rewrite any string to make paths easier to read.
2942
	 *
2943
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2944
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2945
	 *
2946
	 * @param $string
2947
	 * @return mixed
2948
	 */
2949
	public static function alias_directories( $string ) {
2950
		// ABSPATH has a trailing slash.
2951
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2952
		// WP_CONTENT_DIR does not have a trailing slash.
2953
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2954
2955
		return $string;
2956
	}
2957
2958
	public static function activate_default_modules(
2959
		$min_version = false,
2960
		$max_version = false,
2961
		$other_modules = array(),
2962
		$redirect = null,
2963
		$send_state_messages = null,
2964
		$requires_connection = null,
2965
		$requires_user_connection = null
2966
	) {
2967
		$jetpack = self::init();
2968
2969
		if ( is_null( $redirect ) ) {
2970
			if (
2971
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2972
			||
2973
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2974
			||
2975
				( defined( 'WP_CLI' ) && WP_CLI )
2976
			||
2977
				( defined( 'DOING_CRON' ) && DOING_CRON )
2978
			||
2979
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2980
			) {
2981
				$redirect = false;
2982
			} elseif ( is_admin() ) {
2983
				$redirect = true;
2984
			} else {
2985
				$redirect = false;
2986
			}
2987
		}
2988
2989
		if ( is_null( $send_state_messages ) ) {
2990
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2991
		}
2992
2993
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2994
		$modules = array_merge( $other_modules, $modules );
2995
2996
		// Look for standalone plugins and disable if active.
2997
2998
		$to_deactivate = array();
2999
		foreach ( $modules as $module ) {
3000
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3001
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
3002
			}
3003
		}
3004
3005
		$deactivated = array();
3006
		foreach ( $to_deactivate as $module => $deactivate_me ) {
3007
			list( $probable_file, $probable_title ) = $deactivate_me;
3008
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
3009
				$deactivated[] = $module;
3010
			}
3011
		}
3012
3013
		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...
3014
			if ( $send_state_messages ) {
3015
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
3016
			}
3017
3018
			if ( $redirect ) {
3019
				$url = add_query_arg(
3020
					array(
3021
						'action'   => 'activate_default_modules',
3022
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
3023
					),
3024
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
3025
				);
3026
				wp_safe_redirect( $url );
3027
				exit;
3028
			}
3029
		}
3030
3031
		/**
3032
		 * Fires before default modules are activated.
3033
		 *
3034
		 * @since 1.9.0
3035
		 *
3036
		 * @param string    $min_version Minimum version number required to use modules.
3037
		 * @param string    $max_version Maximum version number required to use modules.
3038
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3039
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3040
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3041
		 */
3042
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3043
3044
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3045
		if ( $send_state_messages ) {
3046
			self::restate();
3047
			self::catch_errors( true );
3048
		}
3049
3050
		$active = self::get_active_modules();
3051
3052
		foreach ( $modules as $module ) {
3053
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3054
				$active[] = $module;
3055
				self::update_active_modules( $active );
3056
				continue;
3057
			}
3058
3059
			if ( $send_state_messages && in_array( $module, $active ) ) {
3060
				$module_info = self::get_module( $module );
3061 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3062
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3063
					if ( $active_state = self::state( $state ) ) {
3064
						$active_state = explode( ',', $active_state );
3065
					} else {
3066
						$active_state = array();
3067
					}
3068
					$active_state[] = $module;
3069
					self::state( $state, implode( ',', $active_state ) );
3070
				}
3071
				continue;
3072
			}
3073
3074
			$file = self::get_module_path( $module );
3075
			if ( ! file_exists( $file ) ) {
3076
				continue;
3077
			}
3078
3079
			// we'll override this later if the plugin can be included without fatal error
3080
			if ( $redirect ) {
3081
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3082
			}
3083
3084
			if ( $send_state_messages ) {
3085
				self::state( 'error', 'module_activation_failed' );
3086
				self::state( 'module', $module );
3087
			}
3088
3089
			ob_start();
3090
			require_once $file;
3091
3092
			$active[] = $module;
3093
3094 View Code Duplication
			if ( $send_state_messages ) {
3095
3096
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3097
				if ( $active_state = self::state( $state ) ) {
3098
					$active_state = explode( ',', $active_state );
3099
				} else {
3100
					$active_state = array();
3101
				}
3102
				$active_state[] = $module;
3103
				self::state( $state, implode( ',', $active_state ) );
3104
			}
3105
3106
			self::update_active_modules( $active );
3107
3108
			ob_end_clean();
3109
		}
3110
3111
		if ( $send_state_messages ) {
3112
			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...
3113
			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...
3114
		}
3115
3116
		self::catch_errors( false );
3117
		/**
3118
		 * Fires when default modules are activated.
3119
		 *
3120
		 * @since 1.9.0
3121
		 *
3122
		 * @param string    $min_version Minimum version number required to use modules.
3123
		 * @param string    $max_version Maximum version number required to use modules.
3124
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3125
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3126
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3127
		 */
3128
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3129
	}
3130
3131
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3132
		/**
3133
		 * Fires before a module is activated.
3134
		 *
3135
		 * @since 2.6.0
3136
		 *
3137
		 * @param string $module Module slug.
3138
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3139
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3140
		 */
3141
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3142
3143
		$jetpack = self::init();
3144
3145
		if ( ! strlen( $module ) ) {
3146
			return false;
3147
		}
3148
3149
		if ( ! self::is_module( $module ) ) {
3150
			return false;
3151
		}
3152
3153
		// If it's already active, then don't do it again
3154
		$active = self::get_active_modules();
3155
		foreach ( $active as $act ) {
3156
			if ( $act == $module ) {
3157
				return true;
3158
			}
3159
		}
3160
3161
		$module_data = self::get_module( $module );
3162
3163
		$is_offline_mode = ( new Status() )->is_offline_mode();
3164
		if ( ! self::is_connection_ready() ) {
3165
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3166
				return false;
3167
			}
3168
3169
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3170
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3171
				return false;
3172
			}
3173
		}
3174
3175
		// Check and see if the old plugin is active
3176
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3177
			// Deactivate the old plugin
3178
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3179
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3180
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3181
				self::state( 'deactivated_plugins', $module );
3182
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3183
				exit;
3184
			}
3185
		}
3186
3187
		// Protect won't work with mis-configured IPs
3188
		if ( 'protect' === $module ) {
3189
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3190
			if ( ! jetpack_protect_get_ip() ) {
3191
				self::state( 'message', 'protect_misconfigured_ip' );
3192
				return false;
3193
			}
3194
		}
3195
3196
		if ( ! Jetpack_Plan::supports( $module ) ) {
3197
			return false;
3198
		}
3199
3200
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3201
		self::state( 'module', $module );
3202
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3203
3204
		self::catch_errors( true );
3205
		ob_start();
3206
		require self::get_module_path( $module );
3207
		/** This action is documented in class.jetpack.php */
3208
		do_action( 'jetpack_activate_module', $module );
3209
		$active[] = $module;
3210
		self::update_active_modules( $active );
3211
3212
		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...
3213
		ob_end_clean();
3214
		self::catch_errors( false );
3215
3216
		if ( $redirect ) {
3217
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3218
		}
3219
		if ( $exit ) {
3220
			exit;
3221
		}
3222
		return true;
3223
	}
3224
3225
	function activate_module_actions( $module ) {
3226
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3227
	}
3228
3229
	public static function deactivate_module( $module ) {
3230
		/**
3231
		 * Fires when a module is deactivated.
3232
		 *
3233
		 * @since 1.9.0
3234
		 *
3235
		 * @param string $module Module slug.
3236
		 */
3237
		do_action( 'jetpack_pre_deactivate_module', $module );
3238
3239
		$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...
3240
3241
		$active = self::get_active_modules();
3242
		$new    = array_filter( array_diff( $active, (array) $module ) );
3243
3244
		return self::update_active_modules( $new );
3245
	}
3246
3247
	public static function enable_module_configurable( $module ) {
3248
		$module = self::get_module_slug( $module );
3249
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3250
	}
3251
3252
	/**
3253
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3254
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3255
	 *
3256
	 * @param string $module Module slug
3257
	 * @return string $url module configuration URL
3258
	 */
3259
	public static function module_configuration_url( $module ) {
3260
		$module      = self::get_module_slug( $module );
3261
		$default_url = self::admin_url() . "#/settings?term=$module";
3262
		/**
3263
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3264
		 *
3265
		 * @since 6.9.0
3266
		 *
3267
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3268
		 */
3269
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3270
3271
		return $url;
3272
	}
3273
3274
	/* Installation */
3275
	public static function bail_on_activation( $message, $deactivate = true ) {
3276
		?>
3277
<!doctype html>
3278
<html>
3279
<head>
3280
<meta charset="<?php bloginfo( 'charset' ); ?>">
3281
<style>
3282
* {
3283
	text-align: center;
3284
	margin: 0;
3285
	padding: 0;
3286
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3287
}
3288
p {
3289
	margin-top: 1em;
3290
	font-size: 18px;
3291
}
3292
</style>
3293
<body>
3294
<p><?php echo esc_html( $message ); ?></p>
3295
</body>
3296
</html>
3297
		<?php
3298
		if ( $deactivate ) {
3299
			$plugins = get_option( 'active_plugins' );
3300
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3301
			$update  = false;
3302
			foreach ( $plugins as $i => $plugin ) {
3303
				if ( $plugin === $jetpack ) {
3304
					$plugins[ $i ] = false;
3305
					$update        = true;
3306
				}
3307
			}
3308
3309
			if ( $update ) {
3310
				update_option( 'active_plugins', array_filter( $plugins ) );
3311
			}
3312
		}
3313
		exit;
3314
	}
3315
3316
	/**
3317
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3318
	 *
3319
	 * @static
3320
	 */
3321
	public static function plugin_activation( $network_wide ) {
3322
		Jetpack_Options::update_option( 'activated', 1 );
3323
3324
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3325
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3326
		}
3327
3328
		if ( $network_wide ) {
3329
			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...
3330
		}
3331
3332
		// For firing one-off events (notices) immediately after activation
3333
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3334
3335
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3336
3337
		Health::on_jetpack_activated();
3338
3339
		self::plugin_initialize();
3340
	}
3341
3342
	public static function get_activation_source( $referer_url ) {
3343
3344
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3345
			return array( 'wp-cli', null );
3346
		}
3347
3348
		$referer = wp_parse_url( $referer_url );
3349
3350
		$source_type  = 'unknown';
3351
		$source_query = null;
3352
3353
		if ( ! is_array( $referer ) ) {
3354
			return array( $source_type, $source_query );
3355
		}
3356
3357
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3358
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3359
3360
		if ( isset( $referer['query'] ) ) {
3361
			parse_str( $referer['query'], $query_parts );
3362
		} else {
3363
			$query_parts = array();
3364
		}
3365
3366
		if ( $plugins_path === $referer['path'] ) {
3367
			$source_type = 'list';
3368
		} elseif ( $plugins_install_path === $referer['path'] ) {
3369
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3370
			switch ( $tab ) {
3371
				case 'popular':
3372
					$source_type = 'popular';
3373
					break;
3374
				case 'recommended':
3375
					$source_type = 'recommended';
3376
					break;
3377
				case 'favorites':
3378
					$source_type = 'favorites';
3379
					break;
3380
				case 'search':
3381
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3382
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3383
					break;
3384
				default:
3385
					$source_type = 'featured';
3386
			}
3387
		}
3388
3389
		return array( $source_type, $source_query );
3390
	}
3391
3392
	/**
3393
	 * Runs before bumping version numbers up to a new version
3394
	 *
3395
	 * @param string $version    Version:timestamp.
3396
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3397
	 */
3398
	public static function do_version_bump( $version, $old_version ) {
3399
		if ( $old_version ) { // For existing Jetpack installations.
3400
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3401
3402
			// If a front end page is visited after the update, the 'wp' action will fire.
3403
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3404
3405
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3406
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3407
		}
3408
	}
3409
3410
	/**
3411
	 * Sets the display_update_modal state.
3412
	 */
3413
	public static function set_update_modal_display() {
3414
		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...
3415
3416
	}
3417
3418
	/**
3419
	 * Enqueues the block library styles.
3420
	 *
3421
	 * @param string $hook The current admin page.
3422
	 */
3423
	public static function enqueue_block_style( $hook ) {
3424
		if ( 'toplevel_page_jetpack' === $hook ) {
3425
			wp_enqueue_style( 'wp-block-library' );
3426
		}
3427
	}
3428
3429
	/**
3430
	 * Sets the internal version number and activation state.
3431
	 *
3432
	 * @static
3433
	 */
3434
	public static function plugin_initialize() {
3435
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3436
			Jetpack_Options::update_option( 'activated', 2 );
3437
		}
3438
3439 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3440
			$version = $old_version = JETPACK__VERSION . ':' . time();
3441
			/** This action is documented in class.jetpack.php */
3442
			do_action( 'updating_jetpack_version', $version, false );
3443
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3444
		}
3445
3446
		self::load_modules();
3447
3448
		Jetpack_Options::delete_option( 'do_activate' );
3449
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3450
	}
3451
3452
	/**
3453
	 * Removes all connection options
3454
	 *
3455
	 * @static
3456
	 */
3457
	public static function plugin_deactivation() {
3458
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3459
		$tracking = new Tracking();
3460
		$tracking->record_user_event( 'deactivate_plugin', array() );
3461
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3462
			Jetpack_Network::init()->deactivate();
3463
		} else {
3464
			self::disconnect( false );
3465
			// Jetpack_Heartbeat::init()->deactivate();
3466
		}
3467
	}
3468
3469
	/**
3470
	 * Disconnects from the Jetpack servers.
3471
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3472
	 *
3473
	 * @static
3474
	 */
3475
	public static function disconnect( $update_activated_state = true ) {
3476
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3477
3478
		$connection = self::connection();
3479
3480
		( new Nonce_Handler() )->clean_all();
3481
3482
		// If the site is in an IDC because sync is not allowed,
3483
		// let's make sure to not disconnect the production site.
3484
		if ( ! Identity_Crisis::validate_sync_error_idc_option() ) {
3485
			$tracking = new Tracking();
3486
			$tracking->record_user_event( 'disconnect_site', array() );
3487
3488
			$connection->disconnect_site_wpcom( true );
3489
		}
3490
3491
		$connection->delete_all_connection_tokens( true );
3492
		Identity_Crisis::clear_all_idc_options();
3493
3494
		if ( $update_activated_state ) {
3495
			Jetpack_Options::update_option( 'activated', 4 );
3496
		}
3497
3498
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3499
			// Check then record unique disconnection if site has never been disconnected previously
3500
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3501
				$jetpack_unique_connection['disconnected'] = 1;
3502
			} else {
3503
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3504
					// track unique disconnect
3505
					$jetpack = self::init();
3506
3507
					$jetpack->stat( 'connections', 'unique-disconnect' );
3508
					$jetpack->do_stats( 'server_side' );
3509
				}
3510
				// increment number of times disconnected
3511
				$jetpack_unique_connection['disconnected'] += 1;
3512
			}
3513
3514
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3515
		}
3516
3517
		// Delete all the sync related data. Since it could be taking up space.
3518
		Sender::get_instance()->uninstall();
3519
3520
	}
3521
3522
	/**
3523
	 * Disconnects the user
3524
	 *
3525
	 * @param int $user_id The user ID to disconnect.
3526
	 */
3527
	public function disconnect_user( $user_id ) {
3528
		$this->connection_manager->disconnect_user( $user_id );
3529
	}
3530
3531
	/**
3532
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3533
	 *
3534
	 * @deprecated since Jetpack 9.7.0
3535
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
3536
	 *
3537
	 * @return bool|WP_Error
3538
	 */
3539
	public static function try_registration() {
3540
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
3541
		return static::connection()->try_registration();
3542
	}
3543
3544
	/**
3545
	 * Checking the domain names in beta versions.
3546
	 * If this is a development version, before attempting to connect, let's make sure that the domains are viable.
3547
	 *
3548
	 * @param null|\WP_Error $error The domain validation error, or `null` if everything's fine.
3549
	 *
3550
	 * @return null|\WP_Error The domain validation error, or `null` if everything's fine.
3551
	 */
3552
	public static function registration_check_domains( $error ) {
3553
		if ( static::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3554
			$domains_to_check = array_unique(
3555
				array(
3556
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3557
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3558
				)
3559
			);
3560
			foreach ( $domains_to_check as $domain ) {
3561
				$result = static::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3560 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...
3562
				if ( is_wp_error( $result ) ) {
3563
					return $result;
3564
				}
3565
			}
3566
		}
3567
3568
		return $error;
3569
	}
3570
3571
	/**
3572
	 * Tracking an internal event log. Try not to put too much chaff in here.
3573
	 *
3574
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3575
	 */
3576
	public static function log( $code, $data = null ) {
3577
		// only grab the latest 200 entries
3578
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3579
3580
		// Append our event to the log
3581
		$log_entry = array(
3582
			'time'    => time(),
3583
			'user_id' => get_current_user_id(),
3584
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3585
			'code'    => $code,
3586
		);
3587
		// Don't bother storing it unless we've got some.
3588
		if ( ! is_null( $data ) ) {
3589
			$log_entry['data'] = $data;
3590
		}
3591
		$log[] = $log_entry;
3592
3593
		// Try add_option first, to make sure it's not autoloaded.
3594
		// @todo: Add an add_option method to Jetpack_Options
3595
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3596
			Jetpack_Options::update_option( 'log', $log );
3597
		}
3598
3599
		/**
3600
		 * Fires when Jetpack logs an internal event.
3601
		 *
3602
		 * @since 3.0.0
3603
		 *
3604
		 * @param array $log_entry {
3605
		 *  Array of details about the log entry.
3606
		 *
3607
		 *  @param string time Time of the event.
3608
		 *  @param int user_id ID of the user who trigerred the event.
3609
		 *  @param int blog_id Jetpack Blog ID.
3610
		 *  @param string code Unique name for the event.
3611
		 *  @param string data Data about the event.
3612
		 * }
3613
		 */
3614
		do_action( 'jetpack_log_entry', $log_entry );
3615
	}
3616
3617
	/**
3618
	 * Get the internal event log.
3619
	 *
3620
	 * @param $event (string) - only return the specific log events
3621
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3622
	 *
3623
	 * @return array of log events || WP_Error for invalid params
3624
	 */
3625
	public static function get_log( $event = false, $num = false ) {
3626
		if ( $event && ! is_string( $event ) ) {
3627
			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...
3628
		}
3629
3630
		if ( $num && ! is_numeric( $num ) ) {
3631
			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...
3632
		}
3633
3634
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3635
3636
		// If nothing set - act as it did before, otherwise let's start customizing the output
3637
		if ( ! $num && ! $event ) {
3638
			return $entire_log;
3639
		} else {
3640
			$entire_log = array_reverse( $entire_log );
3641
		}
3642
3643
		$custom_log_output = array();
3644
3645
		if ( $event ) {
3646
			foreach ( $entire_log as $log_event ) {
3647
				if ( $event == $log_event['code'] ) {
3648
					$custom_log_output[] = $log_event;
3649
				}
3650
			}
3651
		} else {
3652
			$custom_log_output = $entire_log;
3653
		}
3654
3655
		if ( $num ) {
3656
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3657
		}
3658
3659
		return $custom_log_output;
3660
	}
3661
3662
	/**
3663
	 * Log modification of important settings.
3664
	 */
3665
	public static function log_settings_change( $option, $old_value, $value ) {
3666
		switch ( $option ) {
3667
			case 'jetpack_sync_non_public_post_stati':
3668
				self::log( $option, $value );
3669
				break;
3670
		}
3671
	}
3672
3673
	/**
3674
	 * Return stat data for WPCOM sync
3675
	 */
3676
	public static function get_stat_data( $encode = true, $extended = true ) {
3677
		$data = Jetpack_Heartbeat::generate_stats_array();
3678
3679
		if ( $extended ) {
3680
			$additional_data = self::get_additional_stat_data();
3681
			$data            = array_merge( $data, $additional_data );
3682
		}
3683
3684
		if ( $encode ) {
3685
			return json_encode( $data );
3686
		}
3687
3688
		return $data;
3689
	}
3690
3691
	/**
3692
	 * Get additional stat data to sync to WPCOM
3693
	 */
3694
	public static function get_additional_stat_data( $prefix = '' ) {
3695
		$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...
3696
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3697
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3698
		$return[ "{$prefix}site-count" ]    = 0;
3699
3700
		if ( function_exists( 'get_blog_count' ) ) {
3701
			$return[ "{$prefix}site-count" ] = get_blog_count();
3702
		}
3703
		return $return;
3704
	}
3705
3706
	private static function get_site_user_count() {
3707
		global $wpdb;
3708
3709
		if ( function_exists( 'wp_is_large_network' ) ) {
3710
			if ( wp_is_large_network( 'users' ) ) {
3711
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3712
			}
3713
		}
3714
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3715
			// It wasn't there, so regenerate the data and save the transient
3716
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3717
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3718
		}
3719
		return $user_count;
3720
	}
3721
3722
	/* Admin Pages */
3723
3724
	function admin_init() {
3725
		// If the plugin is not connected, display a connect message.
3726
		if (
3727
			// the plugin was auto-activated and needs its candy
3728
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3729
		||
3730
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3731
			! Jetpack_Options::get_option( 'activated' )
3732
		) {
3733
			self::plugin_initialize();
3734
		}
3735
3736
		$is_offline_mode              = ( new Status() )->is_offline_mode();
3737
		$fallback_no_verify_ssl_certs = Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
3738
		/** Already documented in automattic/jetpack-connection::src/class-client.php */
3739
		$client_verify_ssl_certs = apply_filters( 'jetpack_client_verify_ssl_certs', false );
3740
3741
		if ( ! $is_offline_mode ) {
3742
			Jetpack_Connection_Banner::init();
3743
		}
3744
3745
		if ( ( self::is_connection_ready() || $is_offline_mode ) && false === $fallback_no_verify_ssl_certs && ! $client_verify_ssl_certs ) {
3746
			// Upgrade: 1.1 -> 1.1.1
3747
			// Check and see if host can verify the Jetpack servers' SSL certificate
3748
			$args = array();
3749
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3750
		}
3751
3752
		Jetpack_Recommendations_Banner::init();
3753
3754
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3755
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3756
		}
3757
3758
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3759
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3760
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3761
3762
		if ( isset( $_COOKIE['jetpackState']['display_update_modal'] ) ) {
3763
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3764
		}
3765
3766
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3767
3768
		if ( self::is_connection_ready() || $is_offline_mode ) {
3769
			// Artificially throw errors in certain specific cases during plugin activation.
3770
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3771
		}
3772
3773
		// Add custom column in wp-admin/users.php to show whether user is linked.
3774
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3775
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3776
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3777
	}
3778
3779
	function admin_body_class( $admin_body_class = '' ) {
3780
		$classes = explode( ' ', trim( $admin_body_class ) );
3781
3782
		$classes[] = self::is_connection_ready() ? 'jetpack-connected' : 'jetpack-disconnected';
3783
3784
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3785
		return " $admin_body_class ";
3786
	}
3787
3788
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3789
		return $admin_body_class . ' jetpack-pagestyles ';
3790
	}
3791
3792
	/**
3793
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3794
	 * This function artificially throws errors for such cases (per a specific list).
3795
	 *
3796
	 * @param string $plugin The activated plugin.
3797
	 */
3798
	function throw_error_on_activate_plugin( $plugin ) {
3799
		$active_modules = self::get_active_modules();
3800
3801
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3802
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3803
			$throw = false;
3804
3805
			// Try and make sure it really was the stats plugin
3806
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3807
				if ( 'stats.php' == basename( $plugin ) ) {
3808
					$throw = true;
3809
				}
3810
			} else {
3811
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3812
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3813
					$throw = true;
3814
				}
3815
			}
3816
3817
			if ( $throw ) {
3818
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3819
			}
3820
		}
3821
	}
3822
3823
	function intercept_plugin_error_scrape_init() {
3824
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3825
	}
3826
3827
	function intercept_plugin_error_scrape( $action, $result ) {
3828
		if ( ! $result ) {
3829
			return;
3830
		}
3831
3832
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3833
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3834
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3835
			}
3836
		}
3837
	}
3838
3839
	/**
3840
	 * Register the remote file upload request handlers, if needed.
3841
	 *
3842
	 * @access public
3843
	 */
3844
	public function add_remote_request_handlers() {
3845
		// Remote file uploads are allowed only via AJAX requests.
3846
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3847
			return;
3848
		}
3849
3850
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3851
		$remote_request_actions = array(
3852
			'jetpack_upload_file',
3853
			'jetpack_update_file',
3854
		);
3855
3856
		// phpcs:ignore WordPress.Security.NonceVerification
3857
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3858
			return;
3859
		}
3860
3861
		// Require Jetpack authentication for the remote file upload AJAX requests.
3862
		if ( ! $this->connection_manager ) {
3863
			$this->connection_manager = new Connection_Manager();
3864
		}
3865
3866
		$this->connection_manager->require_jetpack_authentication();
3867
3868
		// Register the remote file upload AJAX handlers.
3869
		foreach ( $remote_request_actions as $action ) {
3870
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3871
		}
3872
	}
3873
3874
	/**
3875
	 * Handler for Jetpack remote file uploads.
3876
	 *
3877
	 * @access public
3878
	 */
3879
	public function remote_request_handlers() {
3880
		$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...
3881
3882
		switch ( current_filter() ) {
3883
			case 'wp_ajax_nopriv_jetpack_upload_file':
3884
				$response = $this->upload_handler();
3885
				break;
3886
3887
			case 'wp_ajax_nopriv_jetpack_update_file':
3888
				$response = $this->upload_handler( true );
3889
				break;
3890
			default:
3891
				$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...
3892
				break;
3893
		}
3894
3895
		if ( ! $response ) {
3896
			$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...
3897
		}
3898
3899
		if ( is_wp_error( $response ) ) {
3900
			$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...
3901
			$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...
3902
			$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...
3903
3904
			if ( ! is_int( $status_code ) ) {
3905
				$status_code = 400;
3906
			}
3907
3908
			status_header( $status_code );
3909
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3910
		}
3911
3912
		status_header( 200 );
3913
		if ( true === $response ) {
3914
			exit;
3915
		}
3916
3917
		die( json_encode( (object) $response ) );
3918
	}
3919
3920
	/**
3921
	 * Uploads a file gotten from the global $_FILES.
3922
	 * If `$update_media_item` is true and `post_id` is defined
3923
	 * the attachment file of the media item (gotten through of the post_id)
3924
	 * will be updated instead of add a new one.
3925
	 *
3926
	 * @param  boolean $update_media_item - update media attachment
3927
	 * @return array - An array describing the uploadind files process
3928
	 */
3929
	function upload_handler( $update_media_item = false ) {
3930
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3931
			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...
3932
		}
3933
3934
		$user = wp_authenticate( '', '' );
3935
		if ( ! $user || is_wp_error( $user ) ) {
3936
			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...
3937
		}
3938
3939
		wp_set_current_user( $user->ID );
3940
3941
		if ( ! current_user_can( 'upload_files' ) ) {
3942
			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...
3943
		}
3944
3945
		if ( empty( $_FILES ) ) {
3946
			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...
3947
		}
3948
3949
		foreach ( array_keys( $_FILES ) as $files_key ) {
3950
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3951
				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...
3952
			}
3953
		}
3954
3955
		$media_keys = array_keys( $_FILES['media'] );
3956
3957
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3958
		if ( ! $token || is_wp_error( $token ) ) {
3959
			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...
3960
		}
3961
3962
		$uploaded_files = array();
3963
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3964
		unset( $GLOBALS['post'] );
3965
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3966
			$file = array();
3967
			foreach ( $media_keys as $media_key ) {
3968
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3969
			}
3970
3971
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3972
3973
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3974
			if ( $hmac_provided !== $hmac_file ) {
3975
				$uploaded_files[ $index ] = (object) array(
3976
					'error'             => 'invalid_hmac',
3977
					'error_description' => 'The corresponding HMAC for this file does not match',
3978
				);
3979
				continue;
3980
			}
3981
3982
			$_FILES['.jetpack.upload.'] = $file;
3983
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3984
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3985
				$post_id = 0;
3986
			}
3987
3988
			if ( $update_media_item ) {
3989
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3990
					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...
3991
				}
3992
3993
				$media_array = $_FILES['media'];
3994
3995
				$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...
3996
				$file_array['type']     = $media_array['type'][0];
3997
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3998
				$file_array['error']    = $media_array['error'][0];
3999
				$file_array['size']     = $media_array['size'][0];
4000
4001
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
4002
4003
				if ( is_wp_error( $edited_media_item ) ) {
4004
					return $edited_media_item;
4005
				}
4006
4007
				$response = (object) array(
4008
					'id'   => (string) $post_id,
4009
					'file' => (string) $edited_media_item->post_title,
4010
					'url'  => (string) wp_get_attachment_url( $post_id ),
4011
					'type' => (string) $edited_media_item->post_mime_type,
4012
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
4013
				);
4014
4015
				return (array) array( $response );
4016
			}
4017
4018
			$attachment_id = media_handle_upload(
4019
				'.jetpack.upload.',
4020
				$post_id,
4021
				array(),
4022
				array(
4023
					'action' => 'jetpack_upload_file',
4024
				)
4025
			);
4026
4027
			if ( ! $attachment_id ) {
4028
				$uploaded_files[ $index ] = (object) array(
4029
					'error'             => 'unknown',
4030
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
4031
				);
4032
			} elseif ( is_wp_error( $attachment_id ) ) {
4033
				$uploaded_files[ $index ] = (object) array(
4034
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
4035
					'error_description' => $attachment_id->get_error_message(),
4036
				);
4037
			} else {
4038
				$attachment               = get_post( $attachment_id );
4039
				$uploaded_files[ $index ] = (object) array(
4040
					'id'   => (string) $attachment_id,
4041
					'file' => $attachment->post_title,
4042
					'url'  => wp_get_attachment_url( $attachment_id ),
4043
					'type' => $attachment->post_mime_type,
4044
					'meta' => wp_get_attachment_metadata( $attachment_id ),
4045
				);
4046
				// Zip files uploads are not supported unless they are done for installation purposed
4047
				// lets delete them in case something goes wrong in this whole process
4048
				if ( 'application/zip' === $attachment->post_mime_type ) {
4049
					// Schedule a cleanup for 2 hours from now in case of failed install.
4050
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
4051
				}
4052
			}
4053
		}
4054
		if ( ! is_null( $global_post ) ) {
4055
			$GLOBALS['post'] = $global_post;
4056
		}
4057
4058
		return $uploaded_files;
4059
	}
4060
4061
	/**
4062
	 * Add help to the Jetpack page
4063
	 *
4064
	 * @since Jetpack (1.2.3)
4065
	 * @return false if not the Jetpack page
4066
	 */
4067
	function admin_help() {
4068
		$current_screen = get_current_screen();
4069
4070
		// Overview
4071
		$current_screen->add_help_tab(
4072
			array(
4073
				'id'      => 'home',
4074
				'title'   => __( 'Home', 'jetpack' ),
4075
				'content' =>
4076
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4077
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4078
					'<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>',
4079
			)
4080
		);
4081
4082
		// Screen Content
4083
		if ( current_user_can( 'manage_options' ) ) {
4084
			$current_screen->add_help_tab(
4085
				array(
4086
					'id'      => 'settings',
4087
					'title'   => __( 'Settings', 'jetpack' ),
4088
					'content' =>
4089
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4090
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4091
						'<ol>' .
4092
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4093
							'<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>' .
4094
						'</ol>' .
4095
						'<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>',
4096
				)
4097
			);
4098
		}
4099
4100
		// Help Sidebar
4101
		$support_url = Redirect::get_url( 'jetpack-support' );
4102
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4103
		$current_screen->set_help_sidebar(
4104
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4105
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4106
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4107
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4108
		);
4109
	}
4110
4111
	function admin_menu_css() {
4112
		wp_enqueue_style( 'jetpack-icons' );
4113
	}
4114
4115
	function admin_menu_order() {
4116
		return true;
4117
	}
4118
4119
	function jetpack_menu_order( $menu_order ) {
4120
		$jp_menu_order = array();
4121
4122
		foreach ( $menu_order as $index => $item ) {
4123
			if ( $item != 'jetpack' ) {
4124
				$jp_menu_order[] = $item;
4125
			}
4126
4127
			if ( $index == 0 ) {
4128
				$jp_menu_order[] = 'jetpack';
4129
			}
4130
		}
4131
4132
		return $jp_menu_order;
4133
	}
4134
4135
	function admin_banner_styles() {
4136
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4137
4138 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4139
			wp_register_style(
4140
				'jetpack-dops-style',
4141
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4142
				array(),
4143
				JETPACK__VERSION
4144
			);
4145
		}
4146
4147
		wp_enqueue_style(
4148
			'jetpack',
4149
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4150
			array( 'jetpack-dops-style' ),
4151
			JETPACK__VERSION . '-20121016'
4152
		);
4153
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4154
		wp_style_add_data( 'jetpack', 'suffix', $min );
4155
	}
4156
4157
	function plugin_action_links( $actions ) {
4158
4159
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4160
4161
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
4162
			return array_merge(
4163
				$jetpack_home,
4164
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4165
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4166
				$actions
4167
			);
4168
		}
4169
4170
		return array_merge( $jetpack_home, $actions );
4171
	}
4172
4173
	/**
4174
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4175
	 *
4176
	 * @param string $hook The current admin page.
4177
	 *
4178
	 * @return void
4179
	 */
4180
	public function deactivate_dialog( $hook ) {
4181
		if (
4182
			'plugins.php' === $hook
4183
			&& self::is_connection_ready()
4184
		) {
4185
4186
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4187
4188
			if ( count( $active_plugins_using_connection ) > 1 ) {
4189
4190
				add_thickbox();
4191
4192
				wp_register_script(
4193
					'jp-tracks',
4194
					'//stats.wp.com/w.js',
4195
					array(),
4196
					gmdate( 'YW' ),
4197
					true
4198
				);
4199
4200
				wp_register_script(
4201
					'jp-tracks-functions',
4202
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4203
					array( 'jp-tracks' ),
4204
					JETPACK__VERSION,
4205
					false
4206
				);
4207
4208
				wp_enqueue_script(
4209
					'jetpack-deactivate-dialog-js',
4210
					Assets::get_file_url_for_environment(
4211
						'_inc/build/jetpack-deactivate-dialog.min.js',
4212
						'_inc/jetpack-deactivate-dialog.js'
4213
					),
4214
					array( 'jquery', 'jp-tracks-functions' ),
4215
					JETPACK__VERSION,
4216
					true
4217
				);
4218
4219
				wp_localize_script(
4220
					'jetpack-deactivate-dialog-js',
4221
					'deactivate_dialog',
4222
					array(
4223
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4224
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4225
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4226
					)
4227
				);
4228
4229
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4230
4231
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4232
			}
4233
		}
4234
	}
4235
4236
	/**
4237
	 * Outputs the content of the deactivation modal
4238
	 *
4239
	 * @return void
4240
	 */
4241
	public function deactivate_dialog_content() {
4242
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4243
		unset( $active_plugins_using_connection['jetpack'] );
4244
		$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 4242 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...
4245
	}
4246
4247
	/**
4248
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4249
	 *
4250
	 * @param string $login_url The wp-login URL.
4251
	 * @param string $redirect  URL to redirect users after logging in.
4252
	 * @since Jetpack 8.4
4253
	 * @return string
4254
	 */
4255
	public function login_url( $login_url, $redirect ) {
4256
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4257
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4258
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4259
		}
4260
		return $login_url;
4261
	}
4262
4263
	/**
4264
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4265
	 *
4266
	 * @since Jetpack 8.4
4267
	 */
4268
	public function login_init() {
4269
		// phpcs:ignore WordPress.Security.NonceVerification
4270
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4271
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4272
			wp_safe_redirect(
4273
				add_query_arg(
4274
					array(
4275
						'forceInstall' => 1,
4276
						'url'          => rawurlencode( get_site_url() ),
4277
					),
4278
					// @todo provide way to go to specific calypso env.
4279
					self::get_calypso_host() . 'jetpack/connect'
4280
				)
4281
			);
4282
			exit;
4283
		}
4284
	}
4285
4286
	/*
4287
	 * Registration flow:
4288
	 * 1 - ::admin_page_load() action=register
4289
	 * 2 - ::try_registration()
4290
	 * 3 - ::register()
4291
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4292
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4293
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4294
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4295
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4296
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4297
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4298
	 *       jetpack_id, jetpack_secret, jetpack_public
4299
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4300
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4301
	 * 5 - user logs in with WP.com account
4302
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4303
	 *		- Manager::authorize()
4304
	 *		- Manager::get_token()
4305
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4306
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4307
	 *			- which responds with access_token, token_type, scope
4308
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4309
	 *		- Jetpack::activate_default_modules()
4310
	 *     		- Deactivates deprecated plugins
4311
	 *     		- Activates all default modules
4312
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4313
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4314
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4315
	 *     Done!
4316
	 */
4317
4318
	/**
4319
	 * Handles the page load events for the Jetpack admin page
4320
	 */
4321
	function admin_page_load() {
4322
		$error = false;
4323
4324
		// Make sure we have the right body class to hook stylings for subpages off of.
4325
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4326
4327
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4328
			// Should only be used in intermediate redirects to preserve state across redirects
4329
			self::restate();
4330
		}
4331
4332
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4333
			// @todo: Add validation against a known allowed list.
4334
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4335
			// User clicked in the iframe to link their accounts
4336
			if ( ! self::connection()->is_user_connected() ) {
4337
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4338
4339
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4340
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4341
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4342
4343
				if ( isset( $_GET['notes_iframe'] ) ) {
4344
					$connect_url .= '&notes_iframe';
4345
				}
4346
				wp_redirect( $connect_url );
4347
				exit;
4348
			} else {
4349
				if ( ! isset( $_GET['calypso_env'] ) ) {
4350
					self::state( 'message', 'already_authorized' );
4351
					wp_safe_redirect( self::admin_url() );
4352
					exit;
4353
				} else {
4354
					$connect_url  = $this->build_connect_url( true, false, $from );
4355
					$connect_url .= '&already_authorized=true';
4356
					wp_redirect( $connect_url );
4357
					exit;
4358
				}
4359
			}
4360
		}
4361
4362
		if ( isset( $_GET['action'] ) ) {
4363
			switch ( $_GET['action'] ) {
4364
				case 'authorize_redirect':
4365
					self::log( 'authorize_redirect' );
4366
4367
					add_filter(
4368
						'allowed_redirect_hosts',
4369
						function ( $domains ) {
4370
							$domains[] = 'jetpack.com';
4371
							$domains[] = 'jetpack.wordpress.com';
4372
							$domains[] = 'wordpress.com';
4373
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4374
							return array_unique( $domains );
4375
						}
4376
					);
4377
4378
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4379
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4380
4381
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4382
						// The destination URL is missing or invalid, nothing to do here.
4383
						exit;
4384
					}
4385
4386
					if ( static::connection()->is_connected() && static::connection()->is_user_connected() ) {
4387
						// The user is either already connected, or finished the connection process.
4388
						wp_safe_redirect( $dest_url );
4389
						exit;
4390
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4391
						// The user decided not to proceed with setting up the connection.
4392
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4393
						exit;
4394
					}
4395
4396
					$redirect_url = self::admin_url(
4397
						array(
4398
							'page'     => 'jetpack',
4399
							'action'   => 'authorize_redirect',
4400
							'dest_url' => rawurlencode( $dest_url ),
4401
							'done'     => '1',
4402
						)
4403
					);
4404
4405
					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...
4406
					exit;
4407
				case 'authorize':
4408
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4409
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4410
					exit;
4411
				case 'register':
4412
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4413
						$error = 'cheatin';
4414
						break;
4415
					}
4416
					check_admin_referer( 'jetpack-register' );
4417
					self::log( 'register' );
4418
					self::maybe_set_version_option();
4419
					$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4420
					if ( $from ) {
4421
						static::connection()->add_register_request_param( 'from', (string) $from );
4422
					}
4423
					$registered = static::connection()->try_registration();
4424
					if ( is_wp_error( $registered ) ) {
4425
						$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...
4426
						self::state( 'error', $error );
4427
						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...
4428
4429
						/**
4430
						 * Jetpack registration Error.
4431
						 *
4432
						 * @since 7.5.0
4433
						 *
4434
						 * @param string|int $error The error code.
4435
						 * @param \WP_Error $registered The error object.
4436
						 */
4437
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4438
						break;
4439
					}
4440
4441
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4442
4443
					/**
4444
					 * Jetpack registration Success.
4445
					 *
4446
					 * @since 7.5.0
4447
					 *
4448
					 * @param string $from 'from' GET parameter;
4449
					 */
4450
					do_action( 'jetpack_connection_register_success', $from );
4451
4452
					$url = $this->build_connect_url( true, $redirect, $from );
4453
4454
					if ( ! empty( $_GET['onboarding'] ) ) {
4455
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4456
					}
4457
4458
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4459
						$url = add_query_arg( 'auth_approved', 'true', $url );
4460
					}
4461
4462
					wp_redirect( $url );
4463
					exit;
4464
				case 'activate':
4465
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4466
						$error = 'cheatin';
4467
						break;
4468
					}
4469
4470
					$module = stripslashes( $_GET['module'] );
4471
					check_admin_referer( "jetpack_activate-$module" );
4472
					self::log( 'activate', $module );
4473
					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...
4474
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4475
					}
4476
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4477
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4478
					exit;
4479
				case 'activate_default_modules':
4480
					check_admin_referer( 'activate_default_modules' );
4481
					self::log( 'activate_default_modules' );
4482
					self::restate();
4483
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4484
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4485
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4486
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4487
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4488
					exit;
4489 View Code Duplication
				case 'disconnect':
4490
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4491
						$error = 'cheatin';
4492
						break;
4493
					}
4494
4495
					check_admin_referer( 'jetpack-disconnect' );
4496
					self::log( 'disconnect' );
4497
					self::disconnect();
4498
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4499
					exit;
4500 View Code Duplication
				case 'reconnect':
4501
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4502
						$error = 'cheatin';
4503
						break;
4504
					}
4505
4506
					check_admin_referer( 'jetpack-reconnect' );
4507
					self::log( 'reconnect' );
4508
					self::disconnect();
4509
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4510
					exit;
4511 View Code Duplication
				case 'deactivate':
4512
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4513
						$error = 'cheatin';
4514
						break;
4515
					}
4516
4517
					$modules = stripslashes( $_GET['module'] );
4518
					check_admin_referer( "jetpack_deactivate-$modules" );
4519
					foreach ( explode( ',', $modules ) as $module ) {
4520
						self::log( 'deactivate', $module );
4521
						self::deactivate_module( $module );
4522
						self::state( 'message', 'module_deactivated' );
4523
					}
4524
					self::state( 'module', $modules );
4525
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4526
					exit;
4527
				case 'unlink':
4528
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4529
					check_admin_referer( 'jetpack-unlink' );
4530
					self::log( 'unlink' );
4531
					$this->connection_manager->disconnect_user();
4532
					self::state( 'message', 'unlinked' );
4533
					if ( 'sub-unlink' == $redirect ) {
4534
						wp_safe_redirect( admin_url() );
4535
					} else {
4536
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4537
					}
4538
					exit;
4539
				case 'onboard':
4540
					if ( ! current_user_can( 'manage_options' ) ) {
4541
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4542
					} else {
4543
						self::create_onboarding_token();
4544
						$url = $this->build_connect_url( true );
4545
4546
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4547
							$url = add_query_arg( 'onboarding', $token, $url );
4548
						}
4549
4550
						$calypso_env = $this->get_calypso_env();
4551
						if ( ! empty( $calypso_env ) ) {
4552
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4553
						}
4554
4555
						wp_redirect( $url );
4556
						exit;
4557
					}
4558
					exit;
4559
				default:
4560
					/**
4561
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4562
					 *
4563
					 * @since 2.6.0
4564
					 *
4565
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4566
					 */
4567
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4568
			}
4569
		}
4570
4571
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4572
			self::activate_new_modules( true );
4573
		}
4574
4575
		$message_code = self::state( 'message' );
4576
		if ( self::state( 'optin-manage' ) ) {
4577
			$activated_manage = $message_code;
4578
			$message_code     = 'jetpack-manage';
4579
		}
4580
4581
		switch ( $message_code ) {
4582
			case 'jetpack-manage':
4583
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4584
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4585
				$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>';
4586
				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...
4587
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4588
				}
4589
				break;
4590
4591
		}
4592
4593
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4594
4595
		if ( ! empty( $deactivated_plugins ) ) {
4596
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4597
			$deactivated_titles  = array();
4598
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4599
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4600
					continue;
4601
				}
4602
4603
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4604
			}
4605
4606
			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...
4607
				if ( $this->message ) {
4608
					$this->message .= "<br /><br />\n";
4609
				}
4610
4611
				$this->message .= wp_sprintf(
4612
					_n(
4613
						'Jetpack contains the most recent version of the old %l plugin.',
4614
						'Jetpack contains the most recent versions of the old %l plugins.',
4615
						count( $deactivated_titles ),
4616
						'jetpack'
4617
					),
4618
					$deactivated_titles
4619
				);
4620
4621
				$this->message .= "<br />\n";
4622
4623
				$this->message .= _n(
4624
					'The old version has been deactivated and can be removed from your site.',
4625
					'The old versions have been deactivated and can be removed from your site.',
4626
					count( $deactivated_titles ),
4627
					'jetpack'
4628
				);
4629
			}
4630
		}
4631
4632
		$this->privacy_checks = self::state( 'privacy_checks' );
4633
4634
		if ( $this->message || $this->error || $this->privacy_checks ) {
4635
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4636
		}
4637
4638
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4639
	}
4640
4641
	function admin_notices() {
4642
4643
		if ( $this->error ) {
4644
			?>
4645
<div id="message" class="jetpack-message jetpack-err">
4646
	<div class="squeezer">
4647
		<h2>
4648
			<?php
4649
			echo wp_kses(
4650
				$this->error,
4651
				array(
4652
					'a'      => array( 'href' => array() ),
4653
					'small'  => true,
4654
					'code'   => true,
4655
					'strong' => true,
4656
					'br'     => true,
4657
					'b'      => true,
4658
				)
4659
			);
4660
			?>
4661
			</h2>
4662
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4663
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4664
<?php	endif; ?>
4665
	</div>
4666
</div>
4667
			<?php
4668
		}
4669
4670
		if ( $this->message ) {
4671
			?>
4672
<div id="message" class="jetpack-message">
4673
	<div class="squeezer">
4674
		<h2>
4675
			<?php
4676
			echo wp_kses(
4677
				$this->message,
4678
				array(
4679
					'strong' => array(),
4680
					'a'      => array( 'href' => true ),
4681
					'br'     => true,
4682
				)
4683
			);
4684
			?>
4685
			</h2>
4686
	</div>
4687
</div>
4688
			<?php
4689
		}
4690
4691
		if ( $this->privacy_checks ) :
4692
			$module_names = $module_slugs = array();
4693
4694
			$privacy_checks = explode( ',', $this->privacy_checks );
4695
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4696
			foreach ( $privacy_checks as $module_slug ) {
4697
				$module = self::get_module( $module_slug );
4698
				if ( ! $module ) {
4699
					continue;
4700
				}
4701
4702
				$module_slugs[] = $module_slug;
4703
				$module_names[] = "<strong>{$module['name']}</strong>";
4704
			}
4705
4706
			$module_slugs = join( ',', $module_slugs );
4707
			?>
4708
<div id="message" class="jetpack-message jetpack-err">
4709
	<div class="squeezer">
4710
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4711
		<p>
4712
			<?php
4713
			echo wp_kses(
4714
				wptexturize(
4715
					wp_sprintf(
4716
						_nx(
4717
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4718
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4719
							count( $privacy_checks ),
4720
							'%l = list of Jetpack module/feature names',
4721
							'jetpack'
4722
						),
4723
						$module_names
4724
					)
4725
				),
4726
				array( 'strong' => true )
4727
			);
4728
4729
			echo "\n<br />\n";
4730
4731
			echo wp_kses(
4732
				sprintf(
4733
					_nx(
4734
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4735
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4736
						count( $privacy_checks ),
4737
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4738
						'jetpack'
4739
					),
4740
					wp_nonce_url(
4741
						self::admin_url(
4742
							array(
4743
								'page'   => 'jetpack',
4744
								'action' => 'deactivate',
4745
								'module' => urlencode( $module_slugs ),
4746
							)
4747
						),
4748
						"jetpack_deactivate-$module_slugs"
4749
					),
4750
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4751
				),
4752
				array(
4753
					'a' => array(
4754
						'href'  => true,
4755
						'title' => true,
4756
					),
4757
				)
4758
			);
4759
			?>
4760
		</p>
4761
	</div>
4762
</div>
4763
			<?php
4764
endif;
4765
	}
4766
4767
	/**
4768
	 * We can't always respond to a signed XML-RPC request with a
4769
	 * helpful error message. In some circumstances, doing so could
4770
	 * leak information.
4771
	 *
4772
	 * Instead, track that the error occurred via a Jetpack_Option,
4773
	 * and send that data back in the heartbeat.
4774
	 * All this does is increment a number, but it's enough to find
4775
	 * trends.
4776
	 *
4777
	 * @param WP_Error $xmlrpc_error The error produced during
4778
	 *                               signature validation.
4779
	 */
4780
	function track_xmlrpc_error( $xmlrpc_error ) {
4781
		$code = is_wp_error( $xmlrpc_error )
4782
			? $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...
4783
			: 'should-not-happen';
4784
4785
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4786
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4787
			// No need to update the option if we already have
4788
			// this code stored.
4789
			return;
4790
		}
4791
		$xmlrpc_errors[ $code ] = true;
4792
4793
		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...
4794
	}
4795
4796
	/**
4797
	 * Initialize the jetpack stats instance only when needed
4798
	 *
4799
	 * @return void
4800
	 */
4801
	private function initialize_stats() {
4802
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4803
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4804
		}
4805
	}
4806
4807
	/**
4808
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4809
	 */
4810
	function stat( $group, $detail ) {
4811
		$this->initialize_stats();
4812
		$this->a8c_mc_stats_instance->add( $group, $detail );
4813
4814
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4815
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4816
	}
4817
4818
	/**
4819
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4820
	 */
4821
	function do_stats( $method = '' ) {
4822
		$this->initialize_stats();
4823
		if ( 'server_side' === $method ) {
4824
			$this->a8c_mc_stats_instance->do_server_side_stats();
4825
		} else {
4826
			$this->a8c_mc_stats_instance->do_stats();
4827
		}
4828
4829
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4830
		$this->stats = array();
4831
	}
4832
4833
	/**
4834
	 * Runs stats code for a one-off, server-side.
4835
	 *
4836
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4837
	 *
4838
	 * @return bool If it worked.
4839
	 */
4840
	static function do_server_side_stat( $args ) {
4841
		$url                   = self::build_stats_url( $args );
4842
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4843
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4844
	}
4845
4846
	/**
4847
	 * Builds the stats url.
4848
	 *
4849
	 * @param $args array|string The arguments to append to the URL.
4850
	 *
4851
	 * @return string The URL to be pinged.
4852
	 */
4853
	static function build_stats_url( $args ) {
4854
4855
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4856
		return $a8c_mc_stats_instance->build_stats_url( $args );
4857
4858
	}
4859
4860
	/**
4861
	 * Builds a URL to the Jetpack connection auth page
4862
	 *
4863
	 * @since 3.9.5
4864
	 *
4865
	 * @param bool        $raw If true, URL will not be escaped.
4866
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4867
	 *                              If string, will be a custom redirect.
4868
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4869
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4870
	 *
4871
	 * @return string Connect URL
4872
	 */
4873
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4874
		$site_id    = Jetpack_Options::get_option( 'id' );
4875
		$blog_token = ( new Tokens() )->get_access_token();
4876
4877
		if ( $register || ! $blog_token || ! $site_id ) {
4878
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4879
4880
			if ( ! empty( $redirect ) ) {
4881
				$url = add_query_arg(
4882
					'redirect',
4883
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4884
					$url
4885
				);
4886
			}
4887
4888
			if ( is_network_admin() ) {
4889
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4890
			}
4891
4892
			$calypso_env = self::get_calypso_env();
4893
4894
			if ( ! empty( $calypso_env ) ) {
4895
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4896
			}
4897
		} else {
4898
4899
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4900
			// because otherwise this logic can get us in to a loop.
4901
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4902
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4903
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4904
4905
				$response = Client::wpcom_json_api_request_as_blog(
4906
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4907
					'1.1'
4908
				);
4909
4910
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4911
4912
					// Generating a register URL instead to refresh the existing token
4913
					return $this->build_connect_url( $raw, $redirect, $from, true );
4914
				}
4915
			}
4916
4917
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4873 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...
4918
		}
4919
4920
		if ( $from ) {
4921
			$url = add_query_arg( 'from', $from, $url );
4922
		}
4923
4924
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4925
		/**
4926
		 * Filter the URL used when connecting a user to a WordPress.com account.
4927
		 *
4928
		 * @since 8.1.0
4929
		 *
4930
		 * @param string $url Connection URL.
4931
		 * @param bool   $raw If true, URL will not be escaped.
4932
		 */
4933
		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...
4934
	}
4935
4936
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4937
4938
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4939
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4940
4941
		if ( $iframe ) {
4942
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4943
		}
4944
4945
		$c8n = self::connection();
4946
		$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...
4947
4948
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4949
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4950
4951
		if ( $iframe ) {
4952
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4953
		}
4954
4955
		/**
4956
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4957
		 *
4958
		 * @since 8.9.0
4959
		 *
4960
		 * @param string $url Connection URL.
4961
		 */
4962
		return apply_filters( 'jetpack_build_authorize_url', $url );
4963
	}
4964
4965
	/**
4966
	 * Filters the connection URL parameter array.
4967
	 *
4968
	 * @param array $args default URL parameters used by the package.
4969
	 * @return array the modified URL arguments array.
4970
	 */
4971
	public static function filter_connect_request_body( $args ) {
4972
		if (
4973
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4974
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4975
		) {
4976
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4977
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4978
				? $gp_locale->slug
4979
				: '';
4980
		}
4981
4982
		$tracking        = new Tracking();
4983
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4984
4985
		$args = array_merge(
4986
			$args,
4987
			array(
4988
				'_ui' => $tracks_identity['_ui'],
4989
				'_ut' => $tracks_identity['_ut'],
4990
			)
4991
		);
4992
4993
		$calypso_env = self::get_calypso_env();
4994
4995
		if ( ! empty( $calypso_env ) ) {
4996
			$args['calypso_env'] = $calypso_env;
4997
		}
4998
4999
		return $args;
5000
	}
5001
5002
	/**
5003
	 * Filters the URL that will process the connection data. It can be different from the URL
5004
	 * that we send the user to after everything is done.
5005
	 *
5006
	 * @param String $processing_url the default redirect URL used by the package.
5007
	 * @return String the modified URL.
5008
	 *
5009
	 * @deprecated since Jetpack 9.5.0
5010
	 */
5011
	public static function filter_connect_processing_url( $processing_url ) {
5012
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
5013
5014
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
5015
		return $processing_url;
5016
	}
5017
5018
	/**
5019
	 * Filters the redirection URL that is used for connect requests. The redirect
5020
	 * URL should return the user back to the Jetpack console.
5021
	 *
5022
	 * @param String $redirect the default redirect URL used by the package.
5023
	 * @return String the modified URL.
5024
	 */
5025
	public static function filter_connect_redirect_url( $redirect ) {
5026
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
5027
		$redirect           = $redirect
5028
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
5029
			: $jetpack_admin_page;
5030
5031
		if ( isset( $_REQUEST['is_multisite'] ) ) {
5032
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
5033
		}
5034
5035
		return $redirect;
5036
	}
5037
5038
	/**
5039
	 * This action fires at the beginning of the Manager::authorize method.
5040
	 */
5041
	public static function authorize_starting() {
5042
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
5043
		// Checking if site has been active/connected previously before recording unique connection.
5044
		if ( ! $jetpack_unique_connection ) {
5045
			// jetpack_unique_connection option has never been set.
5046
			$jetpack_unique_connection = array(
5047
				'connected'    => 0,
5048
				'disconnected' => 0,
5049
				'version'      => '3.6.1',
5050
			);
5051
5052
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
5053
5054
			// Track unique connection.
5055
			$jetpack = self::init();
5056
5057
			$jetpack->stat( 'connections', 'unique-connection' );
5058
			$jetpack->do_stats( 'server_side' );
5059
		}
5060
5061
		// Increment number of times connected.
5062
		$jetpack_unique_connection['connected'] += 1;
5063
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5064
	}
5065
5066
	/**
5067
	 * This action fires when the site is registered (connected at a site level).
5068
	 */
5069
	public function handle_unique_registrations_stats() {
5070
		$jetpack_unique_registrations = Jetpack_Options::get_option( 'unique_registrations' );
5071
		// Checking if site has been registered previously before recording unique connection.
5072
		if ( ! $jetpack_unique_registrations ) {
5073
5074
			$jetpack_unique_registrations = 0;
5075
5076
			$this->stat( 'connections', 'unique-registrations' );
5077
			$this->do_stats( 'server_side' );
5078
		}
5079
5080
		// Increment number of times connected.
5081
		$jetpack_unique_registrations ++;
5082
		Jetpack_Options::update_option( 'unique_registrations', $jetpack_unique_registrations );
5083
	}
5084
5085
	/**
5086
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5087
	 * linked.
5088
	 */
5089
	public static function authorize_ending_linked() {
5090
		// Don't activate anything since we are just connecting a user.
5091
		self::state( 'message', 'linked' );
5092
	}
5093
5094
	/**
5095
	 * This action fires at the end of the Manager::authorize method when the master user is
5096
	 * authorized.
5097
	 *
5098
	 * @param array $data The request data.
5099
	 */
5100
	public static function authorize_ending_authorized( $data ) {
5101
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5102
		self::invalidate_onboarding_token();
5103
5104
		// If redirect_uri is SSO, ensure SSO module is enabled.
5105
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5106
5107
		/** This filter is documented in class.jetpack-cli.php */
5108
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5109
5110
		$activate_sso = (
5111
			isset( $redirect_options['action'] ) &&
5112
			'jetpack-sso' === $redirect_options['action'] &&
5113
			$jetpack_start_enable_sso
5114
		);
5115
5116
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5117
5118
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5119
	}
5120
5121
	/**
5122
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5123
	 */
5124
	public static function activate_default_modules_on_site_register() {
5125
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5126
		if ( $active_modules ) {
5127
			self::delete_active_modules();
5128
5129
			// 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.
5130
			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...
5131
		} else {
5132
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5133
			self::activate_default_modules( false, false, array(), false, null, null, false );
5134
		}
5135
5136
		// Since this is a fresh connection, be sure to clear out IDC options.
5137
		Identity_Crisis::clear_all_idc_options();
5138
	}
5139
5140
	/**
5141
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5142
	 * reconnect process is completed.
5143
	 * Note that this currently only happens when we don't need the user to re-authorize
5144
	 * their WP.com account, eg in cases where we are restoring a connection with
5145
	 * unhealthy blog token.
5146
	 */
5147
	public static function reconnection_completed() {
5148
		self::state( 'message', 'reconnection_completed' );
5149
	}
5150
5151
	/**
5152
	 * Get our assumed site creation date.
5153
	 * Calculated based on the earlier date of either:
5154
	 * - Earliest admin user registration date.
5155
	 * - Earliest date of post of any post type.
5156
	 *
5157
	 * @since 7.2.0
5158
	 * @deprecated since 7.8.0
5159
	 *
5160
	 * @return string Assumed site creation date and time.
5161
	 */
5162
	public static function get_assumed_site_creation_date() {
5163
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5164
		return self::connection()->get_assumed_site_creation_date();
5165
	}
5166
5167 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5168
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5169
5170
		if ( $activation_source_name ) {
5171
			$args['_as'] = urlencode( $activation_source_name );
5172
		}
5173
5174
		if ( $activation_source_keyword ) {
5175
			$args['_ak'] = urlencode( $activation_source_keyword );
5176
		}
5177
	}
5178
5179
	function build_reconnect_url( $raw = false ) {
5180
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5181
		return $raw ? $url : esc_url( $url );
5182
	}
5183
5184
	public static function admin_url( $args = null ) {
5185
		$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...
5186
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5187
		return $url;
5188
	}
5189
5190
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5191
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5192
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5193
	}
5194
5195
	function dismiss_jetpack_notice() {
5196
5197
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5198
			return;
5199
		}
5200
5201
		switch ( $_GET['jetpack-notice'] ) {
5202
			case 'dismiss':
5203
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5204
5205
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5206
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5207
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5208
				}
5209
				break;
5210
		}
5211
	}
5212
5213
	public static function sort_modules( $a, $b ) {
5214
		if ( $a['sort'] == $b['sort'] ) {
5215
			return 0;
5216
		}
5217
5218
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5219
	}
5220
5221
	function ajax_recheck_ssl() {
5222
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5223
		$result = self::permit_ssl( true );
5224
		wp_send_json(
5225
			array(
5226
				'enabled' => $result,
5227
				'message' => get_transient( 'jetpack_https_test_message' ),
5228
			)
5229
		);
5230
	}
5231
5232
	/* Client API */
5233
5234
	/**
5235
	 * Returns the requested Jetpack API URL
5236
	 *
5237
	 * @deprecated since 7.7
5238
	 * @return string
5239
	 */
5240
	public static function api_url( $relative_url ) {
5241
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5242
		$connection = self::connection();
5243
		return $connection->api_url( $relative_url );
5244
	}
5245
5246
	/**
5247
	 * @deprecated 8.0
5248
	 *
5249
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5250
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5251
	 */
5252
	public static function fix_url_for_bad_hosts( $url ) {
5253
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5254
		return $url;
5255
	}
5256
5257
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5258
		// Default to a blog token.
5259
		$token_type = 'blog';
5260
5261
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5262
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5263
			if ( ! empty( $_GET['onboarding'] ) ) {
5264
				$jpo = $_GET;
5265
			} else {
5266
				$jpo = json_decode( $request_data, true );
5267
			}
5268
5269
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5270
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5271
5272
			if (
5273
				isset( $jpo_user )
5274
				&& isset( $jpo_token )
5275
				&& is_email( $jpo_user )
5276
				&& ctype_alnum( $jpo_token )
5277
				&& isset( $_GET['rest_route'] )
5278
				&& self::validate_onboarding_token_action(
5279
					$jpo_token,
5280
					$_GET['rest_route']
5281
				)
5282
			) {
5283
				$jp_user = get_user_by( 'email', $jpo_user );
5284
				if ( is_a( $jp_user, 'WP_User' ) ) {
5285
					wp_set_current_user( $jp_user->ID );
5286
					$user_can = is_multisite()
5287
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5288
						: current_user_can( 'manage_options' );
5289
					if ( $user_can ) {
5290
						$token_type              = 'user';
5291
						$token->external_user_id = $jp_user->ID;
5292
					}
5293
				}
5294
			}
5295
5296
			$token_data['type']    = $token_type;
5297
			$token_data['user_id'] = $token->external_user_id;
5298
		}
5299
5300
		return $token_data;
5301
	}
5302
5303
	/**
5304
	 * Create a random secret for validating onboarding payload
5305
	 *
5306
	 * @return string Secret token
5307
	 */
5308
	public static function create_onboarding_token() {
5309
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5310
			$token = wp_generate_password( 32, false );
5311
			Jetpack_Options::update_option( 'onboarding', $token );
5312
		}
5313
5314
		return $token;
5315
	}
5316
5317
	/**
5318
	 * Remove the onboarding token
5319
	 *
5320
	 * @return bool True on success, false on failure
5321
	 */
5322
	public static function invalidate_onboarding_token() {
5323
		return Jetpack_Options::delete_option( 'onboarding' );
5324
	}
5325
5326
	/**
5327
	 * Validate an onboarding token for a specific action
5328
	 *
5329
	 * @return boolean True if token/action pair is accepted, false if not
5330
	 */
5331
	public static function validate_onboarding_token_action( $token, $action ) {
5332
		// Compare tokens, bail if tokens do not match
5333
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5334
			return false;
5335
		}
5336
5337
		// List of valid actions we can take
5338
		$valid_actions = array(
5339
			'/jetpack/v4/settings',
5340
		);
5341
5342
		// Only allow valid actions.
5343
		if ( ! in_array( $action, $valid_actions ) ) {
5344
			return false;
5345
		}
5346
5347
		return true;
5348
	}
5349
5350
	/**
5351
	 * Checks to see if the URL is using SSL to connect with Jetpack
5352
	 *
5353
	 * @since 2.3.3
5354
	 * @return boolean
5355
	 */
5356
	public static function permit_ssl( $force_recheck = false ) {
5357
		// Do some fancy tests to see if ssl is being supported
5358
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5359
			$message = '';
5360
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5361
				$ssl = 0;
5362
			} else {
5363
				$ssl = 1;
5364
5365
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5366
					$ssl     = 0;
5367
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5368
				} else {
5369
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5370
					if ( is_wp_error( $response ) ) {
5371
						$ssl     = 0;
5372
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5373
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5374
						$ssl     = 0;
5375
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5376
					}
5377
				}
5378
			}
5379
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5380
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5381
		}
5382
5383
		return (bool) $ssl;
5384
	}
5385
5386
	/*
5387
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5388
	 */
5389
	public function alert_auto_ssl_fail() {
5390
		if ( ! current_user_can( 'manage_options' ) ) {
5391
			return;
5392
		}
5393
5394
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5395
		?>
5396
5397
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5398
			<div class="jp-banner__content">
5399
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5400
				<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>
5401
				<p>
5402
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5403
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5404
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5405
				</p>
5406
				<p>
5407
					<?php
5408
					printf(
5409
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5410
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5411
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5412
					);
5413
					?>
5414
				</p>
5415
			</div>
5416
		</div>
5417
		<style>
5418
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5419
		</style>
5420
		<script type="text/javascript">
5421
			jQuery( document ).ready( function( $ ) {
5422
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5423
					var $this = $( this );
5424
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5425
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5426
					e.preventDefault();
5427
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5428
					$.post( ajaxurl, data )
5429
					  .done( function( response ) {
5430
						  if ( response.enabled ) {
5431
							  $( '#jetpack-ssl-warning' ).hide();
5432
						  } else {
5433
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5434
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5435
						  }
5436
					  }.bind( $this ) );
5437
				} );
5438
			} );
5439
		</script>
5440
5441
		<?php
5442
	}
5443
5444
	/**
5445
	 * Returns the Jetpack XML-RPC API
5446
	 *
5447
	 * @deprecated 8.0 Use Connection_Manager instead.
5448
	 * @return string
5449
	 */
5450
	public static function xmlrpc_api_url() {
5451
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5452
		return self::connection()->xmlrpc_api_url();
5453
	}
5454
5455
	/**
5456
	 * Returns the connection manager object.
5457
	 *
5458
	 * @return Automattic\Jetpack\Connection\Manager
5459
	 */
5460
	public static function connection() {
5461
		$jetpack = static::init();
5462
5463
		// If the connection manager hasn't been instantiated, do that now.
5464
		if ( ! $jetpack->connection_manager ) {
5465
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5466
		}
5467
5468
		return $jetpack->connection_manager;
5469
	}
5470
5471
	/**
5472
	 * Creates two secret tokens and the end of life timestamp for them.
5473
	 *
5474
	 * Note these tokens are unique per call, NOT static per site for connecting.
5475
	 *
5476
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5477
	 *
5478
	 * @since 2.6
5479
	 * @param String  $action  The action name.
5480
	 * @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...
5481
	 * @param Integer $exp     Expiration time in seconds.
5482
	 * @return array
5483
	 */
5484
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5485
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5486
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5487
	}
5488
5489
	public static function get_secrets( $action, $user_id ) {
5490
		$secrets = ( new Secrets() )->get( $action, $user_id );
5491
5492
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5493
			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...
5494
		}
5495
5496
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5497
			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...
5498
		}
5499
5500
		return $secrets;
5501
	}
5502
5503
	/**
5504
	 * Builds the timeout limit for queries talking with the wpcom servers.
5505
	 *
5506
	 * Based on local php max_execution_time in php.ini
5507
	 *
5508
	 * @since 2.6
5509
	 * @return int
5510
	 * @deprecated
5511
	 **/
5512
	public function get_remote_query_timeout_limit() {
5513
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5514
		return self::get_max_execution_time();
5515
	}
5516
5517
	/**
5518
	 * Builds the timeout limit for queries talking with the wpcom servers.
5519
	 *
5520
	 * Based on local php max_execution_time in php.ini
5521
	 *
5522
	 * @since 5.4
5523
	 * @return int
5524
	 **/
5525
	public static function get_max_execution_time() {
5526
		$timeout = (int) ini_get( 'max_execution_time' );
5527
5528
		// Ensure exec time set in php.ini
5529
		if ( ! $timeout ) {
5530
			$timeout = 30;
5531
		}
5532
		return $timeout;
5533
	}
5534
5535
	/**
5536
	 * Sets a minimum request timeout, and returns the current timeout
5537
	 *
5538
	 * @since 5.4
5539
	 **/
5540 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5541
		$timeout = self::get_max_execution_time();
5542
		if ( $timeout < $min_timeout ) {
5543
			$timeout = $min_timeout;
5544
			set_time_limit( $timeout );
5545
		}
5546
		return $timeout;
5547
	}
5548
5549
	/**
5550
	 * Takes the response from the Jetpack register new site endpoint and
5551
	 * verifies it worked properly.
5552
	 *
5553
	 * @since 2.6
5554
	 * @deprecated since 7.7.0
5555
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5556
	 **/
5557
	public function validate_remote_register_response() {
5558
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5559
	}
5560
5561
	/**
5562
	 * @deprecated since Jetpack 9.7.0
5563
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
5564
	 *
5565
	 * @return bool|WP_Error
5566
	 */
5567
	public static function register() {
5568
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
5569
		return static::connection()->try_registration( false );
5570
	}
5571
5572
	/**
5573
	 * Filters the registration request body to include tracking properties.
5574
	 *
5575
	 * @deprecated since Jetpack 9.7.0
5576
	 * @see Automattic\Jetpack\Connection\Utils::filter_register_request_body()
5577
	 *
5578
	 * @param array $properties
5579
	 * @return array amended properties.
5580
	 */
5581
	public static function filter_register_request_body( $properties ) {
5582
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Utils::filter_register_request_body' );
5583
		return Connection_Utils::filter_register_request_body( $properties );
5584
	}
5585
5586
	/**
5587
	 * Filters the token request body to include tracking properties.
5588
	 *
5589
	 * @param array $properties
5590
	 * @return array amended properties.
5591
	 */
5592 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5593
		$tracking        = new Tracking();
5594
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5595
5596
		return array_merge(
5597
			$properties,
5598
			array(
5599
				'_ui' => $tracks_identity['_ui'],
5600
				'_ut' => $tracks_identity['_ut'],
5601
			)
5602
		);
5603
	}
5604
5605
	/**
5606
	 * If the db version is showing something other that what we've got now, bump it to current.
5607
	 *
5608
	 * @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...
5609
	 */
5610
	public static function maybe_set_version_option() {
5611
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5612
		if ( JETPACK__VERSION != $version ) {
5613
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5614
5615
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5616
				/** This action is documented in class.jetpack.php */
5617
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5618
			}
5619
5620
			return true;
5621
		}
5622
		return false;
5623
	}
5624
5625
	/* Client Server API */
5626
5627
	/**
5628
	 * Loads the Jetpack XML-RPC client.
5629
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5630
	 *
5631
	 * @deprecated since 7.7.0
5632
	 */
5633
	public static function load_xml_rpc_client() {
5634
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5635
	}
5636
5637
	/**
5638
	 * Resets the saved authentication state in between testing requests.
5639
	 *
5640
	 * @deprecated since 8.9.0
5641
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5642
	 */
5643
	public function reset_saved_auth_state() {
5644
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5645
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5646
	}
5647
5648
	/**
5649
	 * Verifies the signature of the current request.
5650
	 *
5651
	 * @deprecated since 7.7.0
5652
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5653
	 *
5654
	 * @return false|array
5655
	 */
5656
	public function verify_xml_rpc_signature() {
5657
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5658
		return self::connection()->verify_xml_rpc_signature();
5659
	}
5660
5661
	/**
5662
	 * Verifies the signature of the current request.
5663
	 *
5664
	 * This function has side effects and should not be used. Instead,
5665
	 * use the memoized version `->verify_xml_rpc_signature()`.
5666
	 *
5667
	 * @deprecated since 7.7.0
5668
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5669
	 * @internal
5670
	 */
5671
	private function internal_verify_xml_rpc_signature() {
5672
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5673
	}
5674
5675
	/**
5676
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5677
	 *
5678
	 * @deprecated since 7.7.0
5679
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5680
	 *
5681
	 * @param \WP_User|mixed $user     User object if authenticated.
5682
	 * @param string         $username Username.
5683
	 * @param string         $password Password string.
5684
	 * @return \WP_User|mixed Authenticated user or error.
5685
	 */
5686 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5687
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5688
5689
		if ( ! $this->connection_manager ) {
5690
			$this->connection_manager = new Connection_Manager();
5691
		}
5692
5693
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5694
	}
5695
5696
	/**
5697
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5698
	 * Uses the existing XMLRPC request signing implementation.
5699
	 *
5700
	 * @deprecated since 8.9.0
5701
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5702
	 */
5703
	function wp_rest_authenticate( $user ) {
5704
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5705
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5706
	}
5707
5708
	/**
5709
	 * Report authentication status to the WP REST API.
5710
	 *
5711
	 * @deprecated since 8.9.0
5712
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5713
	 *
5714
	 * @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...
5715
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5716
	 */
5717
	public function wp_rest_authentication_errors( $value ) {
5718
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5719
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5720
	}
5721
5722
	/**
5723
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5724
	 * Capture it here so we can verify the signature later.
5725
	 *
5726
	 * @deprecated since 7.7.0
5727
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5728
	 *
5729
	 * @param array $methods XMLRPC methods.
5730
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5731
	 */
5732 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5733
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5734
5735
		if ( ! $this->connection_manager ) {
5736
			$this->connection_manager = new Connection_Manager();
5737
		}
5738
5739
		return $this->connection_manager->xmlrpc_methods( $methods );
5740
	}
5741
5742
	/**
5743
	 * Register additional public XMLRPC methods.
5744
	 *
5745
	 * @deprecated since 7.7.0
5746
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5747
	 *
5748
	 * @param array $methods Public XMLRPC methods.
5749
	 * @return array Public XMLRPC methods, with the getOptions one.
5750
	 */
5751 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5752
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5753
5754
		if ( ! $this->connection_manager ) {
5755
			$this->connection_manager = new Connection_Manager();
5756
		}
5757
5758
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5759
	}
5760
5761
	/**
5762
	 * Handles a getOptions XMLRPC method call.
5763
	 *
5764
	 * @deprecated since 7.7.0
5765
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5766
	 *
5767
	 * @param array $args method call arguments.
5768
	 * @return array an amended XMLRPC server options array.
5769
	 */
5770 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5771
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5772
5773
		if ( ! $this->connection_manager ) {
5774
			$this->connection_manager = new Connection_Manager();
5775
		}
5776
5777
		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...
5778
	}
5779
5780
	/**
5781
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5782
	 *
5783
	 * @deprecated since 7.7.0
5784
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5785
	 *
5786
	 * @param array $options Standard Core options.
5787
	 * @return array Amended options.
5788
	 */
5789 View Code Duplication
	public function xmlrpc_options( $options ) {
5790
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5791
5792
		if ( ! $this->connection_manager ) {
5793
			$this->connection_manager = new Connection_Manager();
5794
		}
5795
5796
		return $this->connection_manager->xmlrpc_options( $options );
5797
	}
5798
5799
	/**
5800
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5801
	 * SET: state( $key, $value );
5802
	 * GET: $value = state( $key );
5803
	 *
5804
	 * @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...
5805
	 * @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...
5806
	 * @param bool   $restate private
5807
	 */
5808
	public static function state( $key = null, $value = null, $restate = false ) {
5809
		static $state = array();
5810
		static $path, $domain;
5811
		if ( ! isset( $path ) ) {
5812
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5813
			$admin_url = self::admin_url();
5814
			$bits      = wp_parse_url( $admin_url );
5815
5816
			if ( is_array( $bits ) ) {
5817
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5818
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5819
			} else {
5820
				$path = $domain = null;
5821
			}
5822
		}
5823
5824
		// Extract state from cookies and delete cookies
5825
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5826
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5827
			unset( $_COOKIE['jetpackState'] );
5828
			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...
5829
				if ( strlen( $v ) ) {
5830
					$state[ $k ] = $v;
5831
				}
5832
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5833
			}
5834
		}
5835
5836
		if ( $restate ) {
5837
			foreach ( $state as $k => $v ) {
5838
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5839
			}
5840
			return;
5841
		}
5842
5843
		// Get a state variable.
5844
		if ( isset( $key ) && ! isset( $value ) ) {
5845
			if ( array_key_exists( $key, $state ) ) {
5846
				return $state[ $key ];
5847
			}
5848
			return null;
5849
		}
5850
5851
		// Set a state variable.
5852
		if ( isset( $key ) && isset( $value ) ) {
5853
			if ( is_array( $value ) && isset( $value[0] ) ) {
5854
				$value = $value[0];
5855
			}
5856
			$state[ $key ] = $value;
5857
			if ( ! headers_sent() ) {
5858
				if ( self::should_set_cookie( $key ) ) {
5859
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5860
				}
5861
			}
5862
		}
5863
	}
5864
5865
	public static function restate() {
5866
		self::state( null, null, true );
5867
	}
5868
5869
	/**
5870
	 * Determines whether the jetpackState[$key] value should be added to the
5871
	 * cookie.
5872
	 *
5873
	 * @param string $key The state key.
5874
	 *
5875
	 * @return boolean Whether the value should be added to the cookie.
5876
	 */
5877
	public static function should_set_cookie( $key ) {
5878
		global $current_screen;
5879
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5880
5881
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5882
			return false;
5883
		}
5884
5885
		return true;
5886
	}
5887
5888
	public static function check_privacy( $file ) {
5889
		static $is_site_publicly_accessible = null;
5890
5891
		if ( is_null( $is_site_publicly_accessible ) ) {
5892
			$is_site_publicly_accessible = false;
5893
5894
			$rpc = new Jetpack_IXR_Client();
5895
5896
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5897
			if ( $success ) {
5898
				$response = $rpc->getResponse();
5899
				if ( $response ) {
5900
					$is_site_publicly_accessible = true;
5901
				}
5902
			}
5903
5904
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5905
		}
5906
5907
		if ( $is_site_publicly_accessible ) {
5908
			return;
5909
		}
5910
5911
		$module_slug = self::get_module_slug( $file );
5912
5913
		$privacy_checks = self::state( 'privacy_checks' );
5914
		if ( ! $privacy_checks ) {
5915
			$privacy_checks = $module_slug;
5916
		} else {
5917
			$privacy_checks .= ",$module_slug";
5918
		}
5919
5920
		self::state( 'privacy_checks', $privacy_checks );
5921
	}
5922
5923
	/**
5924
	 * Helper method for multicall XMLRPC.
5925
	 *
5926
	 * @deprecated since 8.9.0
5927
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5928
	 *
5929
	 * @param ...$args Args for the async_call.
5930
	 */
5931
	public static function xmlrpc_async_call( ...$args ) {
5932
5933
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5934
5935
		global $blog_id;
5936
		static $clients = array();
5937
5938
		$client_blog_id = is_multisite() ? $blog_id : 0;
5939
5940
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5941
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5942
			if ( function_exists( 'ignore_user_abort' ) ) {
5943
				ignore_user_abort( true );
5944
			}
5945
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5946
		}
5947
5948
		if ( ! empty( $args[0] ) ) {
5949
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5950
		} elseif ( is_multisite() ) {
5951
			foreach ( $clients as $client_blog_id => $client ) {
5952
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5953
					continue;
5954
				}
5955
5956
				$switch_success = switch_to_blog( $client_blog_id, true );
5957
				if ( ! $switch_success ) {
5958
					continue;
5959
				}
5960
5961
				flush();
5962
				$client->query();
5963
5964
				restore_current_blog();
5965
			}
5966
		} else {
5967
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5968
				flush();
5969
				$clients[0]->query();
5970
			}
5971
		}
5972
	}
5973
5974
	/**
5975
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5976
	 *
5977
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5978
	 *
5979
	 * @param string $url WordPress.com static resource URL.
5980
	 */
5981
	public static function staticize_subdomain( $url ) {
5982
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5983
		return Assets::staticize_subdomain( $url );
5984
	}
5985
5986
	/* JSON API Authorization */
5987
5988
	/**
5989
	 * Handles the login action for Authorizing the JSON API
5990
	 */
5991
	function login_form_json_api_authorization() {
5992
		$this->verify_json_api_authorization_request();
5993
5994
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5995
5996
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5997
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5998
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5999
	}
6000
6001
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
6002
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
6003
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
6004
			return $url;
6005
		}
6006
6007
		$parsed_url = wp_parse_url( $url );
6008
		$url        = strtok( $url, '?' );
6009
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
6010
		if ( ! empty( $parsed_url['query'] ) ) {
6011
			$url .= "&{$parsed_url['query']}";
6012
		}
6013
6014
		return $url;
6015
	}
6016
6017
	// Make sure the POSTed request is handled by the same action
6018
	function preserve_action_in_login_form_for_json_api_authorization() {
6019
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6020
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6021
	}
6022
6023
	// If someone logs in to approve API access, store the Access Code in usermeta
6024
	function store_json_api_authorization_token( $user_login, $user ) {
6025
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6026
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6027
		$token = wp_generate_password( 32, false );
6028
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6029
	}
6030
6031
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
6032
	function allow_wpcom_public_api_domain( $domains ) {
6033
		$domains[] = 'public-api.wordpress.com';
6034
		return $domains;
6035
	}
6036
6037
	static function is_redirect_encoded( $redirect_url ) {
6038
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
6039
	}
6040
6041
	// Add all wordpress.com environments to the safe redirect allowed list.
6042
	function allow_wpcom_environments( $domains ) {
6043
		$domains[] = 'wordpress.com';
6044
		$domains[] = 'wpcalypso.wordpress.com';
6045
		$domains[] = 'horizon.wordpress.com';
6046
		$domains[] = 'calypso.localhost';
6047
		return $domains;
6048
	}
6049
6050
	// Add the Access Code details to the public-api.wordpress.com redirect
6051
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6052
		return add_query_arg(
6053
			urlencode_deep(
6054
				array(
6055
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6056
					'jetpack-user-id' => (int) $user->ID,
6057
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6058
				)
6059
			),
6060
			$redirect_to
6061
		);
6062
	}
6063
6064
	/**
6065
	 * Verifies the request by checking the signature
6066
	 *
6067
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6068
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6069
	 *
6070
	 * @param null|array $environment
6071
	 */
6072
	function verify_json_api_authorization_request( $environment = null ) {
6073
		$environment = is_null( $environment )
6074
			? $_REQUEST
6075
			: $environment;
6076
6077
		//phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
6078
		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...
6079
		$token = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
6080
		if ( ! $token || empty( $token->secret ) ) {
6081
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6082
		}
6083
6084
		$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' );
6085
6086
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6087
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6088
			/**
6089
			 * Jetpack authorisation request Error.
6090
			 *
6091
			 * @since 7.5.0
6092
			 */
6093
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6094
			$die_error = sprintf(
6095
				/* translators: %s is a URL */
6096
				__( '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' ),
6097
				Redirect::get_url( 'jetpack-support-double-encoding' )
6098
			);
6099
		}
6100
6101
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6102
6103
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6104
			$signature = $jetpack_signature->sign_request(
6105
				$environment['token'],
6106
				$environment['timestamp'],
6107
				$environment['nonce'],
6108
				'',
6109
				'GET',
6110
				$environment['jetpack_json_api_original_query'],
6111
				null,
6112
				true
6113
			);
6114
		} else {
6115
			$signature = $jetpack_signature->sign_current_request(
6116
				array(
6117
					'body'   => null,
6118
					'method' => 'GET',
6119
				)
6120
			);
6121
		}
6122
6123
		if ( ! $signature ) {
6124
			wp_die( $die_error );
6125
		} elseif ( is_wp_error( $signature ) ) {
6126
			wp_die( $die_error );
6127
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6128
			if ( is_ssl() ) {
6129
				// 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
6130
				$signature = $jetpack_signature->sign_current_request(
6131
					array(
6132
						'scheme' => 'http',
6133
						'body'   => null,
6134
						'method' => 'GET',
6135
					)
6136
				);
6137
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6138
					wp_die( $die_error );
6139
				}
6140
			} else {
6141
				wp_die( $die_error );
6142
			}
6143
		}
6144
6145
		$timestamp = (int) $environment['timestamp'];
6146
		$nonce     = stripslashes( (string) $environment['nonce'] );
6147
6148
		if ( ! $this->connection_manager ) {
6149
			$this->connection_manager = new Connection_Manager();
6150
		}
6151
6152
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
6153
			// De-nonce the nonce, at least for 5 minutes.
6154
			// 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)
6155
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6156
			if ( $old_nonce_time < time() - 300 ) {
6157
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6158
			}
6159
		}
6160
6161
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6162
		$data_filters = array(
6163
			'state'        => 'opaque',
6164
			'client_id'    => 'int',
6165
			'client_title' => 'string',
6166
			'client_image' => 'url',
6167
		);
6168
6169
		foreach ( $data_filters as $key => $sanitation ) {
6170
			if ( ! isset( $data->$key ) ) {
6171
				wp_die( $die_error );
6172
			}
6173
6174
			switch ( $sanitation ) {
6175
				case 'int':
6176
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6177
					break;
6178
				case 'opaque':
6179
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6180
					break;
6181
				case 'string':
6182
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6183
					break;
6184
				case 'url':
6185
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6186
					break;
6187
			}
6188
		}
6189
6190
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6191
			wp_die( $die_error );
6192
		}
6193
	}
6194
6195
	function login_message_json_api_authorization( $message ) {
6196
		return '<p class="message">' . sprintf(
6197
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6198
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6199
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6200
	}
6201
6202
	/**
6203
	 * Get $content_width, but with a <s>twist</s> filter.
6204
	 */
6205
	public static function get_content_width() {
6206
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6207
			? $GLOBALS['content_width']
6208
			: false;
6209
		/**
6210
		 * Filter the Content Width value.
6211
		 *
6212
		 * @since 2.2.3
6213
		 *
6214
		 * @param string $content_width Content Width value.
6215
		 */
6216
		return apply_filters( 'jetpack_content_width', $content_width );
6217
	}
6218
6219
	/**
6220
	 * Pings the WordPress.com Mirror Site for the specified options.
6221
	 *
6222
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6223
	 *
6224
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6225
	 */
6226
	public function get_cloud_site_options( $option_names ) {
6227
		$option_names = array_filter( (array) $option_names, 'is_string' );
6228
6229
		$xml = new Jetpack_IXR_Client();
6230
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6231
		if ( $xml->isError() ) {
6232
			return array(
6233
				'error_code' => $xml->getErrorCode(),
6234
				'error_msg'  => $xml->getErrorMessage(),
6235
			);
6236
		}
6237
		$cloud_site_options = $xml->getResponse();
6238
6239
		return $cloud_site_options;
6240
	}
6241
6242
	/**
6243
	 * Checks if the site is currently in an identity crisis.
6244
	 *
6245
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6246
	 */
6247
	public static function check_identity_crisis() {
6248
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() || ! Identity_Crisis::validate_sync_error_idc_option() ) {
6249
			return false;
6250
		}
6251
6252
		return Jetpack_Options::get_option( 'sync_error_idc' );
6253
	}
6254
6255
	/**
6256
	 * Checks whether the home and siteurl specifically are allowed.
6257
	 * Written so that we don't have re-check $key and $value params every time
6258
	 * we want to check if this site is allowed, for example in footer.php
6259
	 *
6260
	 * @since  3.8.0
6261
	 * @return bool True = already allowed False = not on the allowed list.
6262
	 */
6263
	public static function is_staging_site() {
6264
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6265
		return ( new Status() )->is_staging_site();
6266
	}
6267
6268
	/**
6269
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6270
	 *
6271
	 * @since 4.4.0
6272
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6273
	 *
6274
	 * @return bool
6275
	 */
6276
	public static function validate_sync_error_idc_option() {
6277
		_deprecated_function( 'Jetpack::validate_sync_error_idc_option', 'jetpack-9.8', '/Automattic/Jetpack/Identity_Crisis::validate_sync_error_idc_option' );
6278
		return Identity_Crisis::validate_sync_error_idc_option();
6279
	}
6280
6281
	/**
6282
	 * Normalizes a url by doing three things:
6283
	 *  - Strips protocol
6284
	 *  - Strips www
6285
	 *  - Adds a trailing slash
6286
	 *
6287
	 * @since 4.4.0
6288
	 * @param string $url
6289
	 * @return WP_Error|string
6290
	 */
6291
	public static function normalize_url_protocol_agnostic( $url ) {
6292
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6293
		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...
6294
			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...
6295
		}
6296
6297
		// Strip www and protocols
6298
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6299
		return $url;
6300
	}
6301
6302
	/**
6303
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6304
	 *
6305
	 * @since 4.4.0
6306
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6307
	 *
6308
	 * @param array $response
6309
	 * @return array Array of the local urls, wpcom urls, and error code
6310
	 */
6311
	public static function get_sync_error_idc_option( $response = array() ) {
6312
		_deprecated_function( 'Jetpack::get_sync_error_idc_option', 'jetpack-9.8', '/Automattic/Jetpack/Identity_Crisis::get_sync_error_idc_option' );
6313
		return Identity_Crisis::get_sync_error_idc_option( $response );
6314
	}
6315
6316
	/**
6317
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6318
	 * If set to true, the site will be put into staging mode.
6319
	 *
6320
	 * @since 4.3.2
6321
	 * @return bool
6322
	 */
6323
	public static function sync_idc_optin() {
6324
		_deprecated_function( 'Jetpack::sync_idc_optin', 'jetpack-9.8', '/Automattic/Jetpack/Identity_Crisis::sync_idc_optin' );
6325
		return Identity_Crisis::sync_idc_optin();
6326
	}
6327
6328
	/**
6329
	 * Maybe Use a .min.css stylesheet, maybe not.
6330
	 *
6331
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6332
	 */
6333
	public static function maybe_min_asset( $url, $path, $plugin ) {
6334
		// Short out on things trying to find actual paths.
6335
		if ( ! $path || empty( $plugin ) ) {
6336
			return $url;
6337
		}
6338
6339
		$path = ltrim( $path, '/' );
6340
6341
		// Strip out the abspath.
6342
		$base = dirname( plugin_basename( $plugin ) );
6343
6344
		// Short out on non-Jetpack assets.
6345
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6346
			return $url;
6347
		}
6348
6349
		// File name parsing.
6350
		$file              = "{$base}/{$path}";
6351
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6352
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6353
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6354
		$extension         = array_shift( $file_name_parts_r );
6355
6356
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6357
			// Already pointing at the minified version.
6358
			if ( 'min' === $file_name_parts_r[0] ) {
6359
				return $url;
6360
			}
6361
6362
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6363
			if ( file_exists( $min_full_path ) ) {
6364
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6365
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6366
				if ( 'css' === $extension ) {
6367
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6368
					self::$min_assets[ $key ] = $path;
6369
				}
6370
			}
6371
		}
6372
6373
		return $url;
6374
	}
6375
6376
	/**
6377
	 * If the asset is minified, let's flag .min as the suffix.
6378
	 *
6379
	 * Attached to `style_loader_src` filter.
6380
	 *
6381
	 * @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...
6382
	 * @param string $handle The registered handle of the script in question.
6383
	 * @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...
6384
	 */
6385
	public static function set_suffix_on_min( $src, $handle ) {
6386
		if ( false === strpos( $src, '.min.css' ) ) {
6387
			return $src;
6388
		}
6389
6390
		if ( ! empty( self::$min_assets ) ) {
6391
			foreach ( self::$min_assets as $file => $path ) {
6392
				if ( false !== strpos( $src, $file ) ) {
6393
					wp_style_add_data( $handle, 'suffix', '.min' );
6394
					return $src;
6395
				}
6396
			}
6397
		}
6398
6399
		return $src;
6400
	}
6401
6402
	/**
6403
	 * Maybe inlines a stylesheet.
6404
	 *
6405
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6406
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6407
	 *
6408
	 * Attached to `style_loader_tag` filter.
6409
	 *
6410
	 * @param string $tag The tag that would link to the external asset.
6411
	 * @param string $handle The registered handle of the script in question.
6412
	 *
6413
	 * @return string
6414
	 */
6415
	public static function maybe_inline_style( $tag, $handle ) {
6416
		global $wp_styles;
6417
		$item = $wp_styles->registered[ $handle ];
6418
6419
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6420
			return $tag;
6421
		}
6422
6423
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6424
			$href = $matches[1];
6425
			// Strip off query string
6426
			if ( $pos = strpos( $href, '?' ) ) {
6427
				$href = substr( $href, 0, $pos );
6428
			}
6429
			// Strip off fragment
6430
			if ( $pos = strpos( $href, '#' ) ) {
6431
				$href = substr( $href, 0, $pos );
6432
			}
6433
		} else {
6434
			return $tag;
6435
		}
6436
6437
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6438
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6439
			return $tag;
6440
		}
6441
6442
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6443
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6444
			// And this isn't the pass that actually deals with the RTL version...
6445
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6446
				// Short out, as the RTL version will deal with it in a moment.
6447
				return $tag;
6448
			}
6449
		}
6450
6451
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6452
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6453
		if ( $css ) {
6454
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6455
			if ( empty( $item->extra['after'] ) ) {
6456
				wp_add_inline_style( $handle, $css );
6457
			} else {
6458
				array_unshift( $item->extra['after'], $css );
6459
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6460
			}
6461
		}
6462
6463
		return $tag;
6464
	}
6465
6466
	/**
6467
	 * Loads a view file from the views
6468
	 *
6469
	 * Data passed in with the $data parameter will be available in the
6470
	 * template file as $data['value']
6471
	 *
6472
	 * @param string $template - Template file to load
6473
	 * @param array  $data - Any data to pass along to the template
6474
	 * @return boolean - If template file was found
6475
	 **/
6476
	public function load_view( $template, $data = array() ) {
6477
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6478
6479
		if ( file_exists( $views_dir . $template ) ) {
6480
			require_once $views_dir . $template;
6481
			return true;
6482
		}
6483
6484
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6485
		return false;
6486
	}
6487
6488
	/**
6489
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6490
	 */
6491
	public function deprecated_hooks() {
6492
		$filter_deprecated_list = array(
6493
			'jetpack_bail_on_shortcode'                    => array(
6494
				'replacement' => 'jetpack_shortcodes_to_include',
6495
				'version'     => 'jetpack-3.1.0',
6496
			),
6497
			'wpl_sharing_2014_1'                           => array(
6498
				'replacement' => null,
6499
				'version'     => 'jetpack-3.6.0',
6500
			),
6501
			'jetpack-tools-to-include'                     => array(
6502
				'replacement' => 'jetpack_tools_to_include',
6503
				'version'     => 'jetpack-3.9.0',
6504
			),
6505
			'jetpack_identity_crisis_options_to_check'     => array(
6506
				'replacement' => null,
6507
				'version'     => 'jetpack-4.0.0',
6508
			),
6509
			'update_option_jetpack_single_user_site'       => array(
6510
				'replacement' => null,
6511
				'version'     => 'jetpack-4.3.0',
6512
			),
6513
			'audio_player_default_colors'                  => array(
6514
				'replacement' => null,
6515
				'version'     => 'jetpack-4.3.0',
6516
			),
6517
			'add_option_jetpack_featured_images_enabled'   => array(
6518
				'replacement' => null,
6519
				'version'     => 'jetpack-4.3.0',
6520
			),
6521
			'add_option_jetpack_update_details'            => array(
6522
				'replacement' => null,
6523
				'version'     => 'jetpack-4.3.0',
6524
			),
6525
			'add_option_jetpack_updates'                   => array(
6526
				'replacement' => null,
6527
				'version'     => 'jetpack-4.3.0',
6528
			),
6529
			'add_option_jetpack_network_name'              => array(
6530
				'replacement' => null,
6531
				'version'     => 'jetpack-4.3.0',
6532
			),
6533
			'add_option_jetpack_network_allow_new_registrations' => array(
6534
				'replacement' => null,
6535
				'version'     => 'jetpack-4.3.0',
6536
			),
6537
			'add_option_jetpack_network_add_new_users'     => array(
6538
				'replacement' => null,
6539
				'version'     => 'jetpack-4.3.0',
6540
			),
6541
			'add_option_jetpack_network_site_upload_space' => array(
6542
				'replacement' => null,
6543
				'version'     => 'jetpack-4.3.0',
6544
			),
6545
			'add_option_jetpack_network_upload_file_types' => array(
6546
				'replacement' => null,
6547
				'version'     => 'jetpack-4.3.0',
6548
			),
6549
			'add_option_jetpack_network_enable_administration_menus' => array(
6550
				'replacement' => null,
6551
				'version'     => 'jetpack-4.3.0',
6552
			),
6553
			'add_option_jetpack_is_multi_site'             => array(
6554
				'replacement' => null,
6555
				'version'     => 'jetpack-4.3.0',
6556
			),
6557
			'add_option_jetpack_is_main_network'           => array(
6558
				'replacement' => null,
6559
				'version'     => 'jetpack-4.3.0',
6560
			),
6561
			'add_option_jetpack_main_network_site'         => array(
6562
				'replacement' => null,
6563
				'version'     => 'jetpack-4.3.0',
6564
			),
6565
			'jetpack_sync_all_registered_options'          => array(
6566
				'replacement' => null,
6567
				'version'     => 'jetpack-4.3.0',
6568
			),
6569
			'jetpack_has_identity_crisis'                  => array(
6570
				'replacement' => 'jetpack_sync_error_idc_validation',
6571
				'version'     => 'jetpack-4.4.0',
6572
			),
6573
			'jetpack_is_post_mailable'                     => array(
6574
				'replacement' => null,
6575
				'version'     => 'jetpack-4.4.0',
6576
			),
6577
			'jetpack_seo_site_host'                        => array(
6578
				'replacement' => null,
6579
				'version'     => 'jetpack-5.1.0',
6580
			),
6581
			'jetpack_installed_plugin'                     => array(
6582
				'replacement' => 'jetpack_plugin_installed',
6583
				'version'     => 'jetpack-6.0.0',
6584
			),
6585
			'jetpack_holiday_snow_option_name'             => array(
6586
				'replacement' => null,
6587
				'version'     => 'jetpack-6.0.0',
6588
			),
6589
			'jetpack_holiday_chance_of_snow'               => array(
6590
				'replacement' => null,
6591
				'version'     => 'jetpack-6.0.0',
6592
			),
6593
			'jetpack_holiday_snow_js_url'                  => array(
6594
				'replacement' => null,
6595
				'version'     => 'jetpack-6.0.0',
6596
			),
6597
			'jetpack_is_holiday_snow_season'               => array(
6598
				'replacement' => null,
6599
				'version'     => 'jetpack-6.0.0',
6600
			),
6601
			'jetpack_holiday_snow_option_updated'          => array(
6602
				'replacement' => null,
6603
				'version'     => 'jetpack-6.0.0',
6604
			),
6605
			'jetpack_holiday_snowing'                      => array(
6606
				'replacement' => null,
6607
				'version'     => 'jetpack-6.0.0',
6608
			),
6609
			'jetpack_sso_auth_cookie_expirtation'          => array(
6610
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6611
				'version'     => 'jetpack-6.1.0',
6612
			),
6613
			'jetpack_cache_plans'                          => array(
6614
				'replacement' => null,
6615
				'version'     => 'jetpack-6.1.0',
6616
			),
6617
6618
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6619
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6620
				'version'     => 'jetpack-6.5.0',
6621
			),
6622
			'jetpack_enable_site_verification'             => array(
6623
				'replacement' => null,
6624
				'version'     => 'jetpack-6.5.0',
6625
			),
6626
			'can_display_jetpack_manage_notice'            => array(
6627
				'replacement' => null,
6628
				'version'     => 'jetpack-7.3.0',
6629
			),
6630
			'atd_http_post_timeout'                        => array(
6631
				'replacement' => null,
6632
				'version'     => 'jetpack-7.3.0',
6633
			),
6634
			'atd_service_domain'                           => array(
6635
				'replacement' => null,
6636
				'version'     => 'jetpack-7.3.0',
6637
			),
6638
			'atd_load_scripts'                             => array(
6639
				'replacement' => null,
6640
				'version'     => 'jetpack-7.3.0',
6641
			),
6642
			'jetpack_widget_authors_exclude'               => array(
6643
				'replacement' => 'jetpack_widget_authors_params',
6644
				'version'     => 'jetpack-7.7.0',
6645
			),
6646
			// Removed in Jetpack 7.9.0
6647
			'jetpack_pwa_manifest'                         => array(
6648
				'replacement' => null,
6649
				'version'     => 'jetpack-7.9.0',
6650
			),
6651
			'jetpack_pwa_background_color'                 => array(
6652
				'replacement' => null,
6653
				'version'     => 'jetpack-7.9.0',
6654
			),
6655
			'jetpack_check_mobile'                         => array(
6656
				'replacement' => null,
6657
				'version'     => 'jetpack-8.3.0',
6658
			),
6659
			'jetpack_mobile_stylesheet'                    => array(
6660
				'replacement' => null,
6661
				'version'     => 'jetpack-8.3.0',
6662
			),
6663
			'jetpack_mobile_template'                      => array(
6664
				'replacement' => null,
6665
				'version'     => 'jetpack-8.3.0',
6666
			),
6667
			'jetpack_mobile_theme_menu'                    => array(
6668
				'replacement' => null,
6669
				'version'     => 'jetpack-8.3.0',
6670
			),
6671
			'minileven_show_featured_images'               => array(
6672
				'replacement' => null,
6673
				'version'     => 'jetpack-8.3.0',
6674
			),
6675
			'minileven_attachment_size'                    => array(
6676
				'replacement' => null,
6677
				'version'     => 'jetpack-8.3.0',
6678
			),
6679
			'instagram_cache_oembed_api_response_body'     => array(
6680
				'replacement' => null,
6681
				'version'     => 'jetpack-9.1.0',
6682
			),
6683
			'jetpack_can_make_outbound_https'              => array(
6684
				'replacement' => null,
6685
				'version'     => 'jetpack-9.1.0',
6686
			),
6687
		);
6688
6689
		foreach ( $filter_deprecated_list as $tag => $args ) {
6690
			if ( has_filter( $tag ) ) {
6691
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6692
			}
6693
		}
6694
6695
		$action_deprecated_list = array(
6696
			'jetpack_updated_theme'        => array(
6697
				'replacement' => 'jetpack_updated_themes',
6698
				'version'     => 'jetpack-6.2.0',
6699
			),
6700
			'atd_http_post_error'          => array(
6701
				'replacement' => null,
6702
				'version'     => 'jetpack-7.3.0',
6703
			),
6704
			'mobile_reject_mobile'         => array(
6705
				'replacement' => null,
6706
				'version'     => 'jetpack-8.3.0',
6707
			),
6708
			'mobile_force_mobile'          => array(
6709
				'replacement' => null,
6710
				'version'     => 'jetpack-8.3.0',
6711
			),
6712
			'mobile_app_promo_download'    => array(
6713
				'replacement' => null,
6714
				'version'     => 'jetpack-8.3.0',
6715
			),
6716
			'mobile_setup'                 => array(
6717
				'replacement' => null,
6718
				'version'     => 'jetpack-8.3.0',
6719
			),
6720
			'jetpack_mobile_footer_before' => array(
6721
				'replacement' => null,
6722
				'version'     => 'jetpack-8.3.0',
6723
			),
6724
			'wp_mobile_theme_footer'       => array(
6725
				'replacement' => null,
6726
				'version'     => 'jetpack-8.3.0',
6727
			),
6728
			'minileven_credits'            => array(
6729
				'replacement' => null,
6730
				'version'     => 'jetpack-8.3.0',
6731
			),
6732
			'jetpack_mobile_header_before' => array(
6733
				'replacement' => null,
6734
				'version'     => 'jetpack-8.3.0',
6735
			),
6736
			'jetpack_mobile_header_after'  => array(
6737
				'replacement' => null,
6738
				'version'     => 'jetpack-8.3.0',
6739
			),
6740
		);
6741
6742
		foreach ( $action_deprecated_list as $tag => $args ) {
6743
			if ( has_action( $tag ) ) {
6744
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6745
			}
6746
		}
6747
	}
6748
6749
	/**
6750
	 * Converts any url in a stylesheet, to the correct absolute url.
6751
	 *
6752
	 * Considerations:
6753
	 *  - Normal, relative URLs     `feh.png`
6754
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6755
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6756
	 *  - Absolute URLs             `http://domain.com/feh.png`
6757
	 *  - Domain root relative URLs `/feh.png`
6758
	 *
6759
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6760
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6761
	 *
6762
	 * @return mixed|string
6763
	 */
6764
	public static function absolutize_css_urls( $css, $css_file_url ) {
6765
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6766
		$css_dir = dirname( $css_file_url );
6767
		$p       = wp_parse_url( $css_dir );
6768
		$domain  = sprintf(
6769
			'%1$s//%2$s%3$s%4$s',
6770
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6771
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6772
			$p['host'],
6773
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6774
		);
6775
6776
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6777
			$find = $replace = array();
6778
			foreach ( $matches as $match ) {
6779
				$url = trim( $match['path'], "'\" \t" );
6780
6781
				// If this is a data url, we don't want to mess with it.
6782
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6783
					continue;
6784
				}
6785
6786
				// If this is an absolute or protocol-agnostic url,
6787
				// we don't want to mess with it.
6788
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6789
					continue;
6790
				}
6791
6792
				switch ( substr( $url, 0, 1 ) ) {
6793
					case '/':
6794
						$absolute = $domain . $url;
6795
						break;
6796
					default:
6797
						$absolute = $css_dir . '/' . $url;
6798
				}
6799
6800
				$find[]    = $match[0];
6801
				$replace[] = sprintf( 'url("%s")', $absolute );
6802
			}
6803
			$css = str_replace( $find, $replace, $css );
6804
		}
6805
6806
		return $css;
6807
	}
6808
6809
	/**
6810
	 * This methods removes all of the registered css files on the front end
6811
	 * from Jetpack in favor of using a single file. In effect "imploding"
6812
	 * all the files into one file.
6813
	 *
6814
	 * Pros:
6815
	 * - Uses only ONE css asset connection instead of 15
6816
	 * - Saves a minimum of 56k
6817
	 * - Reduces server load
6818
	 * - Reduces time to first painted byte
6819
	 *
6820
	 * Cons:
6821
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6822
	 *      should not cause any issues with themes.
6823
	 * - Plugins/themes dequeuing styles no longer do anything. See
6824
	 *      jetpack_implode_frontend_css filter for a workaround
6825
	 *
6826
	 * For some situations developers may wish to disable css imploding and
6827
	 * instead operate in legacy mode where each file loads seperately and
6828
	 * can be edited individually or dequeued. This can be accomplished with
6829
	 * the following line:
6830
	 *
6831
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6832
	 *
6833
	 * @since 3.2
6834
	 **/
6835
	public function implode_frontend_css( $travis_test = false ) {
6836
		$do_implode = true;
6837
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6838
			$do_implode = false;
6839
		}
6840
6841
		// Do not implode CSS when the page loads via the AMP plugin.
6842
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6843
			$do_implode = false;
6844
		}
6845
6846
		/**
6847
		 * Allow CSS to be concatenated into a single jetpack.css file.
6848
		 *
6849
		 * @since 3.2.0
6850
		 *
6851
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6852
		 */
6853
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6854
6855
		// Do not use the imploded file when default behavior was altered through the filter
6856
		if ( ! $do_implode ) {
6857
			return;
6858
		}
6859
6860
		// We do not want to use the imploded file in dev mode, or if not connected
6861
		if ( ( new Status() )->is_offline_mode() || ! self::is_connection_ready() ) {
6862
			if ( ! $travis_test ) {
6863
				return;
6864
			}
6865
		}
6866
6867
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6868
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6869
			return;
6870
		}
6871
6872
		/*
6873
		 * Now we assume Jetpack is connected and able to serve the single
6874
		 * file.
6875
		 *
6876
		 * In the future there will be a check here to serve the file locally
6877
		 * or potentially from the Jetpack CDN
6878
		 *
6879
		 * For now:
6880
		 * - Enqueue a single imploded css file
6881
		 * - Zero out the style_loader_tag for the bundled ones
6882
		 * - Be happy, drink scotch
6883
		 */
6884
6885
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6886
6887
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6888
6889
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6890
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6891
	}
6892
6893
	function concat_remove_style_loader_tag( $tag, $handle ) {
6894
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6895
			$tag = '';
6896
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6897
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6898
			}
6899
		}
6900
6901
		return $tag;
6902
	}
6903
6904
	/**
6905
	 * @deprecated
6906
	 * @see Automattic\Jetpack\Assets\add_aync_script
6907
	 */
6908
	public function script_add_async( $tag, $handle, $src ) {
6909
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6910
	}
6911
6912
	/*
6913
	 * Check the heartbeat data
6914
	 *
6915
	 * Organizes the heartbeat data by severity.  For example, if the site
6916
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6917
	 *
6918
	 * Data will be added to "caution" array, if it either:
6919
	 *  - Out of date Jetpack version
6920
	 *  - Out of date WP version
6921
	 *  - Out of date PHP version
6922
	 *
6923
	 * $return array $filtered_data
6924
	 */
6925
	public static function jetpack_check_heartbeat_data() {
6926
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6927
6928
		$good    = array();
6929
		$caution = array();
6930
		$bad     = array();
6931
6932
		foreach ( $raw_data as $stat => $value ) {
6933
6934
			// Check jetpack version
6935
			if ( 'version' == $stat ) {
6936
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6937
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6938
					continue;
6939
				}
6940
			}
6941
6942
			// Check WP version
6943
			if ( 'wp-version' == $stat ) {
6944
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6945
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6946
					continue;
6947
				}
6948
			}
6949
6950
			// Check PHP version
6951
			if ( 'php-version' == $stat ) {
6952
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6953
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6954
					continue;
6955
				}
6956
			}
6957
6958
			// Check ID crisis
6959
			if ( 'identitycrisis' == $stat ) {
6960
				if ( 'yes' == $value ) {
6961
					$bad[ $stat ] = $value;
6962
					continue;
6963
				}
6964
			}
6965
6966
			// The rest are good :)
6967
			$good[ $stat ] = $value;
6968
		}
6969
6970
		$filtered_data = array(
6971
			'good'    => $good,
6972
			'caution' => $caution,
6973
			'bad'     => $bad,
6974
		);
6975
6976
		return $filtered_data;
6977
	}
6978
6979
	/*
6980
	 * This method is used to organize all options that can be reset
6981
	 * without disconnecting Jetpack.
6982
	 *
6983
	 * It is used in class.jetpack-cli.php to reset options
6984
	 *
6985
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6986
	 *
6987
	 * @return array of options to delete.
6988
	 */
6989
	public static function get_jetpack_options_for_reset() {
6990
		return Jetpack_Options::get_options_for_reset();
6991
	}
6992
6993
	/*
6994
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6995
	 * so we can bring them directly to their site in calypso.
6996
	 *
6997
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
6998
	 *
6999
	 * @param string | url
7000
	 * @return string | url without the guff
7001
	 */
7002
	public static function build_raw_urls( $url ) {
7003
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
7004
7005
		return ( new Status() )->get_site_suffix( $url );
7006
	}
7007
7008
	/**
7009
	 * Stores and prints out domains to prefetch for page speed optimization.
7010
	 *
7011
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
7012
	 *
7013
	 * @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...
7014
	 */
7015
	public static function dns_prefetch( $urls = null ) {
7016
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
7017
		if ( $urls ) {
7018
			Assets::add_resource_hint( $urls );
7019
		}
7020
	}
7021
7022
	public function wp_dashboard_setup() {
7023
		if ( self::is_connection_ready() ) {
7024
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
7025
		}
7026
7027
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
7028
			$jetpack_logo = new Jetpack_Logo();
7029
			$widget_title = sprintf(
7030
				/* translators: Placeholder is a Jetpack logo. */
7031
				__( 'Stats by %s', 'jetpack' ),
7032
				$jetpack_logo->get_jp_emblem( true )
7033
			);
7034
7035
			// Wrap title in span so Logo can be properly styled.
7036
			$widget_title = sprintf(
7037
				'<span>%s</span>',
7038
				$widget_title
7039
			);
7040
7041
			wp_add_dashboard_widget(
7042
				'jetpack_summary_widget',
7043
				$widget_title,
7044
				array( __CLASS__, 'dashboard_widget' )
7045
			);
7046
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
7047
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
7048
7049
			// If we're inactive and not in offline mode, sort our box to the top.
7050
			if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
7051
				global $wp_meta_boxes;
7052
7053
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7054
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7055
7056
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7057
			}
7058
		}
7059
	}
7060
7061
	/**
7062
	 * @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...
7063
	 * @return mixed
7064
	 */
7065
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7066
		if ( ! is_array( $sorted ) ) {
7067
			return $sorted;
7068
		}
7069
7070
		foreach ( $sorted as $box_context => $ids ) {
7071
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7072
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7073
				continue;
7074
			}
7075
7076
			$ids_array = explode( ',', $ids );
7077
			$key       = array_search( 'dashboard_stats', $ids_array );
7078
7079
			if ( false !== $key ) {
7080
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7081
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7082
				$sorted[ $box_context ] = implode( ',', $ids_array );
7083
				// We've found it, stop searching, and just return.
7084
				break;
7085
			}
7086
		}
7087
7088
		return $sorted;
7089
	}
7090
7091
	public static function dashboard_widget() {
7092
		/**
7093
		 * Fires when the dashboard is loaded.
7094
		 *
7095
		 * @since 3.4.0
7096
		 */
7097
		do_action( 'jetpack_dashboard_widget' );
7098
	}
7099
7100
	public static function dashboard_widget_footer() {
7101
		?>
7102
		<footer>
7103
7104
		<div class="protect">
7105
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7106
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7107
				<p class="blocked-count">
7108
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7109
				</p>
7110
				<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>
7111
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7112
				<a href="
7113
				<?php
7114
				echo esc_url(
7115
					wp_nonce_url(
7116
						self::admin_url(
7117
							array(
7118
								'action' => 'activate',
7119
								'module' => 'protect',
7120
							)
7121
						),
7122
						'jetpack_activate-protect'
7123
					)
7124
				);
7125
				?>
7126
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7127
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7128
				</a>
7129
			<?php else : ?>
7130
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7131
			<?php endif; ?>
7132
		</div>
7133
7134
		<div class="akismet">
7135
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7136
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7137
				<p class="blocked-count">
7138
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7139
				</p>
7140
				<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>
7141
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7142
				<a href="
7143
				<?php
7144
				echo esc_url(
7145
					wp_nonce_url(
7146
						add_query_arg(
7147
							array(
7148
								'action' => 'activate',
7149
								'plugin' => 'akismet/akismet.php',
7150
							),
7151
							admin_url( 'plugins.php' )
7152
						),
7153
						'activate-plugin_akismet/akismet.php'
7154
					)
7155
				);
7156
				?>
7157
							" class="button button-jetpack">
7158
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7159
				</a>
7160
			<?php else : ?>
7161
				<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>
7162
			<?php endif; ?>
7163
		</div>
7164
7165
		</footer>
7166
		<?php
7167
	}
7168
7169
	/*
7170
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7171
	 */
7172
	function jetpack_icon_user_connected( $columns ) {
7173
		$columns['user_jetpack'] = '';
7174
		return $columns;
7175
	}
7176
7177
	/*
7178
	 * Show Jetpack icon if the user is linked.
7179
	 */
7180
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7181
		if ( 'user_jetpack' === $col && self::connection()->is_user_connected( $user_id ) ) {
7182
			$jetpack_logo = new Jetpack_Logo();
7183
			$emblem_html  = sprintf(
7184
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7185
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7186
				$jetpack_logo->get_jp_emblem()
7187
			);
7188
			return $emblem_html;
7189
		}
7190
7191
		return $val;
7192
	}
7193
7194
	/*
7195
	 * Style the Jetpack user column
7196
	 */
7197
	function jetpack_user_col_style() {
7198
		global $current_screen;
7199
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7200
			?>
7201
			<style>
7202
				.fixed .column-user_jetpack {
7203
					width: 21px;
7204
				}
7205
				.jp-emblem-user-admin svg {
7206
					width: 20px;
7207
					height: 20px;
7208
				}
7209
				.jp-emblem-user-admin path {
7210
					fill: #00BE28;
7211
				}
7212
			</style>
7213
			<?php
7214
		}
7215
	}
7216
7217
	/**
7218
	 * Checks if Akismet is active and working.
7219
	 *
7220
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7221
	 * that implied usage of methods present since more recent version.
7222
	 * See https://github.com/Automattic/jetpack/pull/9585
7223
	 *
7224
	 * @since  5.1.0
7225
	 *
7226
	 * @return bool True = Akismet available. False = Aksimet not available.
7227
	 */
7228
	public static function is_akismet_active() {
7229
		static $status = null;
7230
7231
		if ( ! is_null( $status ) ) {
7232
			return $status;
7233
		}
7234
7235
		// Check if a modern version of Akismet is active.
7236
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7237
			$status = false;
7238
			return $status;
7239
		}
7240
7241
		// Make sure there is a key known to Akismet at all before verifying key.
7242
		$akismet_key = Akismet::get_api_key();
7243
		if ( ! $akismet_key ) {
7244
			$status = false;
7245
			return $status;
7246
		}
7247
7248
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7249
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7250
7251
		// 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.
7252
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7253
		// We cache the result of the Akismet key verification for ten minutes.
7254
		if ( ! $akismet_key_state || $recheck ) {
7255
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7256
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7257
		}
7258
7259
		$status = 'valid' === $akismet_key_state;
7260
7261
		return $status;
7262
	}
7263
7264
	/**
7265
	 * @deprecated
7266
	 *
7267
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7268
	 */
7269
	public static function is_function_in_backtrace() {
7270
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7271
	}
7272
7273
	/**
7274
	 * Given a minified path, and a non-minified path, will return
7275
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7276
	 *
7277
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7278
	 * root Jetpack directory.
7279
	 *
7280
	 * @since 5.6.0
7281
	 *
7282
	 * @param string $min_path
7283
	 * @param string $non_min_path
7284
	 * @return string The URL to the file
7285
	 */
7286
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7287
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7288
	}
7289
7290
	/**
7291
	 * Checks for whether Jetpack Backup is enabled.
7292
	 * Will return true if the state of Backup is anything except "unavailable".
7293
	 *
7294
	 * @return bool|int|mixed
7295
	 */
7296
	public static function is_rewind_enabled() {
7297
		// Rewind is a paid feature, therefore requires a user-level connection.
7298
		if ( ! static::connection()->has_connected_owner() ) {
7299
			return false;
7300
		}
7301
7302
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7303
		if ( false === $rewind_enabled ) {
7304
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7305
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7306
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7307
				&& ! empty( $rewind_data['state'] )
7308
				&& 'active' === $rewind_data['state'] )
7309
				? 1
7310
				: 0;
7311
7312
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7313
		}
7314
		return $rewind_enabled;
7315
	}
7316
7317
	/**
7318
	 * Return Calypso environment value; used for developing Jetpack and pairing
7319
	 * it with different Calypso enrionments, such as localhost.
7320
	 *
7321
	 * @since 7.4.0
7322
	 *
7323
	 * @return string Calypso environment
7324
	 */
7325
	public static function get_calypso_env() {
7326
		if ( isset( $_GET['calypso_env'] ) ) {
7327
			return sanitize_key( $_GET['calypso_env'] );
7328
		}
7329
7330
		if ( getenv( 'CALYPSO_ENV' ) ) {
7331
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7332
		}
7333
7334
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7335
			return sanitize_key( CALYPSO_ENV );
7336
		}
7337
7338
		return '';
7339
	}
7340
7341
	/**
7342
	 * Returns the hostname with protocol for Calypso.
7343
	 * Used for developing Jetpack with Calypso.
7344
	 *
7345
	 * @since 8.4.0
7346
	 *
7347
	 * @return string Calypso host.
7348
	 */
7349
	public static function get_calypso_host() {
7350
		$calypso_env = self::get_calypso_env();
7351
		switch ( $calypso_env ) {
7352
			case 'development':
7353
				return 'http://calypso.localhost:3000/';
7354
			case 'wpcalypso':
7355
				return 'https://wpcalypso.wordpress.com/';
7356
			case 'horizon':
7357
				return 'https://horizon.wordpress.com/';
7358
			default:
7359
				return 'https://wordpress.com/';
7360
		}
7361
	}
7362
7363
	/**
7364
	 * Handles activating default modules as well general cleanup for the new connection.
7365
	 *
7366
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7367
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7368
	 * @param boolean $send_state_messages          Whether to send state messages.
7369
	 * @return void
7370
	 */
7371
	public static function handle_post_authorization_actions(
7372
		$activate_sso = false,
7373
		$redirect_on_activation_error = false,
7374
		$send_state_messages = true
7375
	) {
7376
		$other_modules = $activate_sso
7377
			? array( 'sso' )
7378
			: array();
7379
7380
		if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
7381
			$active_modules = Jetpack_Options::get_option( 'active_modules' );
7382
			self::delete_active_modules();
7383
7384
			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...
7385
		} else {
7386
			// Default modules that don't require a user were already activated on site_register.
7387
			// 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.
7388
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
7389
			Jetpack_Options::update_option( 'active_modules_initialized', true );
7390
		}
7391
7392
		// Since this is a fresh connection, be sure to clear out IDC options
7393
		Identity_Crisis::clear_all_idc_options();
7394
7395
		if ( $send_state_messages ) {
7396
			self::state( 'message', 'authorized' );
7397
		}
7398
	}
7399
7400
	/**
7401
	 * Returns a boolean for whether backups UI should be displayed or not.
7402
	 *
7403
	 * @return bool Should backups UI be displayed?
7404
	 */
7405
	public static function show_backups_ui() {
7406
		/**
7407
		 * Whether UI for backups should be displayed.
7408
		 *
7409
		 * @since 6.5.0
7410
		 *
7411
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7412
		 */
7413
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7414
	}
7415
7416
	/*
7417
	 * Deprecated manage functions
7418
	 */
7419
	function prepare_manage_jetpack_notice() {
7420
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7421
	}
7422
	function manage_activate_screen() {
7423
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7424
	}
7425
	function admin_jetpack_manage_notice() {
7426
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7427
	}
7428
	function opt_out_jetpack_manage_url() {
7429
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7430
	}
7431
	function opt_in_jetpack_manage_url() {
7432
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7433
	}
7434
	function opt_in_jetpack_manage_notice() {
7435
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7436
	}
7437
	function can_display_jetpack_manage_notice() {
7438
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7439
	}
7440
7441
	/**
7442
	 * Clean leftoveruser meta.
7443
	 *
7444
	 * Delete Jetpack-related user meta when it is no longer needed.
7445
	 *
7446
	 * @since 7.3.0
7447
	 *
7448
	 * @param int $user_id User ID being updated.
7449
	 */
7450
	public static function user_meta_cleanup( $user_id ) {
7451
		$meta_keys = array(
7452
			// AtD removed from Jetpack 7.3
7453
			'AtD_options',
7454
			'AtD_check_when',
7455
			'AtD_guess_lang',
7456
			'AtD_ignored_phrases',
7457
		);
7458
7459
		foreach ( $meta_keys as $meta_key ) {
7460
			if ( get_user_meta( $user_id, $meta_key ) ) {
7461
				delete_user_meta( $user_id, $meta_key );
7462
			}
7463
		}
7464
	}
7465
7466
	/**
7467
	 * Checks if a Jetpack site is both active and not in offline mode.
7468
	 *
7469
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7470
	 *
7471
	 * @deprecated 8.8.0
7472
	 *
7473
	 * @return bool True if Jetpack is active and not in offline mode.
7474
	 */
7475
	public static function is_active_and_not_development_mode() {
7476
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7477
		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...
7478
			return false;
7479
		}
7480
		return true;
7481
	}
7482
7483
	/**
7484
	 * Checks if a Jetpack site is both active and not in offline mode.
7485
	 *
7486
	 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
7487
	 *
7488
	 * @since 8.8.0
7489
	 *
7490
	 * @return bool True if Jetpack is active and not in offline mode.
7491
	 */
7492
	public static function is_active_and_not_offline_mode() {
7493
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
7494
			return false;
7495
		}
7496
		return true;
7497
	}
7498
7499
	/**
7500
	 * Returns the list of products that we have available for purchase.
7501
	 */
7502
	public static function get_products_for_purchase() {
7503
		$products = array();
7504
		if ( ! is_multisite() ) {
7505
			$products[] = array(
7506
				'key'               => 'backup',
7507
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7508
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7509
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7510
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7511
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7512
				'options'           => array(
7513
					array(
7514
						'type'        => 'daily',
7515
						'slug'        => 'jetpack-backup-daily',
7516
						'key'         => 'jetpack_backup_daily',
7517
						'name'        => __( 'Daily Backups', 'jetpack' ),
7518
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7519
					),
7520
					array(
7521
						'type'        => 'realtime',
7522
						'slug'        => 'jetpack-backup-realtime',
7523
						'key'         => 'jetpack_backup_realtime',
7524
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7525
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7526
					),
7527
				),
7528
				'default_option'    => 'realtime',
7529
				'show_promotion'    => true,
7530
				'discount_percent'  => 70,
7531
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7532
			);
7533
7534
			$products[] = array(
7535
				'key'               => 'scan',
7536
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7537
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7538
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7539
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7540
				'show_promotion'    => true,
7541
				'discount_percent'  => 30,
7542
				'options'           => array(
7543
					array(
7544
						'type' => 'scan',
7545
						'slug' => 'jetpack-scan',
7546
						'key'  => 'jetpack_scan',
7547
						'name' => __( 'Daily Scan', 'jetpack' ),
7548
					),
7549
				),
7550
				'default_option'    => 'scan',
7551
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7552
			);
7553
		}
7554
7555
		$products[] = array(
7556
			'key'               => 'search',
7557
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7558
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7559
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7560
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7561
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7562
			'options'           => array(
7563
				array(
7564
					'type' => 'search',
7565
					'slug' => 'jetpack-search',
7566
					'key'  => 'jetpack_search',
7567
					'name' => __( 'Search', 'jetpack' ),
7568
				),
7569
			),
7570
			'tears'             => array(),
7571
			'default_option'    => 'search',
7572
			'show_promotion'    => false,
7573
			'included_in_plans' => array( 'search-plan' ),
7574
		);
7575
7576
		$products[] = array(
7577
			'key'               => 'anti-spam',
7578
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7579
			'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' ),
7580
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7581
			'description'       => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
7582
			'options'           => array(
7583
				array(
7584
					'type' => 'anti-spam',
7585
					'slug' => 'jetpack-anti-spam',
7586
					'key'  => 'jetpack_anti_spam',
7587
					'name' => __( 'Anti-Spam', 'jetpack' ),
7588
				),
7589
			),
7590
			'default_option'    => 'anti-spam',
7591
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7592
		);
7593
7594
		return $products;
7595
	}
7596
}
7597