Completed
Push — renovate/major-eslint-and-plug... ( 32931a...ea602c )
by Jeremy
41:27 queued 30:19
created

Jetpack::build_reconnect_url()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

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