Completed
Push — add/testing-info ( be1095...03b7e9 )
by
unknown
09:20
created

Jetpack::validate_sync_error_idc_option()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

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