Completed
Push — add/identity-crisis-package ( 0e0dcc...78b820 )
by
unknown
378:08 queued 366:55
created

Jetpack::registration_check_domains()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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

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

Loading history...
558
	 */
559
	static function update_active_modules( $modules ) {
560
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
561
		$active_modules       = self::get_active_modules();
562
		$new_active_modules   = array_diff( $modules, $current_modules );
563
		$new_inactive_modules = array_diff( $active_modules, $modules );
564
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
565
		$reindexed_modules    = array_values( $new_current_modules );
566
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
567
568
		foreach ( $new_active_modules as $module ) {
569
			/**
570
			 * Fires when a specific module is activated.
571
			 *
572
			 * @since 1.9.0
573
			 *
574
			 * @param string $module Module slug.
575
			 * @param boolean $success whether the module was activated. @since 4.2
576
			 */
577
			do_action( 'jetpack_activate_module', $module, $success );
578
			/**
579
			 * Fires when a module is activated.
580
			 * The dynamic part of the filter, $module, is the module slug.
581
			 *
582
			 * @since 1.9.0
583
			 *
584
			 * @param string $module Module slug.
585
			 */
586
			do_action( "jetpack_activate_module_$module", $module );
587
		}
588
589
		foreach ( $new_inactive_modules as $module ) {
590
			/**
591
			 * Fired after a module has been deactivated.
592
			 *
593
			 * @since 4.2.0
594
			 *
595
			 * @param string $module Module slug.
596
			 * @param boolean $success whether the module was deactivated.
597
			 */
598
			do_action( 'jetpack_deactivate_module', $module, $success );
599
			/**
600
			 * Fires when a module is deactivated.
601
			 * The dynamic part of the filter, $module, is the module slug.
602
			 *
603
			 * @since 1.9.0
604
			 *
605
			 * @param string $module Module slug.
606
			 */
607
			do_action( "jetpack_deactivate_module_$module", $module );
608
		}
609
610
		return $success;
611
	}
612
613
	static function delete_active_modules() {
614
		self::update_active_modules( array() );
615
	}
616
617
	/**
618
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
619
	 * available.
620
	 */
621
	public function add_configure_hook() {
622
		global $wp_filter;
623
624
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
625
		if ( false !== $current_priority ) {
626
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
627
		}
628
629
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
630
		sort( $taken_priorities );
631
632
		$first_priority = array_shift( $taken_priorities );
633
634
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
635
			$new_priority = - PHP_INT_MAX;
636
		} else {
637
			$new_priority = $first_priority - 1;
638
		}
639
640
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
641
	}
642
643
	/**
644
	 * Constructor.  Initializes WordPress hooks
645
	 */
646
	private function __construct() {
647
		/*
648
		 * Check for and alert any deprecated hooks
649
		 */
650
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
651
652
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
653
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
654
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
655
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
656
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
657
658
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
659
660
		add_filter(
661
			'jetpack_signature_check_token',
662
			array( __CLASS__, 'verify_onboarding_token' ),
663
			10,
664
			3
665
		);
666
667
		/**
668
		 * Prepare Gutenberg Editor functionality
669
		 */
670
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
671
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
672
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
673
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
674
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
675
676
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
677
678
		// Unlink user before deleting the user from WP.com.
679
		add_action( 'deleted_user', array( $this, 'disconnect_user' ), 10, 1 );
680
		add_action( 'remove_user_from_blog', array( $this, 'disconnect_user' ), 10, 1 );
681
682
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
683
684
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
685
		add_action( 'login_init', array( $this, 'login_init' ) );
686
687
		// Set up the REST authentication hooks.
688
		Connection_Rest_Authentication::init();
689
690
		add_action( 'admin_init', array( $this, 'admin_init' ) );
691
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
692
693
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
694
695
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
696
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
697
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
698
699
		// returns HTTPS support status
700
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
701
702
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
703
704
		add_action( 'wp_ajax_jetpack_recommendations_banner', array( 'Jetpack_Recommendations_Banner', 'ajax_callback' ) );
705
706
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
707
708
		/**
709
		 * These actions run checks to load additional files.
710
		 * They check for external files or plugins, so they need to run as late as possible.
711
		 */
712
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
713
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
714
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
715
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
716
717
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
718
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
719
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
720
721
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
722
723
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
724
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
725
726
		// A filter to control all just in time messages
727
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
728
729
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
730
731
		require_once JETPACK__PLUGIN_DIR . 'class-jetpack-pre-connection-jitms.php';
732
		$jetpack_jitm_messages = ( new Jetpack_Pre_Connection_JITMs() );
733
		add_filter( 'jetpack_pre_connection_jitms', array( $jetpack_jitm_messages, 'add_pre_connection_jitms' ) );
734
735
		/*
736
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
737
		 * We should make sure to only do this for front end links.
738
		 */
739
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
740
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
741
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
742
743
			/*
744
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
745
			 * so they point moderation links on emails to Calypso.
746
			 */
747
			jetpack_require_lib( 'functions.wp-notify' );
748
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
749
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
750
		}
751
752
		add_action(
753
			'plugins_loaded',
754
			function () {
755
				if ( User_Agent_Info::is_mobile_app() ) {
756
					add_filter( 'get_edit_post_link', '__return_empty_string' );
757
				}
758
			}
759
		);
760
761
		// Update the site's Jetpack plan and products from API on heartbeats.
762
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
763
764
		/**
765
		 * This is the hack to concatenate all css files into one.
766
		 * For description and reasoning see the implode_frontend_css method.
767
		 *
768
		 * Super late priority so we catch all the registered styles.
769
		 */
770
		if ( ! is_admin() ) {
771
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
772
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
773
		}
774
775
		/**
776
		 * These are sync actions that we need to keep track of for jitms
777
		 */
778
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
779
780
		// Actually push the stats on shutdown.
781
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
782
			add_action( 'shutdown', array( $this, 'push_stats' ) );
783
		}
784
785
		// After a successful connection.
786
		add_action( 'jetpack_site_registered', array( $this, 'activate_default_modules_on_site_register' ) );
787
788
		// Actions for Manager::authorize().
789
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
790
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
791
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
792
793
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
794
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
795
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
796
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
797
798
		// Filters for the Manager::get_token() urls and request body.
799
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
800
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
801
802
		// Actions for successful reconnect.
803
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
804
805
		// Actions for licensing.
806
		Licensing::instance()->initialize();
807
808
		// Filters for Sync Callables.
809
		add_filter( 'jetpack_sync_callable_whitelist', array( $this, 'filter_sync_callable_whitelist' ), 10, 1 );
810
		add_filter( 'jetpack_sync_multisite_callable_whitelist', array( $this, 'filter_sync_multisite_callable_whitelist' ), 10, 1 );
811
812
		// Make resources use static domain when possible.
813
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
814
815
		// Validate the domain names in Jetpack development versions.
816
		add_action( 'jetpack_pre_register', array( get_called_class(), 'registration_check_domains' ) );
817
	}
818
819
	/**
820
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
821
	 * Config object.
822
	 */
823
	public function configure() {
824
		$config = new Config();
825
826
		foreach (
827
			array(
828
				'sync',
829
				'jitm',
830
			)
831
			as $feature
832
		) {
833
			$config->ensure( $feature );
834
		}
835
836
		$config->ensure(
837
			'connection',
838
			array(
839
				'slug' => 'jetpack',
840
				'name' => 'Jetpack',
841
			)
842
		);
843
844
		if ( ! $this->connection_manager ) {
845
			$this->connection_manager = new Connection_Manager( 'jetpack' );
846
847
			/**
848
			 * Filter to activate Jetpack Connection UI.
849
			 * INTERNAL USE ONLY.
850
			 *
851
			 * @since 9.5.0
852
			 *
853
			 * @param bool false Whether to activate the Connection UI.
854
			 */
855
			if ( apply_filters( 'jetpack_connection_ui_active', false ) ) {
856
				Automattic\Jetpack\ConnectionUI\Admin::init();
857
			}
858
		}
859
860
		/*
861
		 * Load things that should only be in Network Admin.
862
		 *
863
		 * For now blow away everything else until a more full
864
		 * understanding of what is needed at the network level is
865
		 * available
866
		 */
867
		if ( is_multisite() ) {
868
			$network = Jetpack_Network::init();
869
			$network->set_connection( $this->connection_manager );
870
		}
871
872
		if ( self::is_connection_ready() ) {
873
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
874
875
			Jetpack_Heartbeat::init();
876
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
877
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
878
				Jetpack_Search_Performance_Logger::init();
879
			}
880
		}
881
882
		// Initialize remote file upload request handlers.
883
		$this->add_remote_request_handlers();
884
885
		/*
886
		 * Enable enhanced handling of previewing sites in Calypso
887
		 */
888
		if ( self::is_connection_ready() ) {
889
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
890
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
891
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
892
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
893
		}
894
895
		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...
896
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
897
		} else {
898
			/**
899
			 * Initialize tracking right after the user agrees to the terms of service.
900
			 */
901
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
902
		}
903
	}
904
905
	/**
906
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
907
	 * initialization code.
908
	 *
909
	 * @action plugins_loaded
910
	 */
911
	public function late_initialization() {
912
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
913
914
		Partner::init();
915
916
		/**
917
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
918
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
919
		 *
920
		 * @since 8.1.0
921
		 *
922
		 * @param Jetpack $jetpack the main plugin class object.
923
		 */
924
		do_action( 'jetpack_loaded', $this );
925
926
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
927
	}
928
929
	/**
930
	 * Sets up the XMLRPC request handlers.
931
	 *
932
	 * @deprecated since 7.7.0
933
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
934
	 *
935
	 * @param array                 $request_params Incoming request parameters.
936
	 * @param Boolean               $is_active      Whether the connection is currently active.
937
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
938
	 * @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...
939
	 */
940 View Code Duplication
	public function setup_xmlrpc_handlers(
941
		$request_params,
942
		$is_active,
943
		$is_signed,
944
		Jetpack_XMLRPC_Server $xmlrpc_server = null
945
	) {
946
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
947
948
		if ( ! $this->connection_manager ) {
949
			$this->connection_manager = new Connection_Manager();
950
		}
951
952
		return $this->connection_manager->setup_xmlrpc_handlers(
953
			$request_params,
954
			$is_active,
955
			$is_signed,
956
			$xmlrpc_server
957
		);
958
	}
959
960
	/**
961
	 * Initialize REST API registration connector.
962
	 *
963
	 * @deprecated since 7.7.0
964
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
965
	 */
966 View Code Duplication
	public function initialize_rest_api_registration_connector() {
967
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
968
969
		if ( ! $this->connection_manager ) {
970
			$this->connection_manager = new Connection_Manager();
971
		}
972
973
		$this->connection_manager->initialize_rest_api_registration_connector();
974
	}
975
976
	/**
977
	 * This is ported over from the manage module, which has been deprecated and baked in here.
978
	 *
979
	 * @param $domains
980
	 */
981
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
982
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
983
	}
984
985
	/**
986
	 * Return $domains, with 'wordpress.com' appended.
987
	 * This is ported over from the manage module, which has been deprecated and baked in here.
988
	 *
989
	 * @param $domains
990
	 * @return array
991
	 */
992
	function allow_wpcom_domain( $domains ) {
993
		if ( empty( $domains ) ) {
994
			$domains = array();
995
		}
996
		$domains[] = 'wordpress.com';
997
		return array_unique( $domains );
998
	}
999
1000
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
1001
		$post = get_post( $post_id );
1002
1003
		if ( empty( $post ) ) {
1004
			return $default_url;
1005
		}
1006
1007
		$post_type = $post->post_type;
1008
1009
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1010
		// https://en.support.wordpress.com/custom-post-types/
1011
		$allowed_post_types = array(
1012
			'post',
1013
			'page',
1014
			'jetpack-portfolio',
1015
			'jetpack-testimonial',
1016
		);
1017
1018
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1019
			return $default_url;
1020
		}
1021
1022
		return Redirect::get_url(
1023
			'calypso-edit-' . $post_type,
1024
			array(
1025
				'path' => $post_id,
1026
			)
1027
		);
1028
	}
1029
1030
	function point_edit_comment_links_to_calypso( $url ) {
1031
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1032
		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...
1033
1034
		return Redirect::get_url(
1035
			'calypso-edit-comment',
1036
			array(
1037
				'path' => $query_args['amp;c'],
1038
			)
1039
		);
1040
1041
	}
1042
1043
	/**
1044
	 * Extend Sync callables with Jetpack Plugin functions.
1045
	 *
1046
	 * @param array $callables list of callables.
1047
	 *
1048
	 * @return array list of callables.
1049
	 */
1050
	public function filter_sync_callable_whitelist( $callables ) {
1051
1052
		// Jetpack Functions.
1053
		$jetpack_callables = array(
1054
			'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
1055
			'updates'                  => array( 'Jetpack', 'get_updates' ),
1056
			'active_modules'           => array( 'Jetpack', 'get_active_modules' ),
1057
			'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1058
		);
1059
		$callables         = array_merge( $callables, $jetpack_callables );
1060
1061
		// Jetpack_SSO_Helpers.
1062
		if ( include_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' ) {
1063
			$sso_helpers = array(
1064
				'sso_is_two_step_required'      => array( 'Jetpack_SSO_Helpers', 'is_two_step_required' ),
1065
				'sso_should_hide_login_form'    => array( 'Jetpack_SSO_Helpers', 'should_hide_login_form' ),
1066
				'sso_match_by_email'            => array( 'Jetpack_SSO_Helpers', 'match_by_email' ),
1067
				'sso_new_user_override'         => array( 'Jetpack_SSO_Helpers', 'new_user_override' ),
1068
				'sso_bypass_default_login_form' => array( 'Jetpack_SSO_Helpers', 'bypass_login_forward_wpcom' ),
1069
			);
1070
			$callables   = array_merge( $callables, $sso_helpers );
1071
		}
1072
1073
		return $callables;
1074
	}
1075
1076
	/**
1077
	 * Extend Sync multisite callables with Jetpack Plugin functions.
1078
	 *
1079
	 * @param array $callables list of callables.
1080
	 *
1081
	 * @return array list of callables.
1082
	 */
1083
	public function filter_sync_multisite_callable_whitelist( $callables ) {
1084
1085
		// Jetpack Funtions.
1086
		$jetpack_multisite_callables = array(
1087
			'network_name'                        => array( 'Jetpack', 'network_name' ),
1088
			'network_allow_new_registrations'     => array( 'Jetpack', 'network_allow_new_registrations' ),
1089
			'network_add_new_users'               => array( 'Jetpack', 'network_add_new_users' ),
1090
			'network_site_upload_space'           => array( 'Jetpack', 'network_site_upload_space' ),
1091
			'network_upload_file_types'           => array( 'Jetpack', 'network_upload_file_types' ),
1092
			'network_enable_administration_menus' => array( 'Jetpack', 'network_enable_administration_menus' ),
1093
		);
1094
		$callables                   = array_merge( $callables, $jetpack_multisite_callables );
1095
1096
		return $callables;
1097
	}
1098
1099
	function jetpack_track_last_sync_callback( $params ) {
1100
		/**
1101
		 * Filter to turn off jitm caching
1102
		 *
1103
		 * @since 5.4.0
1104
		 *
1105
		 * @param bool false Whether to cache just in time messages
1106
		 */
1107
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1108
			return $params;
1109
		}
1110
1111
		if ( is_array( $params ) && isset( $params[0] ) ) {
1112
			$option = $params[0];
1113
			if ( 'active_plugins' === $option ) {
1114
				// use the cache if we can, but not terribly important if it gets evicted
1115
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1116
			}
1117
		}
1118
1119
		return $params;
1120
	}
1121
1122
	function jetpack_connection_banner_callback() {
1123
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1124
1125
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1126
		if (
1127
			isset( $_REQUEST['dismissBanner'] ) &&
1128
			! Jetpack_Connection_Banner::force_display()
1129
		) {
1130
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1131
			wp_send_json_success();
1132
		}
1133
1134
		wp_die();
1135
	}
1136
1137
	/**
1138
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1139
	 * Only used in our alternate XML-RPC endpoint, where we want to
1140
	 * ensure that Core and other plugins' methods are not exposed.
1141
	 *
1142
	 * @deprecated since 7.7.0
1143
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1144
	 *
1145
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1146
	 * @return array Filtered $methods
1147
	 */
1148 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1149
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1150
1151
		if ( ! $this->connection_manager ) {
1152
			$this->connection_manager = new Connection_Manager();
1153
		}
1154
1155
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1156
	}
1157
1158
	/**
1159
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1160
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1161
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1162
	 * which is accessible via a different URI. Most of the below is copied directly
1163
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1164
	 *
1165
	 * @deprecated since 7.7.0
1166
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1167
	 */
1168 View Code Duplication
	public function alternate_xmlrpc() {
1169
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1170
1171
		if ( ! $this->connection_manager ) {
1172
			$this->connection_manager = new Connection_Manager();
1173
		}
1174
1175
		$this->connection_manager->alternate_xmlrpc();
1176
	}
1177
1178
	/**
1179
	 * The callback for the JITM ajax requests.
1180
	 *
1181
	 * @deprecated since 7.9.0
1182
	 */
1183
	function jetpack_jitm_ajax_callback() {
1184
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1185
	}
1186
1187
	/**
1188
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1189
	 */
1190
	function push_stats() {
1191
		if ( ! empty( $this->stats ) ) {
1192
			$this->do_stats( 'server_side' );
1193
		}
1194
	}
1195
1196
	/**
1197
	 * Sets the Jetpack custom capabilities.
1198
	 *
1199
	 * @param string[] $caps    Array of the user's capabilities.
1200
	 * @param string   $cap     Capability name.
1201
	 * @param int      $user_id The user ID.
1202
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1203
	 */
1204
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1205
		switch ( $cap ) {
1206
			case 'jetpack_manage_modules':
1207
			case 'jetpack_activate_modules':
1208
			case 'jetpack_deactivate_modules':
1209
				$caps = array( 'manage_options' );
1210
				break;
1211
			case 'jetpack_configure_modules':
1212
				$caps = array( 'manage_options' );
1213
				break;
1214
			case 'jetpack_manage_autoupdates':
1215
				$caps = array(
1216
					'manage_options',
1217
					'update_plugins',
1218
				);
1219
				break;
1220
			case 'jetpack_network_admin_page':
1221
			case 'jetpack_network_settings_page':
1222
				$caps = array( 'manage_network_plugins' );
1223
				break;
1224
			case 'jetpack_network_sites_page':
1225
				$caps = array( 'manage_sites' );
1226
				break;
1227 View Code Duplication
			case 'jetpack_admin_page':
1228
				$is_offline_mode = ( new Status() )->is_offline_mode();
1229
				if ( $is_offline_mode ) {
1230
					$caps = array( 'manage_options' );
1231
					break;
1232
				} else {
1233
					$caps = array( 'read' );
1234
				}
1235
				break;
1236
		}
1237
		return $caps;
1238
	}
1239
1240
	/**
1241
	 * Require a Jetpack authentication.
1242
	 *
1243
	 * @deprecated since 7.7.0
1244
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1245
	 */
1246 View Code Duplication
	public function require_jetpack_authentication() {
1247
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1248
1249
		if ( ! $this->connection_manager ) {
1250
			$this->connection_manager = new Connection_Manager();
1251
		}
1252
1253
		$this->connection_manager->require_jetpack_authentication();
1254
	}
1255
1256
	/**
1257
	 * Register assets for use in various modules and the Jetpack admin page.
1258
	 *
1259
	 * @uses wp_script_is, wp_register_script, plugins_url
1260
	 * @action wp_loaded
1261
	 * @return null
1262
	 */
1263
	public function register_assets() {
1264 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1265
			wp_register_script(
1266
				'jetpack-gallery-settings',
1267
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1268
				array( 'media-views' ),
1269
				'20121225'
1270
			);
1271
		}
1272
1273
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1274
			wp_register_script(
1275
				'jetpack-twitter-timeline',
1276
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1277
				array( 'jquery' ),
1278
				'4.0.0',
1279
				true
1280
			);
1281
		}
1282
1283
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1284
			wp_register_script(
1285
				'jetpack-facebook-embed',
1286
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1287
				array(),
1288
				null,
1289
				true
1290
			);
1291
1292
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1293
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1294
			if ( ! is_numeric( $fb_app_id ) ) {
1295
				$fb_app_id = '';
1296
			}
1297
			wp_localize_script(
1298
				'jetpack-facebook-embed',
1299
				'jpfbembed',
1300
				array(
1301
					'appid'  => $fb_app_id,
1302
					'locale' => $this->get_locale(),
1303
				)
1304
			);
1305
		}
1306
1307
		/**
1308
		 * As jetpack_register_genericons is by default fired off a hook,
1309
		 * the hook may have already fired by this point.
1310
		 * So, let's just trigger it manually.
1311
		 */
1312
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1313
		jetpack_register_genericons();
1314
1315
		/**
1316
		 * Register the social logos
1317
		 */
1318
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1319
		jetpack_register_social_logos();
1320
1321 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1322
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1323
		}
1324
	}
1325
1326
	/**
1327
	 * Guess locale from language code.
1328
	 *
1329
	 * @param string $lang Language code.
1330
	 * @return string|bool
1331
	 */
1332 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1333
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1334
			return 'en_US';
1335
		}
1336
1337
		if ( ! class_exists( 'GP_Locales' ) ) {
1338
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1339
				return false;
1340
			}
1341
1342
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1343
		}
1344
1345
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1346
			// WP.com: get_locale() returns 'it'
1347
			$locale = GP_Locales::by_slug( $lang );
1348
		} else {
1349
			// Jetpack: get_locale() returns 'it_IT';
1350
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1351
		}
1352
1353
		if ( ! $locale ) {
1354
			return false;
1355
		}
1356
1357
		if ( empty( $locale->facebook_locale ) ) {
1358
			if ( empty( $locale->wp_locale ) ) {
1359
				return false;
1360
			} else {
1361
				// Facebook SDK is smart enough to fall back to en_US if a
1362
				// locale isn't supported. Since supported Facebook locales
1363
				// can fall out of sync, we'll attempt to use the known
1364
				// wp_locale value and rely on said fallback.
1365
				return $locale->wp_locale;
1366
			}
1367
		}
1368
1369
		return $locale->facebook_locale;
1370
	}
1371
1372
	/**
1373
	 * Get the locale.
1374
	 *
1375
	 * @return string|bool
1376
	 */
1377
	function get_locale() {
1378
		$locale = $this->guess_locale_from_lang( get_locale() );
1379
1380
		if ( ! $locale ) {
1381
			$locale = 'en_US';
1382
		}
1383
1384
		return $locale;
1385
	}
1386
1387
	/**
1388
	 * Return the network_site_url so that .com knows what network this site is a part of.
1389
	 *
1390
	 * @param  bool $option
1391
	 * @return string
1392
	 */
1393
	public function jetpack_main_network_site_option( $option ) {
1394
		return network_site_url();
1395
	}
1396
	/**
1397
	 * Network Name.
1398
	 */
1399
	static function network_name( $option = null ) {
1400
		global $current_site;
1401
		return $current_site->site_name;
1402
	}
1403
	/**
1404
	 * Does the network allow new user and site registrations.
1405
	 *
1406
	 * @return string
1407
	 */
1408
	static function network_allow_new_registrations( $option = null ) {
1409
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1410
	}
1411
	/**
1412
	 * Does the network allow admins to add new users.
1413
	 *
1414
	 * @return boolian
1415
	 */
1416
	static function network_add_new_users( $option = null ) {
1417
		return (bool) get_site_option( 'add_new_users' );
1418
	}
1419
	/**
1420
	 * File upload psace left per site in MB.
1421
	 *  -1 means NO LIMIT.
1422
	 *
1423
	 * @return number
1424
	 */
1425
	static function network_site_upload_space( $option = null ) {
1426
		// value in MB
1427
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1428
	}
1429
1430
	/**
1431
	 * Network allowed file types.
1432
	 *
1433
	 * @return string
1434
	 */
1435
	static function network_upload_file_types( $option = null ) {
1436
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1437
	}
1438
1439
	/**
1440
	 * Maximum file upload size set by the network.
1441
	 *
1442
	 * @return number
1443
	 */
1444
	static function network_max_upload_file_size( $option = null ) {
1445
		// value in KB
1446
		return get_site_option( 'fileupload_maxk', 300 );
1447
	}
1448
1449
	/**
1450
	 * Lets us know if a site allows admins to manage the network.
1451
	 *
1452
	 * @return array
1453
	 */
1454
	static function network_enable_administration_menus( $option = null ) {
1455
		return get_site_option( 'menu_items' );
1456
	}
1457
1458
	/**
1459
	 * If a user has been promoted to or demoted from admin, we need to clear the
1460
	 * jetpack_other_linked_admins transient.
1461
	 *
1462
	 * @since 4.3.2
1463
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1464
	 *
1465
	 * @param int    $user_id   The user ID whose role changed.
1466
	 * @param string $role      The new role.
1467
	 * @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...
1468
	 */
1469
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1470
		if ( 'administrator' == $role
1471
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1472
			|| is_null( $old_roles )
1473
		) {
1474
			delete_transient( 'jetpack_other_linked_admins' );
1475
		}
1476
	}
1477
1478
	/**
1479
	 * Checks to see if there are any other users available to become primary
1480
	 * Users must both:
1481
	 * - Be linked to wpcom
1482
	 * - Be an admin
1483
	 *
1484
	 * @return mixed False if no other users are linked, Int if there are.
1485
	 */
1486
	static function get_other_linked_admins() {
1487
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1488
1489
		if ( false === $other_linked_users ) {
1490
			$admins = get_users( array( 'role' => 'administrator' ) );
1491
			if ( count( $admins ) > 1 ) {
1492
				$available = array();
1493
				foreach ( $admins as $admin ) {
1494
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1495
						$available[] = $admin->ID;
1496
					}
1497
				}
1498
1499
				$count_connected_admins = count( $available );
1500
				if ( count( $available ) > 1 ) {
1501
					$other_linked_users = $count_connected_admins;
1502
				} else {
1503
					$other_linked_users = 0;
1504
				}
1505
			} else {
1506
				$other_linked_users = 0;
1507
			}
1508
1509
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1510
		}
1511
1512
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1513
	}
1514
1515
	/**
1516
	 * Return whether we are dealing with a multi network setup or not.
1517
	 * The reason we are type casting this is because we want to avoid the situation where
1518
	 * the result is false since when is_main_network_option return false it cases
1519
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1520
	 * database which could be set to anything as opposed to what this function returns.
1521
	 *
1522
	 * @param  bool $option
1523
	 *
1524
	 * @return boolean
1525
	 */
1526
	public function is_main_network_option( $option ) {
1527
		// return '1' or ''
1528
		return (string) (bool) self::is_multi_network();
1529
	}
1530
1531
	/**
1532
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1533
	 *
1534
	 * @param  string $option
1535
	 * @return boolean
1536
	 */
1537
	public function is_multisite( $option ) {
1538
		return (string) (bool) is_multisite();
1539
	}
1540
1541
	/**
1542
	 * Implemented since there is no core is multi network function
1543
	 * Right now there is no way to tell if we which network is the dominant network on the system
1544
	 *
1545
	 * @since  3.3
1546
	 * @return boolean
1547
	 */
1548 View Code Duplication
	public static function is_multi_network() {
1549
		global  $wpdb;
1550
1551
		// if we don't have a multi site setup no need to do any more
1552
		if ( ! is_multisite() ) {
1553
			return false;
1554
		}
1555
1556
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1557
		if ( $num_sites > 1 ) {
1558
			return true;
1559
		} else {
1560
			return false;
1561
		}
1562
	}
1563
1564
	/**
1565
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1566
	 *
1567
	 * @return null
1568
	 */
1569
	function update_jetpack_main_network_site_option() {
1570
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1571
	}
1572
	/**
1573
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1574
	 */
1575
	function update_jetpack_network_settings() {
1576
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1577
		// Only sync this info for the main network site.
1578
	}
1579
1580
	/**
1581
	 * Get back if the current site is single user site.
1582
	 *
1583
	 * @return bool
1584
	 */
1585 View Code Duplication
	public static function is_single_user_site() {
1586
		global $wpdb;
1587
1588
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1589
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1590
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1591
		}
1592
		return 1 === (int) $some_users;
1593
	}
1594
1595
	/**
1596
	 * Returns true if the site has file write access false otherwise.
1597
	 *
1598
	 * @return string ( '1' | '0' )
1599
	 **/
1600
	public static function file_system_write_access() {
1601
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1602
			require_once ABSPATH . 'wp-admin/includes/file.php';
1603
		}
1604
1605
		require_once ABSPATH . 'wp-admin/includes/template.php';
1606
1607
		$filesystem_method = get_filesystem_method();
1608
		if ( $filesystem_method === 'direct' ) {
1609
			return 1;
1610
		}
1611
1612
		ob_start();
1613
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1614
		ob_end_clean();
1615
		if ( $filesystem_credentials_are_stored ) {
1616
			return 1;
1617
		}
1618
		return 0;
1619
	}
1620
1621
	/**
1622
	 * Finds out if a site is using a version control system.
1623
	 *
1624
	 * @return string ( '1' | '0' )
1625
	 **/
1626
	public static function is_version_controlled() {
1627
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1628
		return (string) (int) Functions::is_version_controlled();
1629
	}
1630
1631
	/**
1632
	 * Determines whether the current theme supports featured images or not.
1633
	 *
1634
	 * @return string ( '1' | '0' )
1635
	 */
1636
	public static function featured_images_enabled() {
1637
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1638
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1639
	}
1640
1641
	/**
1642
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1643
	 *
1644
	 * @deprecated 4.7 use get_avatar_url instead.
1645
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1646
	 * @param int               $size Size of the avatar image
1647
	 * @param string            $default URL to a default image to use if no avatar is available
1648
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1649
	 *
1650
	 * @return array
1651
	 */
1652
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1653
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1654
		return get_avatar_url(
1655
			$id_or_email,
1656
			array(
1657
				'size'          => $size,
1658
				'default'       => $default,
1659
				'force_default' => $force_display,
1660
			)
1661
		);
1662
	}
1663
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1664
	/**
1665
	 * jetpack_updates is saved in the following schema:
1666
	 *
1667
	 * array (
1668
	 *      'plugins'                       => (int) Number of plugin updates available.
1669
	 *      'themes'                        => (int) Number of theme updates available.
1670
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1671
	 *      'translations'                  => (int) Number of translation updates available.
1672
	 *      'total'                         => (int) Total of all available updates.
1673
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1674
	 * )
1675
	 *
1676
	 * @return array
1677
	 */
1678
	public static function get_updates() {
1679
		$update_data = wp_get_update_data();
1680
1681
		// Stores the individual update counts as well as the total count.
1682
		if ( isset( $update_data['counts'] ) ) {
1683
			$updates = $update_data['counts'];
1684
		}
1685
1686
		// If we need to update WordPress core, let's find the latest version number.
1687 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1688
			$cur = get_preferred_from_update_core();
1689
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1690
				$updates['wp_update_version'] = $cur->current;
1691
			}
1692
		}
1693
		return isset( $updates ) ? $updates : array();
1694
	}
1695
	// phpcs:enable
1696
1697
	public static function get_update_details() {
1698
		$update_details = array(
1699
			'update_core'    => get_site_transient( 'update_core' ),
1700
			'update_plugins' => get_site_transient( 'update_plugins' ),
1701
			'update_themes'  => get_site_transient( 'update_themes' ),
1702
		);
1703
		return $update_details;
1704
	}
1705
1706
	public static function refresh_update_data() {
1707
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1708
1709
	}
1710
1711
	public static function refresh_theme_data() {
1712
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1713
	}
1714
1715
	/**
1716
	 * Is Jetpack active?
1717
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1718
	 *
1719
	 * This method is deprecated since 9.6.0. Please use one of the methods provided by the Manager class in the Connection package,
1720
	 * or Jetpack::is_connection_ready if you want to know when the Jetpack plugin starts considering the connection ready to be used.
1721
	 *
1722
	 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
1723
	 *
1724
	 * @deprecated 9.6.0
1725
	 *
1726
	 * @return bool
1727
	 */
1728
	public static function is_active() {
1729
		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...
1730
	}
1731
1732
	/**
1733
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1734
	 *
1735
	 * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1736
	 * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1737
	 * users and this option will be available by default for everybody.
1738
	 *
1739
	 * @since 9.6.0
1740
	 *
1741
	 * @return bool is the site connection ready to be used?
1742
	 */
1743
	public static function is_connection_ready() {
1744
		if ( ( new Status() )->is_no_user_testing_mode() ) {
1745
			return self::connection()->is_connected();
1746
		}
1747
		return (bool) self::connection()->has_connected_owner();
1748
	}
1749
1750
	/**
1751
	 * Make an API call to WordPress.com for plan status
1752
	 *
1753
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1754
	 *
1755
	 * @return bool True if plan is updated, false if no update
1756
	 */
1757
	public static function refresh_active_plan_from_wpcom() {
1758
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1759
		return Jetpack_Plan::refresh_from_wpcom();
1760
	}
1761
1762
	/**
1763
	 * Get the plan that this Jetpack site is currently using
1764
	 *
1765
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1766
	 * @return array Active Jetpack plan details.
1767
	 */
1768
	public static function get_active_plan() {
1769
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1770
		return Jetpack_Plan::get();
1771
	}
1772
1773
	/**
1774
	 * Determine whether the active plan supports a particular feature
1775
	 *
1776
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1777
	 * @return bool True if plan supports feature, false if not.
1778
	 */
1779
	public static function active_plan_supports( $feature ) {
1780
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1781
		return Jetpack_Plan::supports( $feature );
1782
	}
1783
1784
	/**
1785
	 * Deprecated: Is Jetpack in development (offline) mode?
1786
	 *
1787
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1788
	 * and themes still use it, and we do not want to flood them with notices.
1789
	 *
1790
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1791
	 *
1792
	 * @deprecated since 8.0.
1793
	 */
1794
	public static function is_development_mode() {
1795
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1796
		return ( new Status() )->is_offline_mode();
1797
	}
1798
1799
	/**
1800
	 * Whether the site is currently onboarding or not.
1801
	 * A site is considered as being onboarded if it currently has an onboarding token.
1802
	 *
1803
	 * @since 5.8
1804
	 *
1805
	 * @access public
1806
	 * @static
1807
	 *
1808
	 * @return bool True if the site is currently onboarding, false otherwise
1809
	 */
1810
	public static function is_onboarding() {
1811
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1812
	}
1813
1814
	/**
1815
	 * Determines reason for Jetpack offline mode.
1816
	 */
1817
	public static function development_mode_trigger_text() {
1818
		$status = new Status();
1819
1820
		if ( ! $status->is_offline_mode() ) {
1821
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1822
		}
1823
1824
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1825
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1826
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1827
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1828
		} elseif ( $status->is_local_site() ) {
1829
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1830
			/** This filter is documented in packages/status/src/class-status.php */
1831
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1832
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1833
		} else {
1834
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1835
		}
1836
1837
		return $notice;
1838
1839
	}
1840
	/**
1841
	 * Get Jetpack offline mode notice text and notice class.
1842
	 *
1843
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1844
	 */
1845
	public static function show_development_mode_notice() {
1846 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1847
			$notice = sprintf(
1848
				/* translators: %s is a URL */
1849
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1850
				Redirect::get_url( 'jetpack-support-development-mode' )
1851
			);
1852
1853
			$notice .= ' ' . self::development_mode_trigger_text();
1854
1855
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1856
		}
1857
1858
		// Throw up a notice if using a development version and as for feedback.
1859
		if ( self::is_development_version() ) {
1860
			/* translators: %s is a URL */
1861
			$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' ) );
1862
1863
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1864
		}
1865
		// Throw up a notice if using staging mode
1866 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1867
			/* translators: %s is a URL */
1868
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1869
1870
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1871
		}
1872
	}
1873
1874
	/**
1875
	 * Whether Jetpack's version maps to a public release, or a development version.
1876
	 */
1877
	public static function is_development_version() {
1878
		/**
1879
		 * Allows filtering whether this is a development version of Jetpack.
1880
		 *
1881
		 * This filter is especially useful for tests.
1882
		 *
1883
		 * @since 4.3.0
1884
		 *
1885
		 * @param bool $development_version Is this a develoment version of Jetpack?
1886
		 */
1887
		return (bool) apply_filters(
1888
			'jetpack_development_version',
1889
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1890
		);
1891
	}
1892
1893
	/**
1894
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1895
	 */
1896
	public static function is_user_connected( $user_id = false ) {
1897
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1898
		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...
1899
	}
1900
1901
	/**
1902
	 * Get the wpcom user data of the current|specified connected user.
1903
	 */
1904
	public static function get_connected_user_data( $user_id = null ) {
1905
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1906
		return self::connection()->get_connected_user_data( $user_id );
1907
	}
1908
1909
	/**
1910
	 * Get the wpcom email of the current|specified connected user.
1911
	 */
1912
	public static function get_connected_user_email( $user_id = null ) {
1913
		if ( ! $user_id ) {
1914
			$user_id = get_current_user_id();
1915
		}
1916
1917
		$xml = new Jetpack_IXR_Client(
1918
			array(
1919
				'user_id' => $user_id,
1920
			)
1921
		);
1922
		$xml->query( 'wpcom.getUserEmail' );
1923
		if ( ! $xml->isError() ) {
1924
			return $xml->getResponse();
1925
		}
1926
		return false;
1927
	}
1928
1929
	/**
1930
	 * Get the wpcom email of the master user.
1931
	 */
1932
	public static function get_master_user_email() {
1933
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1934
		if ( $master_user_id ) {
1935
			return self::get_connected_user_email( $master_user_id );
1936
		}
1937
		return '';
1938
	}
1939
1940
	/**
1941
	 * Whether the current user is the connection owner.
1942
	 *
1943
	 * @deprecated since 7.7
1944
	 *
1945
	 * @return bool Whether the current user is the connection owner.
1946
	 */
1947
	public function current_user_is_connection_owner() {
1948
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1949
		return self::connection()->is_connection_owner();
1950
	}
1951
1952
	/**
1953
	 * Gets current user IP address.
1954
	 *
1955
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1956
	 *
1957
	 * @return string                  Current user IP address.
1958
	 */
1959
	public static function current_user_ip( $check_all_headers = false ) {
1960
		if ( $check_all_headers ) {
1961
			foreach ( array(
1962
				'HTTP_CF_CONNECTING_IP',
1963
				'HTTP_CLIENT_IP',
1964
				'HTTP_X_FORWARDED_FOR',
1965
				'HTTP_X_FORWARDED',
1966
				'HTTP_X_CLUSTER_CLIENT_IP',
1967
				'HTTP_FORWARDED_FOR',
1968
				'HTTP_FORWARDED',
1969
				'HTTP_VIA',
1970
			) as $key ) {
1971
				if ( ! empty( $_SERVER[ $key ] ) ) {
1972
					return $_SERVER[ $key ];
1973
				}
1974
			}
1975
		}
1976
1977
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1978
	}
1979
1980
	/**
1981
	 * Synchronize connected user role changes
1982
	 */
1983
	function user_role_change( $user_id ) {
1984
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1985
		Users::user_role_change( $user_id );
1986
	}
1987
1988
	/**
1989
	 * Loads the currently active modules.
1990
	 */
1991
	public static function load_modules() {
1992
		$is_offline_mode = ( new Status() )->is_offline_mode();
1993
		if (
1994
			! self::is_connection_ready()
1995
			&& ! $is_offline_mode
1996
			&& ! self::is_onboarding()
1997
			&& (
1998
				! is_multisite()
1999
				|| ! get_site_option( 'jetpack_protect_active' )
2000
			)
2001
		) {
2002
			return;
2003
		}
2004
2005
		$version = Jetpack_Options::get_option( 'version' );
2006 View Code Duplication
		if ( ! $version ) {
2007
			$version = $old_version = JETPACK__VERSION . ':' . time();
2008
			/** This action is documented in class.jetpack.php */
2009
			do_action( 'updating_jetpack_version', $version, false );
2010
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2011
		}
2012
		list( $version ) = explode( ':', $version );
2013
2014
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
2015
2016
		$modules_data = array();
2017
2018
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
2019
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
2020
			$updated_modules = array();
2021
			foreach ( $modules as $module ) {
2022
				$modules_data[ $module ] = self::get_module( $module );
2023
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
2024
					continue;
2025
				}
2026
2027
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2028
					continue;
2029
				}
2030
2031
				$updated_modules[] = $module;
2032
			}
2033
2034
			$modules = array_diff( $modules, $updated_modules );
2035
		}
2036
2037
		foreach ( $modules as $index => $module ) {
2038
			// If we're in offline mode, disable modules requiring a connection.
2039
			if ( $is_offline_mode ) {
2040
				// Prime the pump if we need to
2041
				if ( empty( $modules_data[ $module ] ) ) {
2042
					$modules_data[ $module ] = self::get_module( $module );
2043
				}
2044
				// If the module requires a connection, but we're in local mode, don't include it.
2045
				if ( $modules_data[ $module ]['requires_connection'] ) {
2046
					continue;
2047
				}
2048
			}
2049
2050
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2051
				continue;
2052
			}
2053
2054
			if ( ! include_once self::get_module_path( $module ) ) {
2055
				unset( $modules[ $index ] );
2056
				self::update_active_modules( array_values( $modules ) );
2057
				continue;
2058
			}
2059
2060
			/**
2061
			 * Fires when a specific module is loaded.
2062
			 * The dynamic part of the hook, $module, is the module slug.
2063
			 *
2064
			 * @since 1.1.0
2065
			 */
2066
			do_action( 'jetpack_module_loaded_' . $module );
2067
		}
2068
2069
		/**
2070
		 * Fires when all the modules are loaded.
2071
		 *
2072
		 * @since 1.1.0
2073
		 */
2074
		do_action( 'jetpack_modules_loaded' );
2075
2076
		// 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.
2077
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2078
	}
2079
2080
	/**
2081
	 * Check if Jetpack's REST API compat file should be included
2082
	 *
2083
	 * @action plugins_loaded
2084
	 * @return null
2085
	 */
2086
	public function check_rest_api_compat() {
2087
		/**
2088
		 * Filters the list of REST API compat files to be included.
2089
		 *
2090
		 * @since 2.2.5
2091
		 *
2092
		 * @param array $args Array of REST API compat files to include.
2093
		 */
2094
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2095
2096
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2097
			require_once $_jetpack_rest_api_compat_include;
2098
		}
2099
	}
2100
2101
	/**
2102
	 * Gets all plugins currently active in values, regardless of whether they're
2103
	 * traditionally activated or network activated.
2104
	 *
2105
	 * @todo Store the result in core's object cache maybe?
2106
	 */
2107
	public static function get_active_plugins() {
2108
		$active_plugins = (array) get_option( 'active_plugins', array() );
2109
2110
		if ( is_multisite() ) {
2111
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2112
			// whereas active_plugins stores them in the values.
2113
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2114
			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...
2115
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2116
			}
2117
		}
2118
2119
		sort( $active_plugins );
2120
2121
		return array_unique( $active_plugins );
2122
	}
2123
2124
	/**
2125
	 * Gets and parses additional plugin data to send with the heartbeat data
2126
	 *
2127
	 * @since 3.8.1
2128
	 *
2129
	 * @return array Array of plugin data
2130
	 */
2131
	public static function get_parsed_plugin_data() {
2132
		if ( ! function_exists( 'get_plugins' ) ) {
2133
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2134
		}
2135
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2136
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2137
		$active_plugins = self::get_active_plugins();
2138
2139
		$plugins = array();
2140
		foreach ( $all_plugins as $path => $plugin_data ) {
2141
			$plugins[ $path ] = array(
2142
				'is_active' => in_array( $path, $active_plugins ),
2143
				'file'      => $path,
2144
				'name'      => $plugin_data['Name'],
2145
				'version'   => $plugin_data['Version'],
2146
				'author'    => $plugin_data['Author'],
2147
			);
2148
		}
2149
2150
		return $plugins;
2151
	}
2152
2153
	/**
2154
	 * Gets and parses theme data to send with the heartbeat data
2155
	 *
2156
	 * @since 3.8.1
2157
	 *
2158
	 * @return array Array of theme data
2159
	 */
2160
	public static function get_parsed_theme_data() {
2161
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2162
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2163
2164
		$themes = array();
2165
		foreach ( $all_themes as $slug => $theme_data ) {
2166
			$theme_headers = array();
2167
			foreach ( $header_keys as $header_key ) {
2168
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2169
			}
2170
2171
			$themes[ $slug ] = array(
2172
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2173
				'slug'            => $slug,
2174
				'theme_root'      => $theme_data->get_theme_root_uri(),
2175
				'parent'          => $theme_data->parent(),
2176
				'headers'         => $theme_headers,
2177
			);
2178
		}
2179
2180
		return $themes;
2181
	}
2182
2183
	/**
2184
	 * Checks whether a specific plugin is active.
2185
	 *
2186
	 * We don't want to store these in a static variable, in case
2187
	 * there are switch_to_blog() calls involved.
2188
	 */
2189
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2190
		return in_array( $plugin, self::get_active_plugins() );
2191
	}
2192
2193
	/**
2194
	 * Check if Jetpack's Open Graph tags should be used.
2195
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2196
	 *
2197
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2198
	 * @action plugins_loaded
2199
	 * @return null
2200
	 */
2201
	public function check_open_graph() {
2202
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2203
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2204
		}
2205
2206
		$active_plugins = self::get_active_plugins();
2207
2208
		if ( ! empty( $active_plugins ) ) {
2209
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2210
				if ( in_array( $plugin, $active_plugins ) ) {
2211
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2212
					break;
2213
				}
2214
			}
2215
		}
2216
2217
		/**
2218
		 * Allow the addition of Open Graph Meta Tags to all pages.
2219
		 *
2220
		 * @since 2.0.3
2221
		 *
2222
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2223
		 */
2224
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2225
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2226
		}
2227
	}
2228
2229
	/**
2230
	 * Check if Jetpack's Twitter tags should be used.
2231
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2232
	 *
2233
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2234
	 * @action plugins_loaded
2235
	 * @return null
2236
	 */
2237
	public function check_twitter_tags() {
2238
2239
		$active_plugins = self::get_active_plugins();
2240
2241
		if ( ! empty( $active_plugins ) ) {
2242
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2243
				if ( in_array( $plugin, $active_plugins ) ) {
2244
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2245
					break;
2246
				}
2247
			}
2248
		}
2249
2250
		/**
2251
		 * Allow Twitter Card Meta tags to be disabled.
2252
		 *
2253
		 * @since 2.6.0
2254
		 *
2255
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2256
		 */
2257
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2258
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2259
		}
2260
	}
2261
2262
	/**
2263
	 * Allows plugins to submit security reports.
2264
	 *
2265
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2266
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2267
	 * @param array  $args         See definitions above
2268
	 */
2269
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2270
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2271
	}
2272
2273
	/* Jetpack Options API */
2274
2275
	public static function get_option_names( $type = 'compact' ) {
2276
		return Jetpack_Options::get_option_names( $type );
2277
	}
2278
2279
	/**
2280
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2281
	 *
2282
	 * @param string $name    Option name
2283
	 * @param mixed  $default (optional)
2284
	 */
2285
	public static function get_option( $name, $default = false ) {
2286
		return Jetpack_Options::get_option( $name, $default );
2287
	}
2288
2289
	/**
2290
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2291
	 *
2292
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2293
	 * @param string $name  Option name
2294
	 * @param mixed  $value Option value
2295
	 */
2296
	public static function update_option( $name, $value ) {
2297
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2298
		return Jetpack_Options::update_option( $name, $value );
2299
	}
2300
2301
	/**
2302
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2303
	 *
2304
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2305
	 * @param array $array array( option name => option value, ... )
2306
	 */
2307
	public static function update_options( $array ) {
2308
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2309
		return Jetpack_Options::update_options( $array );
2310
	}
2311
2312
	/**
2313
	 * Deletes the given option.  May be passed multiple option names as an array.
2314
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2315
	 *
2316
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2317
	 * @param string|array $names
2318
	 */
2319
	public static function delete_option( $names ) {
2320
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2321
		return Jetpack_Options::delete_option( $names );
2322
	}
2323
2324
	/**
2325
	 * Enters a user token into the user_tokens option
2326
	 *
2327
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2328
	 *
2329
	 * @param int    $user_id The user id.
2330
	 * @param string $token The user token.
2331
	 * @param bool   $is_master_user Whether the user is the master user.
2332
	 * @return bool
2333
	 */
2334
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2335
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2336
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2337
	}
2338
2339
	/**
2340
	 * Returns an array of all PHP files in the specified absolute path.
2341
	 * Equivalent to glob( "$absolute_path/*.php" ).
2342
	 *
2343
	 * @param string $absolute_path The absolute path of the directory to search.
2344
	 * @return array Array of absolute paths to the PHP files.
2345
	 */
2346
	public static function glob_php( $absolute_path ) {
2347
		if ( function_exists( 'glob' ) ) {
2348
			return glob( "$absolute_path/*.php" );
2349
		}
2350
2351
		$absolute_path = untrailingslashit( $absolute_path );
2352
		$files         = array();
2353
		if ( ! $dir = @opendir( $absolute_path ) ) {
2354
			return $files;
2355
		}
2356
2357
		while ( false !== $file = readdir( $dir ) ) {
2358
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2359
				continue;
2360
			}
2361
2362
			$file = "$absolute_path/$file";
2363
2364
			if ( ! is_file( $file ) ) {
2365
				continue;
2366
			}
2367
2368
			$files[] = $file;
2369
		}
2370
2371
		closedir( $dir );
2372
2373
		return $files;
2374
	}
2375
2376
	public static function activate_new_modules( $redirect = false ) {
2377
		if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2378
			return;
2379
		}
2380
2381
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2382 View Code Duplication
		if ( ! $jetpack_old_version ) {
2383
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2384
			/** This action is documented in class.jetpack.php */
2385
			do_action( 'updating_jetpack_version', $version, false );
2386
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2387
		}
2388
2389
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2390
2391
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2392
			return;
2393
		}
2394
2395
		$active_modules     = self::get_active_modules();
2396
		$reactivate_modules = array();
2397
		foreach ( $active_modules as $active_module ) {
2398
			$module = self::get_module( $active_module );
2399
			if ( ! isset( $module['changed'] ) ) {
2400
				continue;
2401
			}
2402
2403
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2404
				continue;
2405
			}
2406
2407
			$reactivate_modules[] = $active_module;
2408
			self::deactivate_module( $active_module );
2409
		}
2410
2411
		$new_version = JETPACK__VERSION . ':' . time();
2412
		/** This action is documented in class.jetpack.php */
2413
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2414
		Jetpack_Options::update_options(
2415
			array(
2416
				'version'     => $new_version,
2417
				'old_version' => $jetpack_old_version,
2418
			)
2419
		);
2420
2421
		self::state( 'message', 'modules_activated' );
2422
2423
		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...
2424
2425
		if ( $redirect ) {
2426
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2427
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2428
				$page = $_GET['page'];
2429
			}
2430
2431
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2432
			exit;
2433
		}
2434
	}
2435
2436
	/**
2437
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2438
	 * Make sure to tuck away module "library" files in a sub-directory.
2439
	 *
2440
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2441
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2442
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2443
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2444
	 *
2445
	 * @return array $modules Array of module slugs
2446
	 */
2447
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2448
		static $modules = null;
2449
2450
		if ( ! isset( $modules ) ) {
2451
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2452
			// Use the cache if we're on the front-end and it's available...
2453
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2454
				$modules = $available_modules_option[ JETPACK__VERSION ];
2455
			} else {
2456
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2457
2458
				$modules = array();
2459
2460
				foreach ( $files as $file ) {
2461
					if ( ! $headers = self::get_module( $file ) ) {
2462
						continue;
2463
					}
2464
2465
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2466
				}
2467
2468
				Jetpack_Options::update_option(
2469
					'available_modules',
2470
					array(
2471
						JETPACK__VERSION => $modules,
2472
					)
2473
				);
2474
			}
2475
		}
2476
2477
		/**
2478
		 * Filters the array of modules available to be activated.
2479
		 *
2480
		 * @since 2.4.0
2481
		 *
2482
		 * @param array $modules Array of available modules.
2483
		 * @param string $min_version Minimum version number required to use modules.
2484
		 * @param string $max_version Maximum version number required to use modules.
2485
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2486
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2487
		 */
2488
		$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...
2489
2490
		if ( ! $min_version && ! $max_version && is_null( $requires_connection ) && is_null( $requires_user_connection ) ) {
2491
			return array_keys( $mods );
2492
		}
2493
2494
		$r = array();
2495
		foreach ( $mods as $slug => $introduced ) {
2496
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2497
				continue;
2498
			}
2499
2500
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2501
				continue;
2502
			}
2503
2504
			$mod_details = self::get_module( $slug );
2505
2506
			if ( null !== $requires_connection && (bool) $requires_connection !== $mod_details['requires_connection'] ) {
2507
				continue;
2508
			}
2509
2510
			if ( null !== $requires_user_connection && (bool) $requires_user_connection !== $mod_details['requires_user_connection'] ) {
2511
				continue;
2512
			}
2513
2514
			$r[] = $slug;
2515
		}
2516
2517
		return $r;
2518
	}
2519
2520
	/**
2521
	 * Get default modules loaded on activation.
2522
	 *
2523
	 * @param bool|string $min_version Onlu return modules introduced in this version or later. Default is false, do not filter.
2524
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2525
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2526
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2527
	 *
2528
	 * @return array $modules Array of module slugs
2529
	 */
2530
	public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2531
		$return = array();
2532
2533
		foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2534
			$module_data = self::get_module( $module );
2535
2536
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2537
				case 'yes':
2538
					$return[] = $module;
2539
					break;
2540
				case 'public':
2541
					if ( Jetpack_Options::get_option( 'public' ) ) {
2542
						$return[] = $module;
2543
					}
2544
					break;
2545
				case 'no':
2546
				default:
2547
					break;
2548
			}
2549
		}
2550
		/**
2551
		 * Filters the array of default modules.
2552
		 *
2553
		 * @since 2.5.0
2554
		 *
2555
		 * @param array $return Array of default modules.
2556
		 * @param string $min_version Minimum version number required to use modules.
2557
		 * @param string $max_version Maximum version number required to use modules.
2558
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2559
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2560
		 */
2561
		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...
2562
	}
2563
2564
	/**
2565
	 * Checks activated modules during auto-activation to determine
2566
	 * if any of those modules are being deprecated.  If so, close
2567
	 * them out, and add any replacement modules.
2568
	 *
2569
	 * Runs at priority 99 by default.
2570
	 *
2571
	 * This is run late, so that it can still activate a module if
2572
	 * the new module is a replacement for another that the user
2573
	 * currently has active, even if something at the normal priority
2574
	 * would kibosh everything.
2575
	 *
2576
	 * @since 2.6
2577
	 * @uses jetpack_get_default_modules filter
2578
	 * @param array $modules
2579
	 * @return array
2580
	 */
2581
	function handle_deprecated_modules( $modules ) {
2582
		$deprecated_modules = array(
2583
			'debug'            => null,  // Closed out and moved to the debugger library.
2584
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2585
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2586
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2587
		);
2588
2589
		// Don't activate SSO if they never completed activating WPCC.
2590
		if ( self::is_module_active( 'wpcc' ) ) {
2591
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2592
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2593
				$deprecated_modules['wpcc'] = null;
2594
			}
2595
		}
2596
2597
		foreach ( $deprecated_modules as $module => $replacement ) {
2598
			if ( self::is_module_active( $module ) ) {
2599
				self::deactivate_module( $module );
2600
				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...
2601
					$modules[] = $replacement;
2602
				}
2603
			}
2604
		}
2605
2606
		return array_unique( $modules );
2607
	}
2608
2609
	/**
2610
	 * Checks activated plugins during auto-activation to determine
2611
	 * if any of those plugins are in the list with a corresponding module
2612
	 * that is not compatible with the plugin. The module will not be allowed
2613
	 * to auto-activate.
2614
	 *
2615
	 * @since 2.6
2616
	 * @uses jetpack_get_default_modules filter
2617
	 * @param array $modules
2618
	 * @return array
2619
	 */
2620
	function filter_default_modules( $modules ) {
2621
2622
		$active_plugins = self::get_active_plugins();
2623
2624
		if ( ! empty( $active_plugins ) ) {
2625
2626
			// For each module we'd like to auto-activate...
2627
			foreach ( $modules as $key => $module ) {
2628
				// If there are potential conflicts for it...
2629
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2630
					// For each potential conflict...
2631
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2632
						// If that conflicting plugin is active...
2633
						if ( in_array( $plugin, $active_plugins ) ) {
2634
							// Remove that item from being auto-activated.
2635
							unset( $modules[ $key ] );
2636
						}
2637
					}
2638
				}
2639
			}
2640
		}
2641
2642
		return $modules;
2643
	}
2644
2645
	/**
2646
	 * Extract a module's slug from its full path.
2647
	 */
2648
	public static function get_module_slug( $file ) {
2649
		return str_replace( '.php', '', basename( $file ) );
2650
	}
2651
2652
	/**
2653
	 * Generate a module's path from its slug.
2654
	 */
2655
	public static function get_module_path( $slug ) {
2656
		/**
2657
		 * Filters the path of a modules.
2658
		 *
2659
		 * @since 7.4.0
2660
		 *
2661
		 * @param array $return The absolute path to a module's root php file
2662
		 * @param string $slug The module slug
2663
		 */
2664
		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...
2665
	}
2666
2667
	/**
2668
	 * Load module data from module file. Headers differ from WordPress
2669
	 * plugin headers to avoid them being identified as standalone
2670
	 * plugins on the WordPress plugins page.
2671
	 */
2672
	public static function get_module( $module ) {
2673
		$headers = array(
2674
			'name'                      => 'Module Name',
2675
			'description'               => 'Module Description',
2676
			'sort'                      => 'Sort Order',
2677
			'recommendation_order'      => 'Recommendation Order',
2678
			'introduced'                => 'First Introduced',
2679
			'changed'                   => 'Major Changes In',
2680
			'deactivate'                => 'Deactivate',
2681
			'free'                      => 'Free',
2682
			'requires_connection'       => 'Requires Connection',
2683
			'requires_user_connection'  => 'Requires User Connection',
2684
			'auto_activate'             => 'Auto Activate',
2685
			'module_tags'               => 'Module Tags',
2686
			'feature'                   => 'Feature',
2687
			'additional_search_queries' => 'Additional Search Queries',
2688
			'plan_classes'              => 'Plans',
2689
		);
2690
2691
		static $modules_details;
2692
		$file = self::get_module_path( self::get_module_slug( $module ) );
2693
2694
		if ( isset( $modules_details[ $module ] ) ) {
2695
			$mod = $modules_details[ $module ];
2696
		} else {
2697
2698
			$mod = self::get_file_data( $file, $headers );
2699
			if ( empty( $mod['name'] ) ) {
2700
				return false;
2701
			}
2702
2703
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2704
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2705
			$mod['deactivate']               = empty( $mod['deactivate'] );
2706
			$mod['free']                     = empty( $mod['free'] );
2707
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2708
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2709
2710
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2711
				$mod['auto_activate'] = 'No';
2712
			} else {
2713
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2714
			}
2715
2716
			if ( $mod['module_tags'] ) {
2717
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2718
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2719
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2720
			} else {
2721
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2722
			}
2723
2724 View Code Duplication
			if ( $mod['plan_classes'] ) {
2725
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2726
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2727
			} else {
2728
				$mod['plan_classes'] = array( 'free' );
2729
			}
2730
2731 View Code Duplication
			if ( $mod['feature'] ) {
2732
				$mod['feature'] = explode( ',', $mod['feature'] );
2733
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2734
			} else {
2735
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2736
			}
2737
2738
			$modules_details[ $module ] = $mod;
2739
2740
		}
2741
2742
		/**
2743
		 * Filters the feature array on a module.
2744
		 *
2745
		 * This filter allows you to control where each module is filtered: Recommended,
2746
		 * and the default "Other" listing.
2747
		 *
2748
		 * @since 3.5.0
2749
		 *
2750
		 * @param array   $mod['feature'] The areas to feature this module:
2751
		 *     'Recommended' shows on the main Jetpack admin screen.
2752
		 *     'Other' should be the default if no other value is in the array.
2753
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2754
		 * @param array   $mod All the currently assembled module data.
2755
		 */
2756
		$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...
2757
2758
		/**
2759
		 * Filter the returned data about a module.
2760
		 *
2761
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2762
		 * so please be careful.
2763
		 *
2764
		 * @since 3.6.0
2765
		 *
2766
		 * @param array   $mod    The details of the requested module.
2767
		 * @param string  $module The slug of the module, e.g. sharedaddy
2768
		 * @param string  $file   The path to the module source file.
2769
		 */
2770
		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...
2771
	}
2772
2773
	/**
2774
	 * Like core's get_file_data implementation, but caches the result.
2775
	 */
2776
	public static function get_file_data( $file, $headers ) {
2777
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2778
		$file_name = basename( $file );
2779
2780
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2781
2782
		$file_data_option = get_transient( $cache_key );
2783
2784
		if ( ! is_array( $file_data_option ) ) {
2785
			delete_transient( $cache_key );
2786
			$file_data_option = false;
2787
		}
2788
2789
		if ( false === $file_data_option ) {
2790
			$file_data_option = array();
2791
		}
2792
2793
		$key           = md5( $file_name . serialize( $headers ) );
2794
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2795
2796
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2797
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2798
			return $file_data_option[ $key ];
2799
		}
2800
2801
		$data = get_file_data( $file, $headers );
2802
2803
		$file_data_option[ $key ] = $data;
2804
2805
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2806
2807
		return $data;
2808
	}
2809
2810
	/**
2811
	 * Return translated module tag.
2812
	 *
2813
	 * @param string $tag Tag as it appears in each module heading.
2814
	 *
2815
	 * @return mixed
2816
	 */
2817
	public static function translate_module_tag( $tag ) {
2818
		return jetpack_get_module_i18n_tag( $tag );
2819
	}
2820
2821
	/**
2822
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2823
	 *
2824
	 * @since 3.9.2
2825
	 *
2826
	 * @param array $modules
2827
	 *
2828
	 * @return string|void
2829
	 */
2830
	public static function get_translated_modules( $modules ) {
2831
		foreach ( $modules as $index => $module ) {
2832
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2833
			if ( isset( $module['name'] ) ) {
2834
				$modules[ $index ]['name'] = $i18n_module['name'];
2835
			}
2836
			if ( isset( $module['description'] ) ) {
2837
				$modules[ $index ]['description']       = $i18n_module['description'];
2838
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2839
			}
2840
		}
2841
		return $modules;
2842
	}
2843
2844
	/**
2845
	 * Get a list of activated modules as an array of module slugs.
2846
	 */
2847
	public static function get_active_modules() {
2848
		$active = Jetpack_Options::get_option( 'active_modules' );
2849
2850
		if ( ! is_array( $active ) ) {
2851
			$active = array();
2852
		}
2853
2854
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2855
			$active[] = 'vaultpress';
2856
		} else {
2857
			$active = array_diff( $active, array( 'vaultpress' ) );
2858
		}
2859
2860
		// If protect is active on the main site of a multisite, it should be active on all sites.
2861
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2862
			$active[] = 'protect';
2863
		}
2864
2865
		/**
2866
		 * Allow filtering of the active modules.
2867
		 *
2868
		 * Gives theme and plugin developers the power to alter the modules that
2869
		 * are activated on the fly.
2870
		 *
2871
		 * @since 5.8.0
2872
		 *
2873
		 * @param array $active Array of active module slugs.
2874
		 */
2875
		$active = apply_filters( 'jetpack_active_modules', $active );
2876
2877
		return array_unique( $active );
2878
	}
2879
2880
	/**
2881
	 * Check whether or not a Jetpack module is active.
2882
	 *
2883
	 * @param string $module The slug of a Jetpack module.
2884
	 * @return bool
2885
	 *
2886
	 * @static
2887
	 */
2888
	public static function is_module_active( $module ) {
2889
		return in_array( $module, self::get_active_modules() );
2890
	}
2891
2892
	public static function is_module( $module ) {
2893
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2894
	}
2895
2896
	/**
2897
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2898
	 *
2899
	 * @param bool $catch True to start catching, False to stop.
2900
	 *
2901
	 * @static
2902
	 */
2903
	public static function catch_errors( $catch ) {
2904
		static $display_errors, $error_reporting;
2905
2906
		if ( $catch ) {
2907
			$display_errors  = @ini_set( 'display_errors', 1 );
2908
			$error_reporting = @error_reporting( E_ALL );
2909
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2910
		} else {
2911
			@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...
2912
			@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...
2913
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2914
		}
2915
	}
2916
2917
	/**
2918
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2919
	 */
2920
	public static function catch_errors_on_shutdown() {
2921
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2922
	}
2923
2924
	/**
2925
	 * Rewrite any string to make paths easier to read.
2926
	 *
2927
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2928
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2929
	 *
2930
	 * @param $string
2931
	 * @return mixed
2932
	 */
2933
	public static function alias_directories( $string ) {
2934
		// ABSPATH has a trailing slash.
2935
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2936
		// WP_CONTENT_DIR does not have a trailing slash.
2937
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2938
2939
		return $string;
2940
	}
2941
2942
	public static function activate_default_modules(
2943
		$min_version = false,
2944
		$max_version = false,
2945
		$other_modules = array(),
2946
		$redirect = null,
2947
		$send_state_messages = null,
2948
		$requires_connection = null,
2949
		$requires_user_connection = null
2950
	) {
2951
		$jetpack = self::init();
2952
2953
		if ( is_null( $redirect ) ) {
2954
			if (
2955
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2956
			||
2957
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2958
			||
2959
				( defined( 'WP_CLI' ) && WP_CLI )
2960
			||
2961
				( defined( 'DOING_CRON' ) && DOING_CRON )
2962
			||
2963
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2964
			) {
2965
				$redirect = false;
2966
			} elseif ( is_admin() ) {
2967
				$redirect = true;
2968
			} else {
2969
				$redirect = false;
2970
			}
2971
		}
2972
2973
		if ( is_null( $send_state_messages ) ) {
2974
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2975
		}
2976
2977
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2978
		$modules = array_merge( $other_modules, $modules );
2979
2980
		// Look for standalone plugins and disable if active.
2981
2982
		$to_deactivate = array();
2983
		foreach ( $modules as $module ) {
2984
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2985
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2986
			}
2987
		}
2988
2989
		$deactivated = array();
2990
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2991
			list( $probable_file, $probable_title ) = $deactivate_me;
2992
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2993
				$deactivated[] = $module;
2994
			}
2995
		}
2996
2997
		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...
2998
			if ( $send_state_messages ) {
2999
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
3000
			}
3001
3002
			if ( $redirect ) {
3003
				$url = add_query_arg(
3004
					array(
3005
						'action'   => 'activate_default_modules',
3006
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
3007
					),
3008
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
3009
				);
3010
				wp_safe_redirect( $url );
3011
				exit;
3012
			}
3013
		}
3014
3015
		/**
3016
		 * Fires before default modules are activated.
3017
		 *
3018
		 * @since 1.9.0
3019
		 *
3020
		 * @param string    $min_version Minimum version number required to use modules.
3021
		 * @param string    $max_version Maximum version number required to use modules.
3022
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3023
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3024
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3025
		 */
3026
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3027
3028
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3029
		if ( $send_state_messages ) {
3030
			self::restate();
3031
			self::catch_errors( true );
3032
		}
3033
3034
		$active = self::get_active_modules();
3035
3036
		foreach ( $modules as $module ) {
3037
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3038
				$active[] = $module;
3039
				self::update_active_modules( $active );
3040
				continue;
3041
			}
3042
3043
			if ( $send_state_messages && in_array( $module, $active ) ) {
3044
				$module_info = self::get_module( $module );
3045 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3046
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3047
					if ( $active_state = self::state( $state ) ) {
3048
						$active_state = explode( ',', $active_state );
3049
					} else {
3050
						$active_state = array();
3051
					}
3052
					$active_state[] = $module;
3053
					self::state( $state, implode( ',', $active_state ) );
3054
				}
3055
				continue;
3056
			}
3057
3058
			$file = self::get_module_path( $module );
3059
			if ( ! file_exists( $file ) ) {
3060
				continue;
3061
			}
3062
3063
			// we'll override this later if the plugin can be included without fatal error
3064
			if ( $redirect ) {
3065
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3066
			}
3067
3068
			if ( $send_state_messages ) {
3069
				self::state( 'error', 'module_activation_failed' );
3070
				self::state( 'module', $module );
3071
			}
3072
3073
			ob_start();
3074
			require_once $file;
3075
3076
			$active[] = $module;
3077
3078 View Code Duplication
			if ( $send_state_messages ) {
3079
3080
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3081
				if ( $active_state = self::state( $state ) ) {
3082
					$active_state = explode( ',', $active_state );
3083
				} else {
3084
					$active_state = array();
3085
				}
3086
				$active_state[] = $module;
3087
				self::state( $state, implode( ',', $active_state ) );
3088
			}
3089
3090
			self::update_active_modules( $active );
3091
3092
			ob_end_clean();
3093
		}
3094
3095
		if ( $send_state_messages ) {
3096
			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...
3097
			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...
3098
		}
3099
3100
		self::catch_errors( false );
3101
		/**
3102
		 * Fires when default modules are activated.
3103
		 *
3104
		 * @since 1.9.0
3105
		 *
3106
		 * @param string    $min_version Minimum version number required to use modules.
3107
		 * @param string    $max_version Maximum version number required to use modules.
3108
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3109
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3110
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3111
		 */
3112
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3113
	}
3114
3115
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3116
		/**
3117
		 * Fires before a module is activated.
3118
		 *
3119
		 * @since 2.6.0
3120
		 *
3121
		 * @param string $module Module slug.
3122
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3123
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3124
		 */
3125
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3126
3127
		$jetpack = self::init();
3128
3129
		if ( ! strlen( $module ) ) {
3130
			return false;
3131
		}
3132
3133
		if ( ! self::is_module( $module ) ) {
3134
			return false;
3135
		}
3136
3137
		// If it's already active, then don't do it again
3138
		$active = self::get_active_modules();
3139
		foreach ( $active as $act ) {
3140
			if ( $act == $module ) {
3141
				return true;
3142
			}
3143
		}
3144
3145
		$module_data = self::get_module( $module );
3146
3147
		$is_offline_mode = ( new Status() )->is_offline_mode();
3148
		if ( ! self::is_connection_ready() ) {
3149
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3150
				return false;
3151
			}
3152
3153
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3154
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3155
				return false;
3156
			}
3157
		}
3158
3159
		// Check and see if the old plugin is active
3160
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3161
			// Deactivate the old plugin
3162
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3163
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3164
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3165
				self::state( 'deactivated_plugins', $module );
3166
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3167
				exit;
3168
			}
3169
		}
3170
3171
		// Protect won't work with mis-configured IPs
3172
		if ( 'protect' === $module ) {
3173
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3174
			if ( ! jetpack_protect_get_ip() ) {
3175
				self::state( 'message', 'protect_misconfigured_ip' );
3176
				return false;
3177
			}
3178
		}
3179
3180
		if ( ! Jetpack_Plan::supports( $module ) ) {
3181
			return false;
3182
		}
3183
3184
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3185
		self::state( 'module', $module );
3186
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3187
3188
		self::catch_errors( true );
3189
		ob_start();
3190
		require self::get_module_path( $module );
3191
		/** This action is documented in class.jetpack.php */
3192
		do_action( 'jetpack_activate_module', $module );
3193
		$active[] = $module;
3194
		self::update_active_modules( $active );
3195
3196
		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...
3197
		ob_end_clean();
3198
		self::catch_errors( false );
3199
3200
		if ( $redirect ) {
3201
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3202
		}
3203
		if ( $exit ) {
3204
			exit;
3205
		}
3206
		return true;
3207
	}
3208
3209
	function activate_module_actions( $module ) {
3210
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3211
	}
3212
3213
	public static function deactivate_module( $module ) {
3214
		/**
3215
		 * Fires when a module is deactivated.
3216
		 *
3217
		 * @since 1.9.0
3218
		 *
3219
		 * @param string $module Module slug.
3220
		 */
3221
		do_action( 'jetpack_pre_deactivate_module', $module );
3222
3223
		$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...
3224
3225
		$active = self::get_active_modules();
3226
		$new    = array_filter( array_diff( $active, (array) $module ) );
3227
3228
		return self::update_active_modules( $new );
3229
	}
3230
3231
	public static function enable_module_configurable( $module ) {
3232
		$module = self::get_module_slug( $module );
3233
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3234
	}
3235
3236
	/**
3237
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3238
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3239
	 *
3240
	 * @param string $module Module slug
3241
	 * @return string $url module configuration URL
3242
	 */
3243
	public static function module_configuration_url( $module ) {
3244
		$module      = self::get_module_slug( $module );
3245
		$default_url = self::admin_url() . "#/settings?term=$module";
3246
		/**
3247
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3248
		 *
3249
		 * @since 6.9.0
3250
		 *
3251
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3252
		 */
3253
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3254
3255
		return $url;
3256
	}
3257
3258
	/* Installation */
3259
	public static function bail_on_activation( $message, $deactivate = true ) {
3260
		?>
3261
<!doctype html>
3262
<html>
3263
<head>
3264
<meta charset="<?php bloginfo( 'charset' ); ?>">
3265
<style>
3266
* {
3267
	text-align: center;
3268
	margin: 0;
3269
	padding: 0;
3270
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3271
}
3272
p {
3273
	margin-top: 1em;
3274
	font-size: 18px;
3275
}
3276
</style>
3277
<body>
3278
<p><?php echo esc_html( $message ); ?></p>
3279
</body>
3280
</html>
3281
		<?php
3282
		if ( $deactivate ) {
3283
			$plugins = get_option( 'active_plugins' );
3284
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3285
			$update  = false;
3286
			foreach ( $plugins as $i => $plugin ) {
3287
				if ( $plugin === $jetpack ) {
3288
					$plugins[ $i ] = false;
3289
					$update        = true;
3290
				}
3291
			}
3292
3293
			if ( $update ) {
3294
				update_option( 'active_plugins', array_filter( $plugins ) );
3295
			}
3296
		}
3297
		exit;
3298
	}
3299
3300
	/**
3301
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3302
	 *
3303
	 * @static
3304
	 */
3305
	public static function plugin_activation( $network_wide ) {
3306
		Jetpack_Options::update_option( 'activated', 1 );
3307
3308
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3309
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3310
		}
3311
3312
		if ( $network_wide ) {
3313
			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...
3314
		}
3315
3316
		// For firing one-off events (notices) immediately after activation
3317
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3318
3319
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3320
3321
		Health::on_jetpack_activated();
3322
3323
		self::plugin_initialize();
3324
	}
3325
3326
	public static function get_activation_source( $referer_url ) {
3327
3328
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3329
			return array( 'wp-cli', null );
3330
		}
3331
3332
		$referer = wp_parse_url( $referer_url );
3333
3334
		$source_type  = 'unknown';
3335
		$source_query = null;
3336
3337
		if ( ! is_array( $referer ) ) {
3338
			return array( $source_type, $source_query );
3339
		}
3340
3341
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3342
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3343
3344
		if ( isset( $referer['query'] ) ) {
3345
			parse_str( $referer['query'], $query_parts );
3346
		} else {
3347
			$query_parts = array();
3348
		}
3349
3350
		if ( $plugins_path === $referer['path'] ) {
3351
			$source_type = 'list';
3352
		} elseif ( $plugins_install_path === $referer['path'] ) {
3353
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3354
			switch ( $tab ) {
3355
				case 'popular':
3356
					$source_type = 'popular';
3357
					break;
3358
				case 'recommended':
3359
					$source_type = 'recommended';
3360
					break;
3361
				case 'favorites':
3362
					$source_type = 'favorites';
3363
					break;
3364
				case 'search':
3365
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3366
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3367
					break;
3368
				default:
3369
					$source_type = 'featured';
3370
			}
3371
		}
3372
3373
		return array( $source_type, $source_query );
3374
	}
3375
3376
	/**
3377
	 * Runs before bumping version numbers up to a new version
3378
	 *
3379
	 * @param string $version    Version:timestamp.
3380
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3381
	 */
3382
	public static function do_version_bump( $version, $old_version ) {
3383
		if ( $old_version ) { // For existing Jetpack installations.
3384
3385
			// If a front end page is visited after the update, the 'wp' action will fire.
3386
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3387
3388
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3389
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3390
		}
3391
	}
3392
3393
	/**
3394
	 * Sets the display_update_modal state.
3395
	 */
3396
	public static function set_update_modal_display() {
3397
		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...
3398
	}
3399
3400
	/**
3401
	 * Sets the internal version number and activation state.
3402
	 *
3403
	 * @static
3404
	 */
3405
	public static function plugin_initialize() {
3406
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3407
			Jetpack_Options::update_option( 'activated', 2 );
3408
		}
3409
3410 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3411
			$version = $old_version = JETPACK__VERSION . ':' . time();
3412
			/** This action is documented in class.jetpack.php */
3413
			do_action( 'updating_jetpack_version', $version, false );
3414
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3415
		}
3416
3417
		self::load_modules();
3418
3419
		Jetpack_Options::delete_option( 'do_activate' );
3420
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3421
	}
3422
3423
	/**
3424
	 * Removes all connection options
3425
	 *
3426
	 * @static
3427
	 */
3428
	public static function plugin_deactivation() {
3429
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3430
		$tracking = new Tracking();
3431
		$tracking->record_user_event( 'deactivate_plugin', array() );
3432
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3433
			Jetpack_Network::init()->deactivate();
3434
		} else {
3435
			self::disconnect( false );
3436
			// Jetpack_Heartbeat::init()->deactivate();
3437
		}
3438
	}
3439
3440
	/**
3441
	 * Disconnects from the Jetpack servers.
3442
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3443
	 *
3444
	 * @static
3445
	 */
3446
	public static function disconnect( $update_activated_state = true ) {
3447
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3448
3449
		$connection = self::connection();
3450
3451
		( new Nonce_Handler() )->clean_all();
3452
3453
		// If the site is in an IDC because sync is not allowed,
3454
		// let's make sure to not disconnect the production site.
3455
		if ( ! self::validate_sync_error_idc_option() ) {
3456
			$tracking = new Tracking();
3457
			$tracking->record_user_event( 'disconnect_site', array() );
3458
3459
			$connection->disconnect_site_wpcom( true );
3460
		}
3461
3462
		$connection->delete_all_connection_tokens( true );
3463
		Jetpack_IDC::clear_all_idc_options();
3464
3465
		if ( $update_activated_state ) {
3466
			Jetpack_Options::update_option( 'activated', 4 );
3467
		}
3468
3469
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3470
			// Check then record unique disconnection if site has never been disconnected previously
3471
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3472
				$jetpack_unique_connection['disconnected'] = 1;
3473
			} else {
3474
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3475
					// track unique disconnect
3476
					$jetpack = self::init();
3477
3478
					$jetpack->stat( 'connections', 'unique-disconnect' );
3479
					$jetpack->do_stats( 'server_side' );
3480
				}
3481
				// increment number of times disconnected
3482
				$jetpack_unique_connection['disconnected'] += 1;
3483
			}
3484
3485
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3486
		}
3487
3488
		// Delete all the sync related data. Since it could be taking up space.
3489
		Sender::get_instance()->uninstall();
3490
3491
	}
3492
3493
	/**
3494
	 * Disconnects the user
3495
	 *
3496
	 * @param int $user_id The user ID to disconnect.
3497
	 */
3498
	public function disconnect_user( $user_id ) {
3499
		$this->connection_manager->disconnect_user( $user_id );
3500
	}
3501
3502
	/**
3503
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3504
	 *
3505
	 * @deprecated since Jetpack 9.7.0
3506
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
3507
	 *
3508
	 * @return bool|WP_Error
3509
	 */
3510
	public static function try_registration() {
3511
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
3512
		return static::connection()->try_registration();
3513
	}
3514
3515
	/**
3516
	 * Checking the domain names in beta versions.
3517
	 * If this is a development version, before attempting to connect, let's make sure that the domains are viable.
3518
	 *
3519
	 * @param null|\WP_Error $error The domain validation error, or `null` if everything's fine.
3520
	 *
3521
	 * @return null|\WP_Error The domain validation error, or `null` if everything's fine.
3522
	 */
3523
	public static function registration_check_domains( $error ) {
3524
		if ( static::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3525
			$domains_to_check = array_unique(
3526
				array(
3527
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3528
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3529
				)
3530
			);
3531
			foreach ( $domains_to_check as $domain ) {
3532
				$result = static::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3531 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...
3533
				if ( is_wp_error( $result ) ) {
3534
					return $result;
3535
				}
3536
			}
3537
		}
3538
3539
		return $error;
3540
	}
3541
3542
	/**
3543
	 * Tracking an internal event log. Try not to put too much chaff in here.
3544
	 *
3545
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3546
	 */
3547
	public static function log( $code, $data = null ) {
3548
		// only grab the latest 200 entries
3549
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3550
3551
		// Append our event to the log
3552
		$log_entry = array(
3553
			'time'    => time(),
3554
			'user_id' => get_current_user_id(),
3555
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3556
			'code'    => $code,
3557
		);
3558
		// Don't bother storing it unless we've got some.
3559
		if ( ! is_null( $data ) ) {
3560
			$log_entry['data'] = $data;
3561
		}
3562
		$log[] = $log_entry;
3563
3564
		// Try add_option first, to make sure it's not autoloaded.
3565
		// @todo: Add an add_option method to Jetpack_Options
3566
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3567
			Jetpack_Options::update_option( 'log', $log );
3568
		}
3569
3570
		/**
3571
		 * Fires when Jetpack logs an internal event.
3572
		 *
3573
		 * @since 3.0.0
3574
		 *
3575
		 * @param array $log_entry {
3576
		 *  Array of details about the log entry.
3577
		 *
3578
		 *  @param string time Time of the event.
3579
		 *  @param int user_id ID of the user who trigerred the event.
3580
		 *  @param int blog_id Jetpack Blog ID.
3581
		 *  @param string code Unique name for the event.
3582
		 *  @param string data Data about the event.
3583
		 * }
3584
		 */
3585
		do_action( 'jetpack_log_entry', $log_entry );
3586
	}
3587
3588
	/**
3589
	 * Get the internal event log.
3590
	 *
3591
	 * @param $event (string) - only return the specific log events
3592
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3593
	 *
3594
	 * @return array of log events || WP_Error for invalid params
3595
	 */
3596
	public static function get_log( $event = false, $num = false ) {
3597
		if ( $event && ! is_string( $event ) ) {
3598
			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...
3599
		}
3600
3601
		if ( $num && ! is_numeric( $num ) ) {
3602
			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...
3603
		}
3604
3605
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3606
3607
		// If nothing set - act as it did before, otherwise let's start customizing the output
3608
		if ( ! $num && ! $event ) {
3609
			return $entire_log;
3610
		} else {
3611
			$entire_log = array_reverse( $entire_log );
3612
		}
3613
3614
		$custom_log_output = array();
3615
3616
		if ( $event ) {
3617
			foreach ( $entire_log as $log_event ) {
3618
				if ( $event == $log_event['code'] ) {
3619
					$custom_log_output[] = $log_event;
3620
				}
3621
			}
3622
		} else {
3623
			$custom_log_output = $entire_log;
3624
		}
3625
3626
		if ( $num ) {
3627
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3628
		}
3629
3630
		return $custom_log_output;
3631
	}
3632
3633
	/**
3634
	 * Log modification of important settings.
3635
	 */
3636
	public static function log_settings_change( $option, $old_value, $value ) {
3637
		switch ( $option ) {
3638
			case 'jetpack_sync_non_public_post_stati':
3639
				self::log( $option, $value );
3640
				break;
3641
		}
3642
	}
3643
3644
	/**
3645
	 * Return stat data for WPCOM sync
3646
	 */
3647
	public static function get_stat_data( $encode = true, $extended = true ) {
3648
		$data = Jetpack_Heartbeat::generate_stats_array();
3649
3650
		if ( $extended ) {
3651
			$additional_data = self::get_additional_stat_data();
3652
			$data            = array_merge( $data, $additional_data );
3653
		}
3654
3655
		if ( $encode ) {
3656
			return json_encode( $data );
3657
		}
3658
3659
		return $data;
3660
	}
3661
3662
	/**
3663
	 * Get additional stat data to sync to WPCOM
3664
	 */
3665
	public static function get_additional_stat_data( $prefix = '' ) {
3666
		$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...
3667
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3668
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3669
		$return[ "{$prefix}site-count" ]    = 0;
3670
3671
		if ( function_exists( 'get_blog_count' ) ) {
3672
			$return[ "{$prefix}site-count" ] = get_blog_count();
3673
		}
3674
		return $return;
3675
	}
3676
3677
	private static function get_site_user_count() {
3678
		global $wpdb;
3679
3680
		if ( function_exists( 'wp_is_large_network' ) ) {
3681
			if ( wp_is_large_network( 'users' ) ) {
3682
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3683
			}
3684
		}
3685
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3686
			// It wasn't there, so regenerate the data and save the transient
3687
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3688
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3689
		}
3690
		return $user_count;
3691
	}
3692
3693
	/* Admin Pages */
3694
3695
	function admin_init() {
3696
		// If the plugin is not connected, display a connect message.
3697
		if (
3698
			// the plugin was auto-activated and needs its candy
3699
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3700
		||
3701
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3702
			! Jetpack_Options::get_option( 'activated' )
3703
		) {
3704
			self::plugin_initialize();
3705
		}
3706
3707
		$is_offline_mode = ( new Status() )->is_offline_mode();
3708
		if ( ! self::is_connection_ready() && ! $is_offline_mode ) {
3709
			Jetpack_Connection_Banner::init();
3710
			/** Already documented in automattic/jetpack-connection::src/class-client.php */
3711
		} elseif ( ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) && ! apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
3712
			// Upgrade: 1.1 -> 1.1.1
3713
			// Check and see if host can verify the Jetpack servers' SSL certificate
3714
			$args = array();
3715
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3716
		}
3717
3718
		Jetpack_Recommendations_Banner::init();
3719
3720
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3721
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3722
		}
3723
3724
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3725
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3726
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3727
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3728
3729
		if ( self::is_connection_ready() || $is_offline_mode ) {
3730
			// Artificially throw errors in certain specific cases during plugin activation.
3731
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3732
		}
3733
3734
		// Add custom column in wp-admin/users.php to show whether user is linked.
3735
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3736
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3737
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3738
	}
3739
3740
	function admin_body_class( $admin_body_class = '' ) {
3741
		$classes = explode( ' ', trim( $admin_body_class ) );
3742
3743
		$classes[] = self::is_connection_ready() ? 'jetpack-connected' : 'jetpack-disconnected';
3744
3745
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3746
		return " $admin_body_class ";
3747
	}
3748
3749
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3750
		return $admin_body_class . ' jetpack-pagestyles ';
3751
	}
3752
3753
	/**
3754
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3755
	 * This function artificially throws errors for such cases (per a specific list).
3756
	 *
3757
	 * @param string $plugin The activated plugin.
3758
	 */
3759
	function throw_error_on_activate_plugin( $plugin ) {
3760
		$active_modules = self::get_active_modules();
3761
3762
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3763
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3764
			$throw = false;
3765
3766
			// Try and make sure it really was the stats plugin
3767
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3768
				if ( 'stats.php' == basename( $plugin ) ) {
3769
					$throw = true;
3770
				}
3771
			} else {
3772
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3773
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3774
					$throw = true;
3775
				}
3776
			}
3777
3778
			if ( $throw ) {
3779
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3780
			}
3781
		}
3782
	}
3783
3784
	function intercept_plugin_error_scrape_init() {
3785
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3786
	}
3787
3788
	function intercept_plugin_error_scrape( $action, $result ) {
3789
		if ( ! $result ) {
3790
			return;
3791
		}
3792
3793
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3794
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3795
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3796
			}
3797
		}
3798
	}
3799
3800
	/**
3801
	 * Register the remote file upload request handlers, if needed.
3802
	 *
3803
	 * @access public
3804
	 */
3805
	public function add_remote_request_handlers() {
3806
		// Remote file uploads are allowed only via AJAX requests.
3807
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3808
			return;
3809
		}
3810
3811
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3812
		$remote_request_actions = array(
3813
			'jetpack_upload_file',
3814
			'jetpack_update_file',
3815
		);
3816
3817
		// phpcs:ignore WordPress.Security.NonceVerification
3818
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3819
			return;
3820
		}
3821
3822
		// Require Jetpack authentication for the remote file upload AJAX requests.
3823
		if ( ! $this->connection_manager ) {
3824
			$this->connection_manager = new Connection_Manager();
3825
		}
3826
3827
		$this->connection_manager->require_jetpack_authentication();
3828
3829
		// Register the remote file upload AJAX handlers.
3830
		foreach ( $remote_request_actions as $action ) {
3831
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3832
		}
3833
	}
3834
3835
	/**
3836
	 * Handler for Jetpack remote file uploads.
3837
	 *
3838
	 * @access public
3839
	 */
3840
	public function remote_request_handlers() {
3841
		$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...
3842
3843
		switch ( current_filter() ) {
3844
			case 'wp_ajax_nopriv_jetpack_upload_file':
3845
				$response = $this->upload_handler();
3846
				break;
3847
3848
			case 'wp_ajax_nopriv_jetpack_update_file':
3849
				$response = $this->upload_handler( true );
3850
				break;
3851
			default:
3852
				$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...
3853
				break;
3854
		}
3855
3856
		if ( ! $response ) {
3857
			$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...
3858
		}
3859
3860
		if ( is_wp_error( $response ) ) {
3861
			$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...
3862
			$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...
3863
			$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...
3864
3865
			if ( ! is_int( $status_code ) ) {
3866
				$status_code = 400;
3867
			}
3868
3869
			status_header( $status_code );
3870
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3871
		}
3872
3873
		status_header( 200 );
3874
		if ( true === $response ) {
3875
			exit;
3876
		}
3877
3878
		die( json_encode( (object) $response ) );
3879
	}
3880
3881
	/**
3882
	 * Uploads a file gotten from the global $_FILES.
3883
	 * If `$update_media_item` is true and `post_id` is defined
3884
	 * the attachment file of the media item (gotten through of the post_id)
3885
	 * will be updated instead of add a new one.
3886
	 *
3887
	 * @param  boolean $update_media_item - update media attachment
3888
	 * @return array - An array describing the uploadind files process
3889
	 */
3890
	function upload_handler( $update_media_item = false ) {
3891
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3892
			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...
3893
		}
3894
3895
		$user = wp_authenticate( '', '' );
3896
		if ( ! $user || is_wp_error( $user ) ) {
3897
			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...
3898
		}
3899
3900
		wp_set_current_user( $user->ID );
3901
3902
		if ( ! current_user_can( 'upload_files' ) ) {
3903
			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...
3904
		}
3905
3906
		if ( empty( $_FILES ) ) {
3907
			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...
3908
		}
3909
3910
		foreach ( array_keys( $_FILES ) as $files_key ) {
3911
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3912
				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...
3913
			}
3914
		}
3915
3916
		$media_keys = array_keys( $_FILES['media'] );
3917
3918
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3919
		if ( ! $token || is_wp_error( $token ) ) {
3920
			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...
3921
		}
3922
3923
		$uploaded_files = array();
3924
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3925
		unset( $GLOBALS['post'] );
3926
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3927
			$file = array();
3928
			foreach ( $media_keys as $media_key ) {
3929
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3930
			}
3931
3932
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3933
3934
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3935
			if ( $hmac_provided !== $hmac_file ) {
3936
				$uploaded_files[ $index ] = (object) array(
3937
					'error'             => 'invalid_hmac',
3938
					'error_description' => 'The corresponding HMAC for this file does not match',
3939
				);
3940
				continue;
3941
			}
3942
3943
			$_FILES['.jetpack.upload.'] = $file;
3944
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3945
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3946
				$post_id = 0;
3947
			}
3948
3949
			if ( $update_media_item ) {
3950
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3951
					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...
3952
				}
3953
3954
				$media_array = $_FILES['media'];
3955
3956
				$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...
3957
				$file_array['type']     = $media_array['type'][0];
3958
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3959
				$file_array['error']    = $media_array['error'][0];
3960
				$file_array['size']     = $media_array['size'][0];
3961
3962
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3963
3964
				if ( is_wp_error( $edited_media_item ) ) {
3965
					return $edited_media_item;
3966
				}
3967
3968
				$response = (object) array(
3969
					'id'   => (string) $post_id,
3970
					'file' => (string) $edited_media_item->post_title,
3971
					'url'  => (string) wp_get_attachment_url( $post_id ),
3972
					'type' => (string) $edited_media_item->post_mime_type,
3973
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3974
				);
3975
3976
				return (array) array( $response );
3977
			}
3978
3979
			$attachment_id = media_handle_upload(
3980
				'.jetpack.upload.',
3981
				$post_id,
3982
				array(),
3983
				array(
3984
					'action' => 'jetpack_upload_file',
3985
				)
3986
			);
3987
3988
			if ( ! $attachment_id ) {
3989
				$uploaded_files[ $index ] = (object) array(
3990
					'error'             => 'unknown',
3991
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3992
				);
3993
			} elseif ( is_wp_error( $attachment_id ) ) {
3994
				$uploaded_files[ $index ] = (object) array(
3995
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3996
					'error_description' => $attachment_id->get_error_message(),
3997
				);
3998
			} else {
3999
				$attachment               = get_post( $attachment_id );
4000
				$uploaded_files[ $index ] = (object) array(
4001
					'id'   => (string) $attachment_id,
4002
					'file' => $attachment->post_title,
4003
					'url'  => wp_get_attachment_url( $attachment_id ),
4004
					'type' => $attachment->post_mime_type,
4005
					'meta' => wp_get_attachment_metadata( $attachment_id ),
4006
				);
4007
				// Zip files uploads are not supported unless they are done for installation purposed
4008
				// lets delete them in case something goes wrong in this whole process
4009
				if ( 'application/zip' === $attachment->post_mime_type ) {
4010
					// Schedule a cleanup for 2 hours from now in case of failed install.
4011
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
4012
				}
4013
			}
4014
		}
4015
		if ( ! is_null( $global_post ) ) {
4016
			$GLOBALS['post'] = $global_post;
4017
		}
4018
4019
		return $uploaded_files;
4020
	}
4021
4022
	/**
4023
	 * Add help to the Jetpack page
4024
	 *
4025
	 * @since Jetpack (1.2.3)
4026
	 * @return false if not the Jetpack page
4027
	 */
4028
	function admin_help() {
4029
		$current_screen = get_current_screen();
4030
4031
		// Overview
4032
		$current_screen->add_help_tab(
4033
			array(
4034
				'id'      => 'home',
4035
				'title'   => __( 'Home', 'jetpack' ),
4036
				'content' =>
4037
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4038
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4039
					'<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>',
4040
			)
4041
		);
4042
4043
		// Screen Content
4044
		if ( current_user_can( 'manage_options' ) ) {
4045
			$current_screen->add_help_tab(
4046
				array(
4047
					'id'      => 'settings',
4048
					'title'   => __( 'Settings', 'jetpack' ),
4049
					'content' =>
4050
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4051
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4052
						'<ol>' .
4053
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4054
							'<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>' .
4055
						'</ol>' .
4056
						'<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>',
4057
				)
4058
			);
4059
		}
4060
4061
		// Help Sidebar
4062
		$support_url = Redirect::get_url( 'jetpack-support' );
4063
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4064
		$current_screen->set_help_sidebar(
4065
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4066
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4067
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4068
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4069
		);
4070
	}
4071
4072
	function admin_menu_css() {
4073
		wp_enqueue_style( 'jetpack-icons' );
4074
	}
4075
4076
	function admin_menu_order() {
4077
		return true;
4078
	}
4079
4080
	function jetpack_menu_order( $menu_order ) {
4081
		$jp_menu_order = array();
4082
4083
		foreach ( $menu_order as $index => $item ) {
4084
			if ( $item != 'jetpack' ) {
4085
				$jp_menu_order[] = $item;
4086
			}
4087
4088
			if ( $index == 0 ) {
4089
				$jp_menu_order[] = 'jetpack';
4090
			}
4091
		}
4092
4093
		return $jp_menu_order;
4094
	}
4095
4096
	function admin_banner_styles() {
4097
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4098
4099 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4100
			wp_register_style(
4101
				'jetpack-dops-style',
4102
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4103
				array(),
4104
				JETPACK__VERSION
4105
			);
4106
		}
4107
4108
		wp_enqueue_style(
4109
			'jetpack',
4110
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4111
			array( 'jetpack-dops-style' ),
4112
			JETPACK__VERSION . '-20121016'
4113
		);
4114
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4115
		wp_style_add_data( 'jetpack', 'suffix', $min );
4116
	}
4117
4118
	function plugin_action_links( $actions ) {
4119
4120
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4121
4122
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
4123
			return array_merge(
4124
				$jetpack_home,
4125
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4126
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4127
				$actions
4128
			);
4129
		}
4130
4131
		return array_merge( $jetpack_home, $actions );
4132
	}
4133
4134
	/**
4135
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4136
	 *
4137
	 * @param string $hook The current admin page.
4138
	 *
4139
	 * @return void
4140
	 */
4141
	public function deactivate_dialog( $hook ) {
4142
		if (
4143
			'plugins.php' === $hook
4144
			&& self::is_connection_ready()
4145
		) {
4146
4147
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4148
4149
			if ( count( $active_plugins_using_connection ) > 1 ) {
4150
4151
				add_thickbox();
4152
4153
				wp_register_script(
4154
					'jp-tracks',
4155
					'//stats.wp.com/w.js',
4156
					array(),
4157
					gmdate( 'YW' ),
4158
					true
4159
				);
4160
4161
				wp_register_script(
4162
					'jp-tracks-functions',
4163
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4164
					array( 'jp-tracks' ),
4165
					JETPACK__VERSION,
4166
					false
4167
				);
4168
4169
				wp_enqueue_script(
4170
					'jetpack-deactivate-dialog-js',
4171
					Assets::get_file_url_for_environment(
4172
						'_inc/build/jetpack-deactivate-dialog.min.js',
4173
						'_inc/jetpack-deactivate-dialog.js'
4174
					),
4175
					array( 'jquery', 'jp-tracks-functions' ),
4176
					JETPACK__VERSION,
4177
					true
4178
				);
4179
4180
				wp_localize_script(
4181
					'jetpack-deactivate-dialog-js',
4182
					'deactivate_dialog',
4183
					array(
4184
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4185
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4186
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4187
					)
4188
				);
4189
4190
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4191
4192
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4193
			}
4194
		}
4195
	}
4196
4197
	/**
4198
	 * Outputs the content of the deactivation modal
4199
	 *
4200
	 * @return void
4201
	 */
4202
	public function deactivate_dialog_content() {
4203
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4204
		unset( $active_plugins_using_connection['jetpack'] );
4205
		$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 4203 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...
4206
	}
4207
4208
	/**
4209
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4210
	 *
4211
	 * @param string $login_url The wp-login URL.
4212
	 * @param string $redirect  URL to redirect users after logging in.
4213
	 * @since Jetpack 8.4
4214
	 * @return string
4215
	 */
4216
	public function login_url( $login_url, $redirect ) {
4217
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4218
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4219
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4220
		}
4221
		return $login_url;
4222
	}
4223
4224
	/**
4225
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4226
	 *
4227
	 * @since Jetpack 8.4
4228
	 */
4229
	public function login_init() {
4230
		// phpcs:ignore WordPress.Security.NonceVerification
4231
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4232
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4233
			wp_safe_redirect(
4234
				add_query_arg(
4235
					array(
4236
						'forceInstall' => 1,
4237
						'url'          => rawurlencode( get_site_url() ),
4238
					),
4239
					// @todo provide way to go to specific calypso env.
4240
					self::get_calypso_host() . 'jetpack/connect'
4241
				)
4242
			);
4243
			exit;
4244
		}
4245
	}
4246
4247
	/*
4248
	 * Registration flow:
4249
	 * 1 - ::admin_page_load() action=register
4250
	 * 2 - ::try_registration()
4251
	 * 3 - ::register()
4252
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4253
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4254
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4255
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4256
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4257
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4258
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4259
	 *       jetpack_id, jetpack_secret, jetpack_public
4260
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4261
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4262
	 * 5 - user logs in with WP.com account
4263
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4264
	 *		- Manager::authorize()
4265
	 *		- Manager::get_token()
4266
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4267
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4268
	 *			- which responds with access_token, token_type, scope
4269
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4270
	 *		- Jetpack::activate_default_modules()
4271
	 *     		- Deactivates deprecated plugins
4272
	 *     		- Activates all default modules
4273
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4274
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4275
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4276
	 *     Done!
4277
	 */
4278
4279
	/**
4280
	 * Handles the page load events for the Jetpack admin page
4281
	 */
4282
	function admin_page_load() {
4283
		$error = false;
4284
4285
		// Make sure we have the right body class to hook stylings for subpages off of.
4286
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4287
4288
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4289
			// Should only be used in intermediate redirects to preserve state across redirects
4290
			self::restate();
4291
		}
4292
4293
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4294
			// @todo: Add validation against a known allowed list.
4295
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4296
			// User clicked in the iframe to link their accounts
4297
			if ( ! self::connection()->is_user_connected() ) {
4298
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4299
4300
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4301
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4302
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4303
4304
				if ( isset( $_GET['notes_iframe'] ) ) {
4305
					$connect_url .= '&notes_iframe';
4306
				}
4307
				wp_redirect( $connect_url );
4308
				exit;
4309
			} else {
4310
				if ( ! isset( $_GET['calypso_env'] ) ) {
4311
					self::state( 'message', 'already_authorized' );
4312
					wp_safe_redirect( self::admin_url() );
4313
					exit;
4314
				} else {
4315
					$connect_url  = $this->build_connect_url( true, false, $from );
4316
					$connect_url .= '&already_authorized=true';
4317
					wp_redirect( $connect_url );
4318
					exit;
4319
				}
4320
			}
4321
		}
4322
4323
		if ( isset( $_GET['action'] ) ) {
4324
			switch ( $_GET['action'] ) {
4325
				case 'authorize_redirect':
4326
					self::log( 'authorize_redirect' );
4327
4328
					add_filter(
4329
						'allowed_redirect_hosts',
4330
						function ( $domains ) {
4331
							$domains[] = 'jetpack.com';
4332
							$domains[] = 'jetpack.wordpress.com';
4333
							$domains[] = 'wordpress.com';
4334
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4335
							return array_unique( $domains );
4336
						}
4337
					);
4338
4339
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4340
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4341
4342
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4343
						// The destination URL is missing or invalid, nothing to do here.
4344
						exit;
4345
					}
4346
4347
					if ( static::connection()->is_connected() && static::connection()->is_user_connected() ) {
4348
						// The user is either already connected, or finished the connection process.
4349
						wp_safe_redirect( $dest_url );
4350
						exit;
4351
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4352
						// The user decided not to proceed with setting up the connection.
4353
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4354
						exit;
4355
					}
4356
4357
					$redirect_url = self::admin_url(
4358
						array(
4359
							'page'     => 'jetpack',
4360
							'action'   => 'authorize_redirect',
4361
							'dest_url' => rawurlencode( $dest_url ),
4362
							'done'     => '1',
4363
						)
4364
					);
4365
4366
					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...
4367
					exit;
4368
				case 'authorize':
4369
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4370
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4371
					exit;
4372
				case 'register':
4373
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4374
						$error = 'cheatin';
4375
						break;
4376
					}
4377
					check_admin_referer( 'jetpack-register' );
4378
					self::log( 'register' );
4379
					self::maybe_set_version_option();
4380
					$registered = static::connection()->try_registration();
4381
					if ( is_wp_error( $registered ) ) {
4382
						$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...
4383
						self::state( 'error', $error );
4384
						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...
4385
4386
						/**
4387
						 * Jetpack registration Error.
4388
						 *
4389
						 * @since 7.5.0
4390
						 *
4391
						 * @param string|int $error The error code.
4392
						 * @param \WP_Error $registered The error object.
4393
						 */
4394
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4395
						break;
4396
					}
4397
4398
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4399
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4400
4401
					/**
4402
					 * Jetpack registration Success.
4403
					 *
4404
					 * @since 7.5.0
4405
					 *
4406
					 * @param string $from 'from' GET parameter;
4407
					 */
4408
					do_action( 'jetpack_connection_register_success', $from );
4409
4410
					$url = $this->build_connect_url( true, $redirect, $from );
4411
4412
					if ( ! empty( $_GET['onboarding'] ) ) {
4413
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4414
					}
4415
4416
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4417
						$url = add_query_arg( 'auth_approved', 'true', $url );
4418
					}
4419
4420
					wp_redirect( $url );
4421
					exit;
4422
				case 'activate':
4423
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4424
						$error = 'cheatin';
4425
						break;
4426
					}
4427
4428
					$module = stripslashes( $_GET['module'] );
4429
					check_admin_referer( "jetpack_activate-$module" );
4430
					self::log( 'activate', $module );
4431
					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...
4432
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4433
					}
4434
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4435
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4436
					exit;
4437
				case 'activate_default_modules':
4438
					check_admin_referer( 'activate_default_modules' );
4439
					self::log( 'activate_default_modules' );
4440
					self::restate();
4441
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4442
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4443
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4444
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4445
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4446
					exit;
4447 View Code Duplication
				case 'disconnect':
4448
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4449
						$error = 'cheatin';
4450
						break;
4451
					}
4452
4453
					check_admin_referer( 'jetpack-disconnect' );
4454
					self::log( 'disconnect' );
4455
					self::disconnect();
4456
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4457
					exit;
4458 View Code Duplication
				case 'reconnect':
4459
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4460
						$error = 'cheatin';
4461
						break;
4462
					}
4463
4464
					check_admin_referer( 'jetpack-reconnect' );
4465
					self::log( 'reconnect' );
4466
					self::disconnect();
4467
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4468
					exit;
4469 View Code Duplication
				case 'deactivate':
4470
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4471
						$error = 'cheatin';
4472
						break;
4473
					}
4474
4475
					$modules = stripslashes( $_GET['module'] );
4476
					check_admin_referer( "jetpack_deactivate-$modules" );
4477
					foreach ( explode( ',', $modules ) as $module ) {
4478
						self::log( 'deactivate', $module );
4479
						self::deactivate_module( $module );
4480
						self::state( 'message', 'module_deactivated' );
4481
					}
4482
					self::state( 'module', $modules );
4483
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4484
					exit;
4485
				case 'unlink':
4486
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4487
					check_admin_referer( 'jetpack-unlink' );
4488
					self::log( 'unlink' );
4489
					$this->connection_manager->disconnect_user();
4490
					self::state( 'message', 'unlinked' );
4491
					if ( 'sub-unlink' == $redirect ) {
4492
						wp_safe_redirect( admin_url() );
4493
					} else {
4494
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4495
					}
4496
					exit;
4497
				case 'onboard':
4498
					if ( ! current_user_can( 'manage_options' ) ) {
4499
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4500
					} else {
4501
						self::create_onboarding_token();
4502
						$url = $this->build_connect_url( true );
4503
4504
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4505
							$url = add_query_arg( 'onboarding', $token, $url );
4506
						}
4507
4508
						$calypso_env = $this->get_calypso_env();
4509
						if ( ! empty( $calypso_env ) ) {
4510
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4511
						}
4512
4513
						wp_redirect( $url );
4514
						exit;
4515
					}
4516
					exit;
4517
				default:
4518
					/**
4519
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4520
					 *
4521
					 * @since 2.6.0
4522
					 *
4523
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4524
					 */
4525
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4526
			}
4527
		}
4528
4529
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4530
			self::activate_new_modules( true );
4531
		}
4532
4533
		$message_code = self::state( 'message' );
4534
		if ( self::state( 'optin-manage' ) ) {
4535
			$activated_manage = $message_code;
4536
			$message_code     = 'jetpack-manage';
4537
		}
4538
4539
		switch ( $message_code ) {
4540
			case 'jetpack-manage':
4541
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4542
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4543
				$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>';
4544
				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...
4545
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4546
				}
4547
				break;
4548
4549
		}
4550
4551
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4552
4553
		if ( ! empty( $deactivated_plugins ) ) {
4554
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4555
			$deactivated_titles  = array();
4556
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4557
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4558
					continue;
4559
				}
4560
4561
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4562
			}
4563
4564
			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...
4565
				if ( $this->message ) {
4566
					$this->message .= "<br /><br />\n";
4567
				}
4568
4569
				$this->message .= wp_sprintf(
4570
					_n(
4571
						'Jetpack contains the most recent version of the old %l plugin.',
4572
						'Jetpack contains the most recent versions of the old %l plugins.',
4573
						count( $deactivated_titles ),
4574
						'jetpack'
4575
					),
4576
					$deactivated_titles
4577
				);
4578
4579
				$this->message .= "<br />\n";
4580
4581
				$this->message .= _n(
4582
					'The old version has been deactivated and can be removed from your site.',
4583
					'The old versions have been deactivated and can be removed from your site.',
4584
					count( $deactivated_titles ),
4585
					'jetpack'
4586
				);
4587
			}
4588
		}
4589
4590
		$this->privacy_checks = self::state( 'privacy_checks' );
4591
4592
		if ( $this->message || $this->error || $this->privacy_checks ) {
4593
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4594
		}
4595
4596
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4597
	}
4598
4599
	function admin_notices() {
4600
4601
		if ( $this->error ) {
4602
			?>
4603
<div id="message" class="jetpack-message jetpack-err">
4604
	<div class="squeezer">
4605
		<h2>
4606
			<?php
4607
			echo wp_kses(
4608
				$this->error,
4609
				array(
4610
					'a'      => array( 'href' => array() ),
4611
					'small'  => true,
4612
					'code'   => true,
4613
					'strong' => true,
4614
					'br'     => true,
4615
					'b'      => true,
4616
				)
4617
			);
4618
			?>
4619
			</h2>
4620
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4621
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4622
<?php	endif; ?>
4623
	</div>
4624
</div>
4625
			<?php
4626
		}
4627
4628
		if ( $this->message ) {
4629
			?>
4630
<div id="message" class="jetpack-message">
4631
	<div class="squeezer">
4632
		<h2>
4633
			<?php
4634
			echo wp_kses(
4635
				$this->message,
4636
				array(
4637
					'strong' => array(),
4638
					'a'      => array( 'href' => true ),
4639
					'br'     => true,
4640
				)
4641
			);
4642
			?>
4643
			</h2>
4644
	</div>
4645
</div>
4646
			<?php
4647
		}
4648
4649
		if ( $this->privacy_checks ) :
4650
			$module_names = $module_slugs = array();
4651
4652
			$privacy_checks = explode( ',', $this->privacy_checks );
4653
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4654
			foreach ( $privacy_checks as $module_slug ) {
4655
				$module = self::get_module( $module_slug );
4656
				if ( ! $module ) {
4657
					continue;
4658
				}
4659
4660
				$module_slugs[] = $module_slug;
4661
				$module_names[] = "<strong>{$module['name']}</strong>";
4662
			}
4663
4664
			$module_slugs = join( ',', $module_slugs );
4665
			?>
4666
<div id="message" class="jetpack-message jetpack-err">
4667
	<div class="squeezer">
4668
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4669
		<p>
4670
			<?php
4671
			echo wp_kses(
4672
				wptexturize(
4673
					wp_sprintf(
4674
						_nx(
4675
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4676
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4677
							count( $privacy_checks ),
4678
							'%l = list of Jetpack module/feature names',
4679
							'jetpack'
4680
						),
4681
						$module_names
4682
					)
4683
				),
4684
				array( 'strong' => true )
4685
			);
4686
4687
			echo "\n<br />\n";
4688
4689
			echo wp_kses(
4690
				sprintf(
4691
					_nx(
4692
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4693
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4694
						count( $privacy_checks ),
4695
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4696
						'jetpack'
4697
					),
4698
					wp_nonce_url(
4699
						self::admin_url(
4700
							array(
4701
								'page'   => 'jetpack',
4702
								'action' => 'deactivate',
4703
								'module' => urlencode( $module_slugs ),
4704
							)
4705
						),
4706
						"jetpack_deactivate-$module_slugs"
4707
					),
4708
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4709
				),
4710
				array(
4711
					'a' => array(
4712
						'href'  => true,
4713
						'title' => true,
4714
					),
4715
				)
4716
			);
4717
			?>
4718
		</p>
4719
	</div>
4720
</div>
4721
			<?php
4722
endif;
4723
	}
4724
4725
	/**
4726
	 * We can't always respond to a signed XML-RPC request with a
4727
	 * helpful error message. In some circumstances, doing so could
4728
	 * leak information.
4729
	 *
4730
	 * Instead, track that the error occurred via a Jetpack_Option,
4731
	 * and send that data back in the heartbeat.
4732
	 * All this does is increment a number, but it's enough to find
4733
	 * trends.
4734
	 *
4735
	 * @param WP_Error $xmlrpc_error The error produced during
4736
	 *                               signature validation.
4737
	 */
4738
	function track_xmlrpc_error( $xmlrpc_error ) {
4739
		$code = is_wp_error( $xmlrpc_error )
4740
			? $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...
4741
			: 'should-not-happen';
4742
4743
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4744
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4745
			// No need to update the option if we already have
4746
			// this code stored.
4747
			return;
4748
		}
4749
		$xmlrpc_errors[ $code ] = true;
4750
4751
		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...
4752
	}
4753
4754
	/**
4755
	 * Initialize the jetpack stats instance only when needed
4756
	 *
4757
	 * @return void
4758
	 */
4759
	private function initialize_stats() {
4760
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4761
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4762
		}
4763
	}
4764
4765
	/**
4766
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4767
	 */
4768
	function stat( $group, $detail ) {
4769
		$this->initialize_stats();
4770
		$this->a8c_mc_stats_instance->add( $group, $detail );
4771
4772
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4773
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4774
	}
4775
4776
	/**
4777
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4778
	 */
4779
	function do_stats( $method = '' ) {
4780
		$this->initialize_stats();
4781
		if ( 'server_side' === $method ) {
4782
			$this->a8c_mc_stats_instance->do_server_side_stats();
4783
		} else {
4784
			$this->a8c_mc_stats_instance->do_stats();
4785
		}
4786
4787
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4788
		$this->stats = array();
4789
	}
4790
4791
	/**
4792
	 * Runs stats code for a one-off, server-side.
4793
	 *
4794
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4795
	 *
4796
	 * @return bool If it worked.
4797
	 */
4798
	static function do_server_side_stat( $args ) {
4799
		$url                   = self::build_stats_url( $args );
4800
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4801
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4802
	}
4803
4804
	/**
4805
	 * Builds the stats url.
4806
	 *
4807
	 * @param $args array|string The arguments to append to the URL.
4808
	 *
4809
	 * @return string The URL to be pinged.
4810
	 */
4811
	static function build_stats_url( $args ) {
4812
4813
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4814
		return $a8c_mc_stats_instance->build_stats_url( $args );
4815
4816
	}
4817
4818
	/**
4819
	 * Builds a URL to the Jetpack connection auth page
4820
	 *
4821
	 * @since 3.9.5
4822
	 *
4823
	 * @param bool        $raw If true, URL will not be escaped.
4824
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4825
	 *                              If string, will be a custom redirect.
4826
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4827
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4828
	 *
4829
	 * @return string Connect URL
4830
	 */
4831
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4832
		$site_id    = Jetpack_Options::get_option( 'id' );
4833
		$blog_token = ( new Tokens() )->get_access_token();
4834
4835
		if ( $register || ! $blog_token || ! $site_id ) {
4836
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4837
4838
			if ( ! empty( $redirect ) ) {
4839
				$url = add_query_arg(
4840
					'redirect',
4841
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4842
					$url
4843
				);
4844
			}
4845
4846
			if ( is_network_admin() ) {
4847
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4848
			}
4849
4850
			$calypso_env = self::get_calypso_env();
4851
4852
			if ( ! empty( $calypso_env ) ) {
4853
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4854
			}
4855
		} else {
4856
4857
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4858
			// because otherwise this logic can get us in to a loop.
4859
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4860
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4861
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4862
4863
				$response = Client::wpcom_json_api_request_as_blog(
4864
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4865
					'1.1'
4866
				);
4867
4868
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4869
4870
					// Generating a register URL instead to refresh the existing token
4871
					return $this->build_connect_url( $raw, $redirect, $from, true );
4872
				}
4873
			}
4874
4875
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4831 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...
4876
		}
4877
4878
		if ( $from ) {
4879
			$url = add_query_arg( 'from', $from, $url );
4880
		}
4881
4882
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4883
		/**
4884
		 * Filter the URL used when connecting a user to a WordPress.com account.
4885
		 *
4886
		 * @since 8.1.0
4887
		 *
4888
		 * @param string $url Connection URL.
4889
		 * @param bool   $raw If true, URL will not be escaped.
4890
		 */
4891
		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...
4892
	}
4893
4894
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4895
4896
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4897
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4898
4899
		if ( $iframe ) {
4900
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4901
		}
4902
4903
		$c8n = self::connection();
4904
		$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...
4905
4906
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4907
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4908
4909
		if ( $iframe ) {
4910
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4911
		}
4912
4913
		/**
4914
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4915
		 *
4916
		 * @since 8.9.0
4917
		 *
4918
		 * @param string $url Connection URL.
4919
		 */
4920
		return apply_filters( 'jetpack_build_authorize_url', $url );
4921
	}
4922
4923
	/**
4924
	 * Filters the connection URL parameter array.
4925
	 *
4926
	 * @param array $args default URL parameters used by the package.
4927
	 * @return array the modified URL arguments array.
4928
	 */
4929
	public static function filter_connect_request_body( $args ) {
4930
		if (
4931
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4932
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4933
		) {
4934
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4935
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4936
				? $gp_locale->slug
4937
				: '';
4938
		}
4939
4940
		$tracking        = new Tracking();
4941
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4942
4943
		$args = array_merge(
4944
			$args,
4945
			array(
4946
				'_ui' => $tracks_identity['_ui'],
4947
				'_ut' => $tracks_identity['_ut'],
4948
			)
4949
		);
4950
4951
		$calypso_env = self::get_calypso_env();
4952
4953
		if ( ! empty( $calypso_env ) ) {
4954
			$args['calypso_env'] = $calypso_env;
4955
		}
4956
4957
		return $args;
4958
	}
4959
4960
	/**
4961
	 * Filters the URL that will process the connection data. It can be different from the URL
4962
	 * that we send the user to after everything is done.
4963
	 *
4964
	 * @param String $processing_url the default redirect URL used by the package.
4965
	 * @return String the modified URL.
4966
	 *
4967
	 * @deprecated since Jetpack 9.5.0
4968
	 */
4969
	public static function filter_connect_processing_url( $processing_url ) {
4970
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4971
4972
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4973
		return $processing_url;
4974
	}
4975
4976
	/**
4977
	 * Filters the redirection URL that is used for connect requests. The redirect
4978
	 * URL should return the user back to the Jetpack console.
4979
	 *
4980
	 * @param String $redirect the default redirect URL used by the package.
4981
	 * @return String the modified URL.
4982
	 */
4983
	public static function filter_connect_redirect_url( $redirect ) {
4984
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4985
		$redirect           = $redirect
4986
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4987
			: $jetpack_admin_page;
4988
4989
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4990
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4991
		}
4992
4993
		return $redirect;
4994
	}
4995
4996
	/**
4997
	 * This action fires at the beginning of the Manager::authorize method.
4998
	 */
4999
	public static function authorize_starting() {
5000
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
5001
		// Checking if site has been active/connected previously before recording unique connection.
5002
		if ( ! $jetpack_unique_connection ) {
5003
			// jetpack_unique_connection option has never been set.
5004
			$jetpack_unique_connection = array(
5005
				'connected'    => 0,
5006
				'disconnected' => 0,
5007
				'version'      => '3.6.1',
5008
			);
5009
5010
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
5011
5012
			// Track unique connection.
5013
			$jetpack = self::init();
5014
5015
			$jetpack->stat( 'connections', 'unique-connection' );
5016
			$jetpack->do_stats( 'server_side' );
5017
		}
5018
5019
		// Increment number of times connected.
5020
		$jetpack_unique_connection['connected'] += 1;
5021
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5022
	}
5023
5024
	/**
5025
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5026
	 * linked.
5027
	 */
5028
	public static function authorize_ending_linked() {
5029
		// Don't activate anything since we are just connecting a user.
5030
		self::state( 'message', 'linked' );
5031
	}
5032
5033
	/**
5034
	 * This action fires at the end of the Manager::authorize method when the master user is
5035
	 * authorized.
5036
	 *
5037
	 * @param array $data The request data.
5038
	 */
5039
	public static function authorize_ending_authorized( $data ) {
5040
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5041
		self::invalidate_onboarding_token();
5042
5043
		// If redirect_uri is SSO, ensure SSO module is enabled.
5044
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5045
5046
		/** This filter is documented in class.jetpack-cli.php */
5047
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5048
5049
		$activate_sso = (
5050
			isset( $redirect_options['action'] ) &&
5051
			'jetpack-sso' === $redirect_options['action'] &&
5052
			$jetpack_start_enable_sso
5053
		);
5054
5055
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5056
5057
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5058
	}
5059
5060
	/**
5061
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5062
	 */
5063
	public static function activate_default_modules_on_site_register() {
5064
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5065
		if ( $active_modules ) {
5066
			self::delete_active_modules();
5067
5068
			// 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.
5069
			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...
5070
		} else {
5071
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5072
			self::activate_default_modules( false, false, array(), false, null, null, false );
5073
		}
5074
5075
		// Since this is a fresh connection, be sure to clear out IDC options.
5076
		Jetpack_IDC::clear_all_idc_options();
5077
	}
5078
5079
	/**
5080
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5081
	 * reconnect process is completed.
5082
	 * Note that this currently only happens when we don't need the user to re-authorize
5083
	 * their WP.com account, eg in cases where we are restoring a connection with
5084
	 * unhealthy blog token.
5085
	 */
5086
	public static function reconnection_completed() {
5087
		self::state( 'message', 'reconnection_completed' );
5088
	}
5089
5090
	/**
5091
	 * Get our assumed site creation date.
5092
	 * Calculated based on the earlier date of either:
5093
	 * - Earliest admin user registration date.
5094
	 * - Earliest date of post of any post type.
5095
	 *
5096
	 * @since 7.2.0
5097
	 * @deprecated since 7.8.0
5098
	 *
5099
	 * @return string Assumed site creation date and time.
5100
	 */
5101
	public static function get_assumed_site_creation_date() {
5102
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5103
		return self::connection()->get_assumed_site_creation_date();
5104
	}
5105
5106 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5107
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5108
5109
		if ( $activation_source_name ) {
5110
			$args['_as'] = urlencode( $activation_source_name );
5111
		}
5112
5113
		if ( $activation_source_keyword ) {
5114
			$args['_ak'] = urlencode( $activation_source_keyword );
5115
		}
5116
	}
5117
5118
	function build_reconnect_url( $raw = false ) {
5119
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5120
		return $raw ? $url : esc_url( $url );
5121
	}
5122
5123
	public static function admin_url( $args = null ) {
5124
		$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...
5125
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5126
		return $url;
5127
	}
5128
5129
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5130
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5131
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5132
	}
5133
5134
	function dismiss_jetpack_notice() {
5135
5136
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5137
			return;
5138
		}
5139
5140
		switch ( $_GET['jetpack-notice'] ) {
5141
			case 'dismiss':
5142
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5143
5144
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5145
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5146
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5147
				}
5148
				break;
5149
		}
5150
	}
5151
5152
	public static function sort_modules( $a, $b ) {
5153
		if ( $a['sort'] == $b['sort'] ) {
5154
			return 0;
5155
		}
5156
5157
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5158
	}
5159
5160
	function ajax_recheck_ssl() {
5161
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5162
		$result = self::permit_ssl( true );
5163
		wp_send_json(
5164
			array(
5165
				'enabled' => $result,
5166
				'message' => get_transient( 'jetpack_https_test_message' ),
5167
			)
5168
		);
5169
	}
5170
5171
	/* Client API */
5172
5173
	/**
5174
	 * Returns the requested Jetpack API URL
5175
	 *
5176
	 * @deprecated since 7.7
5177
	 * @return string
5178
	 */
5179
	public static function api_url( $relative_url ) {
5180
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5181
		$connection = self::connection();
5182
		return $connection->api_url( $relative_url );
5183
	}
5184
5185
	/**
5186
	 * @deprecated 8.0
5187
	 *
5188
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5189
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5190
	 */
5191
	public static function fix_url_for_bad_hosts( $url ) {
5192
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5193
		return $url;
5194
	}
5195
5196
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5197
		// Default to a blog token.
5198
		$token_type = 'blog';
5199
5200
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5201
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5202
			if ( ! empty( $_GET['onboarding'] ) ) {
5203
				$jpo = $_GET;
5204
			} else {
5205
				$jpo = json_decode( $request_data, true );
5206
			}
5207
5208
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5209
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5210
5211
			if (
5212
				isset( $jpo_user )
5213
				&& isset( $jpo_token )
5214
				&& is_email( $jpo_user )
5215
				&& ctype_alnum( $jpo_token )
5216
				&& isset( $_GET['rest_route'] )
5217
				&& self::validate_onboarding_token_action(
5218
					$jpo_token,
5219
					$_GET['rest_route']
5220
				)
5221
			) {
5222
				$jp_user = get_user_by( 'email', $jpo_user );
5223
				if ( is_a( $jp_user, 'WP_User' ) ) {
5224
					wp_set_current_user( $jp_user->ID );
5225
					$user_can = is_multisite()
5226
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5227
						: current_user_can( 'manage_options' );
5228
					if ( $user_can ) {
5229
						$token_type              = 'user';
5230
						$token->external_user_id = $jp_user->ID;
5231
					}
5232
				}
5233
			}
5234
5235
			$token_data['type']    = $token_type;
5236
			$token_data['user_id'] = $token->external_user_id;
5237
		}
5238
5239
		return $token_data;
5240
	}
5241
5242
	/**
5243
	 * Create a random secret for validating onboarding payload
5244
	 *
5245
	 * @return string Secret token
5246
	 */
5247
	public static function create_onboarding_token() {
5248
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5249
			$token = wp_generate_password( 32, false );
5250
			Jetpack_Options::update_option( 'onboarding', $token );
5251
		}
5252
5253
		return $token;
5254
	}
5255
5256
	/**
5257
	 * Remove the onboarding token
5258
	 *
5259
	 * @return bool True on success, false on failure
5260
	 */
5261
	public static function invalidate_onboarding_token() {
5262
		return Jetpack_Options::delete_option( 'onboarding' );
5263
	}
5264
5265
	/**
5266
	 * Validate an onboarding token for a specific action
5267
	 *
5268
	 * @return boolean True if token/action pair is accepted, false if not
5269
	 */
5270
	public static function validate_onboarding_token_action( $token, $action ) {
5271
		// Compare tokens, bail if tokens do not match
5272
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5273
			return false;
5274
		}
5275
5276
		// List of valid actions we can take
5277
		$valid_actions = array(
5278
			'/jetpack/v4/settings',
5279
		);
5280
5281
		// Only allow valid actions.
5282
		if ( ! in_array( $action, $valid_actions ) ) {
5283
			return false;
5284
		}
5285
5286
		return true;
5287
	}
5288
5289
	/**
5290
	 * Checks to see if the URL is using SSL to connect with Jetpack
5291
	 *
5292
	 * @since 2.3.3
5293
	 * @return boolean
5294
	 */
5295
	public static function permit_ssl( $force_recheck = false ) {
5296
		// Do some fancy tests to see if ssl is being supported
5297
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5298
			$message = '';
5299
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5300
				$ssl = 0;
5301
			} else {
5302
				$ssl = 1;
5303
5304
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5305
					$ssl     = 0;
5306
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5307
				} else {
5308
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5309
					if ( is_wp_error( $response ) ) {
5310
						$ssl     = 0;
5311
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5312
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5313
						$ssl     = 0;
5314
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5315
					}
5316
				}
5317
			}
5318
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5319
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5320
		}
5321
5322
		return (bool) $ssl;
5323
	}
5324
5325
	/*
5326
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5327
	 */
5328
	public function alert_auto_ssl_fail() {
5329
		if ( ! current_user_can( 'manage_options' ) ) {
5330
			return;
5331
		}
5332
5333
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5334
		?>
5335
5336
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5337
			<div class="jp-banner__content">
5338
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5339
				<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>
5340
				<p>
5341
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5342
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5343
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5344
				</p>
5345
				<p>
5346
					<?php
5347
					printf(
5348
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5349
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5350
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5351
					);
5352
					?>
5353
				</p>
5354
			</div>
5355
		</div>
5356
		<style>
5357
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5358
		</style>
5359
		<script type="text/javascript">
5360
			jQuery( document ).ready( function( $ ) {
5361
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5362
					var $this = $( this );
5363
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5364
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5365
					e.preventDefault();
5366
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5367
					$.post( ajaxurl, data )
5368
					  .done( function( response ) {
5369
						  if ( response.enabled ) {
5370
							  $( '#jetpack-ssl-warning' ).hide();
5371
						  } else {
5372
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5373
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5374
						  }
5375
					  }.bind( $this ) );
5376
				} );
5377
			} );
5378
		</script>
5379
5380
		<?php
5381
	}
5382
5383
	/**
5384
	 * Returns the Jetpack XML-RPC API
5385
	 *
5386
	 * @deprecated 8.0 Use Connection_Manager instead.
5387
	 * @return string
5388
	 */
5389
	public static function xmlrpc_api_url() {
5390
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5391
		return self::connection()->xmlrpc_api_url();
5392
	}
5393
5394
	/**
5395
	 * Returns the connection manager object.
5396
	 *
5397
	 * @return Automattic\Jetpack\Connection\Manager
5398
	 */
5399
	public static function connection() {
5400
		$jetpack = static::init();
5401
5402
		// If the connection manager hasn't been instantiated, do that now.
5403
		if ( ! $jetpack->connection_manager ) {
5404
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5405
		}
5406
5407
		return $jetpack->connection_manager;
5408
	}
5409
5410
	/**
5411
	 * Creates two secret tokens and the end of life timestamp for them.
5412
	 *
5413
	 * Note these tokens are unique per call, NOT static per site for connecting.
5414
	 *
5415
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5416
	 *
5417
	 * @since 2.6
5418
	 * @param String  $action  The action name.
5419
	 * @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...
5420
	 * @param Integer $exp     Expiration time in seconds.
5421
	 * @return array
5422
	 */
5423
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5424
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5425
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5426
	}
5427
5428
	public static function get_secrets( $action, $user_id ) {
5429
		$secrets = ( new Secrets() )->get( $action, $user_id );
5430
5431
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5432
			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...
5433
		}
5434
5435
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5436
			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...
5437
		}
5438
5439
		return $secrets;
5440
	}
5441
5442
	/**
5443
	 * Builds the timeout limit for queries talking with the wpcom servers.
5444
	 *
5445
	 * Based on local php max_execution_time in php.ini
5446
	 *
5447
	 * @since 2.6
5448
	 * @return int
5449
	 * @deprecated
5450
	 **/
5451
	public function get_remote_query_timeout_limit() {
5452
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5453
		return self::get_max_execution_time();
5454
	}
5455
5456
	/**
5457
	 * Builds the timeout limit for queries talking with the wpcom servers.
5458
	 *
5459
	 * Based on local php max_execution_time in php.ini
5460
	 *
5461
	 * @since 5.4
5462
	 * @return int
5463
	 **/
5464
	public static function get_max_execution_time() {
5465
		$timeout = (int) ini_get( 'max_execution_time' );
5466
5467
		// Ensure exec time set in php.ini
5468
		if ( ! $timeout ) {
5469
			$timeout = 30;
5470
		}
5471
		return $timeout;
5472
	}
5473
5474
	/**
5475
	 * Sets a minimum request timeout, and returns the current timeout
5476
	 *
5477
	 * @since 5.4
5478
	 **/
5479 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5480
		$timeout = self::get_max_execution_time();
5481
		if ( $timeout < $min_timeout ) {
5482
			$timeout = $min_timeout;
5483
			set_time_limit( $timeout );
5484
		}
5485
		return $timeout;
5486
	}
5487
5488
	/**
5489
	 * Takes the response from the Jetpack register new site endpoint and
5490
	 * verifies it worked properly.
5491
	 *
5492
	 * @since 2.6
5493
	 * @deprecated since 7.7.0
5494
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5495
	 **/
5496
	public function validate_remote_register_response() {
5497
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5498
	}
5499
5500
	/**
5501
	 * @deprecated since Jetpack 9.7.0
5502
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
5503
	 *
5504
	 * @return bool|WP_Error
5505
	 */
5506
	public static function register() {
5507
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
5508
		return static::connection()->try_registration( false );
5509
	}
5510
5511
	/**
5512
	 * Filters the registration request body to include tracking properties.
5513
	 *
5514
	 * @deprecated since Jetpack 9.7.0
5515
	 * @see Automattic\Jetpack\Connection\Utils::filter_register_request_body()
5516
	 *
5517
	 * @param array $properties
5518
	 * @return array amended properties.
5519
	 */
5520
	public static function filter_register_request_body( $properties ) {
5521
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Utils::filter_register_request_body' );
5522
		return Connection_Utils::filter_register_request_body( $properties );
5523
	}
5524
5525
	/**
5526
	 * Filters the token request body to include tracking properties.
5527
	 *
5528
	 * @param array $properties
5529
	 * @return array amended properties.
5530
	 */
5531 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5532
		$tracking        = new Tracking();
5533
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5534
5535
		return array_merge(
5536
			$properties,
5537
			array(
5538
				'_ui' => $tracks_identity['_ui'],
5539
				'_ut' => $tracks_identity['_ut'],
5540
			)
5541
		);
5542
	}
5543
5544
	/**
5545
	 * If the db version is showing something other that what we've got now, bump it to current.
5546
	 *
5547
	 * @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...
5548
	 */
5549
	public static function maybe_set_version_option() {
5550
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5551
		if ( JETPACK__VERSION != $version ) {
5552
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5553
5554
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5555
				/** This action is documented in class.jetpack.php */
5556
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5557
			}
5558
5559
			return true;
5560
		}
5561
		return false;
5562
	}
5563
5564
	/* Client Server API */
5565
5566
	/**
5567
	 * Loads the Jetpack XML-RPC client.
5568
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5569
	 *
5570
	 * @deprecated since 7.7.0
5571
	 */
5572
	public static function load_xml_rpc_client() {
5573
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5574
	}
5575
5576
	/**
5577
	 * Resets the saved authentication state in between testing requests.
5578
	 *
5579
	 * @deprecated since 8.9.0
5580
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5581
	 */
5582
	public function reset_saved_auth_state() {
5583
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5584
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5585
	}
5586
5587
	/**
5588
	 * Verifies the signature of the current request.
5589
	 *
5590
	 * @deprecated since 7.7.0
5591
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5592
	 *
5593
	 * @return false|array
5594
	 */
5595
	public function verify_xml_rpc_signature() {
5596
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5597
		return self::connection()->verify_xml_rpc_signature();
5598
	}
5599
5600
	/**
5601
	 * Verifies the signature of the current request.
5602
	 *
5603
	 * This function has side effects and should not be used. Instead,
5604
	 * use the memoized version `->verify_xml_rpc_signature()`.
5605
	 *
5606
	 * @deprecated since 7.7.0
5607
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5608
	 * @internal
5609
	 */
5610
	private function internal_verify_xml_rpc_signature() {
5611
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5612
	}
5613
5614
	/**
5615
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5616
	 *
5617
	 * @deprecated since 7.7.0
5618
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5619
	 *
5620
	 * @param \WP_User|mixed $user     User object if authenticated.
5621
	 * @param string         $username Username.
5622
	 * @param string         $password Password string.
5623
	 * @return \WP_User|mixed Authenticated user or error.
5624
	 */
5625 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5626
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5627
5628
		if ( ! $this->connection_manager ) {
5629
			$this->connection_manager = new Connection_Manager();
5630
		}
5631
5632
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5633
	}
5634
5635
	/**
5636
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5637
	 * Uses the existing XMLRPC request signing implementation.
5638
	 *
5639
	 * @deprecated since 8.9.0
5640
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5641
	 */
5642
	function wp_rest_authenticate( $user ) {
5643
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5644
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5645
	}
5646
5647
	/**
5648
	 * Report authentication status to the WP REST API.
5649
	 *
5650
	 * @deprecated since 8.9.0
5651
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5652
	 *
5653
	 * @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...
5654
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5655
	 */
5656
	public function wp_rest_authentication_errors( $value ) {
5657
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5658
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5659
	}
5660
5661
	/**
5662
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5663
	 * Capture it here so we can verify the signature later.
5664
	 *
5665
	 * @deprecated since 7.7.0
5666
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5667
	 *
5668
	 * @param array $methods XMLRPC methods.
5669
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5670
	 */
5671 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5672
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5673
5674
		if ( ! $this->connection_manager ) {
5675
			$this->connection_manager = new Connection_Manager();
5676
		}
5677
5678
		return $this->connection_manager->xmlrpc_methods( $methods );
5679
	}
5680
5681
	/**
5682
	 * Register additional public XMLRPC methods.
5683
	 *
5684
	 * @deprecated since 7.7.0
5685
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5686
	 *
5687
	 * @param array $methods Public XMLRPC methods.
5688
	 * @return array Public XMLRPC methods, with the getOptions one.
5689
	 */
5690 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5691
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5692
5693
		if ( ! $this->connection_manager ) {
5694
			$this->connection_manager = new Connection_Manager();
5695
		}
5696
5697
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5698
	}
5699
5700
	/**
5701
	 * Handles a getOptions XMLRPC method call.
5702
	 *
5703
	 * @deprecated since 7.7.0
5704
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5705
	 *
5706
	 * @param array $args method call arguments.
5707
	 * @return array an amended XMLRPC server options array.
5708
	 */
5709 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5710
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5711
5712
		if ( ! $this->connection_manager ) {
5713
			$this->connection_manager = new Connection_Manager();
5714
		}
5715
5716
		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...
5717
	}
5718
5719
	/**
5720
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5721
	 *
5722
	 * @deprecated since 7.7.0
5723
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5724
	 *
5725
	 * @param array $options Standard Core options.
5726
	 * @return array Amended options.
5727
	 */
5728 View Code Duplication
	public function xmlrpc_options( $options ) {
5729
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5730
5731
		if ( ! $this->connection_manager ) {
5732
			$this->connection_manager = new Connection_Manager();
5733
		}
5734
5735
		return $this->connection_manager->xmlrpc_options( $options );
5736
	}
5737
5738
	/**
5739
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5740
	 * SET: state( $key, $value );
5741
	 * GET: $value = state( $key );
5742
	 *
5743
	 * @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...
5744
	 * @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...
5745
	 * @param bool   $restate private
5746
	 */
5747
	public static function state( $key = null, $value = null, $restate = false ) {
5748
		static $state = array();
5749
		static $path, $domain;
5750
		if ( ! isset( $path ) ) {
5751
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5752
			$admin_url = self::admin_url();
5753
			$bits      = wp_parse_url( $admin_url );
5754
5755
			if ( is_array( $bits ) ) {
5756
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5757
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5758
			} else {
5759
				$path = $domain = null;
5760
			}
5761
		}
5762
5763
		// Extract state from cookies and delete cookies
5764
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5765
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5766
			unset( $_COOKIE['jetpackState'] );
5767
			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...
5768
				if ( strlen( $v ) ) {
5769
					$state[ $k ] = $v;
5770
				}
5771
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5772
			}
5773
		}
5774
5775
		if ( $restate ) {
5776
			foreach ( $state as $k => $v ) {
5777
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5778
			}
5779
			return;
5780
		}
5781
5782
		// Get a state variable.
5783
		if ( isset( $key ) && ! isset( $value ) ) {
5784
			if ( array_key_exists( $key, $state ) ) {
5785
				return $state[ $key ];
5786
			}
5787
			return null;
5788
		}
5789
5790
		// Set a state variable.
5791
		if ( isset( $key ) && isset( $value ) ) {
5792
			if ( is_array( $value ) && isset( $value[0] ) ) {
5793
				$value = $value[0];
5794
			}
5795
			$state[ $key ] = $value;
5796
			if ( ! headers_sent() ) {
5797
				if ( self::should_set_cookie( $key ) ) {
5798
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5799
				}
5800
			}
5801
		}
5802
	}
5803
5804
	public static function restate() {
5805
		self::state( null, null, true );
5806
	}
5807
5808
	/**
5809
	 * Determines whether the jetpackState[$key] value should be added to the
5810
	 * cookie.
5811
	 *
5812
	 * @param string $key The state key.
5813
	 *
5814
	 * @return boolean Whether the value should be added to the cookie.
5815
	 */
5816
	public static function should_set_cookie( $key ) {
5817
		global $current_screen;
5818
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5819
5820
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5821
			return false;
5822
		}
5823
5824
		return true;
5825
	}
5826
5827
	public static function check_privacy( $file ) {
5828
		static $is_site_publicly_accessible = null;
5829
5830
		if ( is_null( $is_site_publicly_accessible ) ) {
5831
			$is_site_publicly_accessible = false;
5832
5833
			$rpc = new Jetpack_IXR_Client();
5834
5835
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5836
			if ( $success ) {
5837
				$response = $rpc->getResponse();
5838
				if ( $response ) {
5839
					$is_site_publicly_accessible = true;
5840
				}
5841
			}
5842
5843
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5844
		}
5845
5846
		if ( $is_site_publicly_accessible ) {
5847
			return;
5848
		}
5849
5850
		$module_slug = self::get_module_slug( $file );
5851
5852
		$privacy_checks = self::state( 'privacy_checks' );
5853
		if ( ! $privacy_checks ) {
5854
			$privacy_checks = $module_slug;
5855
		} else {
5856
			$privacy_checks .= ",$module_slug";
5857
		}
5858
5859
		self::state( 'privacy_checks', $privacy_checks );
5860
	}
5861
5862
	/**
5863
	 * Helper method for multicall XMLRPC.
5864
	 *
5865
	 * @deprecated since 8.9.0
5866
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5867
	 *
5868
	 * @param ...$args Args for the async_call.
5869
	 */
5870
	public static function xmlrpc_async_call( ...$args ) {
5871
5872
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5873
5874
		global $blog_id;
5875
		static $clients = array();
5876
5877
		$client_blog_id = is_multisite() ? $blog_id : 0;
5878
5879
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5880
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5881
			if ( function_exists( 'ignore_user_abort' ) ) {
5882
				ignore_user_abort( true );
5883
			}
5884
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5885
		}
5886
5887
		if ( ! empty( $args[0] ) ) {
5888
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5889
		} elseif ( is_multisite() ) {
5890
			foreach ( $clients as $client_blog_id => $client ) {
5891
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5892
					continue;
5893
				}
5894
5895
				$switch_success = switch_to_blog( $client_blog_id, true );
5896
				if ( ! $switch_success ) {
5897
					continue;
5898
				}
5899
5900
				flush();
5901
				$client->query();
5902
5903
				restore_current_blog();
5904
			}
5905
		} else {
5906
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5907
				flush();
5908
				$clients[0]->query();
5909
			}
5910
		}
5911
	}
5912
5913
	/**
5914
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5915
	 *
5916
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5917
	 *
5918
	 * @param string $url WordPress.com static resource URL.
5919
	 */
5920
	public static function staticize_subdomain( $url ) {
5921
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5922
		return Assets::staticize_subdomain( $url );
5923
	}
5924
5925
	/* JSON API Authorization */
5926
5927
	/**
5928
	 * Handles the login action for Authorizing the JSON API
5929
	 */
5930
	function login_form_json_api_authorization() {
5931
		$this->verify_json_api_authorization_request();
5932
5933
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5934
5935
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5936
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5937
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5938
	}
5939
5940
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5941
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5942
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5943
			return $url;
5944
		}
5945
5946
		$parsed_url = wp_parse_url( $url );
5947
		$url        = strtok( $url, '?' );
5948
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5949
		if ( ! empty( $parsed_url['query'] ) ) {
5950
			$url .= "&{$parsed_url['query']}";
5951
		}
5952
5953
		return $url;
5954
	}
5955
5956
	// Make sure the POSTed request is handled by the same action
5957
	function preserve_action_in_login_form_for_json_api_authorization() {
5958
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5959
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5960
	}
5961
5962
	// If someone logs in to approve API access, store the Access Code in usermeta
5963
	function store_json_api_authorization_token( $user_login, $user ) {
5964
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5965
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5966
		$token = wp_generate_password( 32, false );
5967
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5968
	}
5969
5970
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5971
	function allow_wpcom_public_api_domain( $domains ) {
5972
		$domains[] = 'public-api.wordpress.com';
5973
		return $domains;
5974
	}
5975
5976
	static function is_redirect_encoded( $redirect_url ) {
5977
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5978
	}
5979
5980
	// Add all wordpress.com environments to the safe redirect allowed list.
5981
	function allow_wpcom_environments( $domains ) {
5982
		$domains[] = 'wordpress.com';
5983
		$domains[] = 'wpcalypso.wordpress.com';
5984
		$domains[] = 'horizon.wordpress.com';
5985
		$domains[] = 'calypso.localhost';
5986
		return $domains;
5987
	}
5988
5989
	// Add the Access Code details to the public-api.wordpress.com redirect
5990
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5991
		return add_query_arg(
5992
			urlencode_deep(
5993
				array(
5994
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5995
					'jetpack-user-id' => (int) $user->ID,
5996
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5997
				)
5998
			),
5999
			$redirect_to
6000
		);
6001
	}
6002
6003
	/**
6004
	 * Verifies the request by checking the signature
6005
	 *
6006
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6007
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6008
	 *
6009
	 * @param null|array $environment
6010
	 */
6011
	function verify_json_api_authorization_request( $environment = null ) {
6012
		$environment = is_null( $environment )
6013
			? $_REQUEST
6014
			: $environment;
6015
6016
		//phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
6017
		list( $env_token, $env_version, $env_user_id ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $env_version is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
6018
		$token = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
6019
		if ( ! $token || empty( $token->secret ) ) {
6020
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6021
		}
6022
6023
		$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' );
6024
6025
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6026
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6027
			/**
6028
			 * Jetpack authorisation request Error.
6029
			 *
6030
			 * @since 7.5.0
6031
			 */
6032
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6033
			$die_error = sprintf(
6034
				/* translators: %s is a URL */
6035
				__( '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' ),
6036
				Redirect::get_url( 'jetpack-support-double-encoding' )
6037
			);
6038
		}
6039
6040
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6041
6042
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6043
			$signature = $jetpack_signature->sign_request(
6044
				$environment['token'],
6045
				$environment['timestamp'],
6046
				$environment['nonce'],
6047
				'',
6048
				'GET',
6049
				$environment['jetpack_json_api_original_query'],
6050
				null,
6051
				true
6052
			);
6053
		} else {
6054
			$signature = $jetpack_signature->sign_current_request(
6055
				array(
6056
					'body'   => null,
6057
					'method' => 'GET',
6058
				)
6059
			);
6060
		}
6061
6062
		if ( ! $signature ) {
6063
			wp_die( $die_error );
6064
		} elseif ( is_wp_error( $signature ) ) {
6065
			wp_die( $die_error );
6066
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6067
			if ( is_ssl() ) {
6068
				// 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
6069
				$signature = $jetpack_signature->sign_current_request(
6070
					array(
6071
						'scheme' => 'http',
6072
						'body'   => null,
6073
						'method' => 'GET',
6074
					)
6075
				);
6076
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6077
					wp_die( $die_error );
6078
				}
6079
			} else {
6080
				wp_die( $die_error );
6081
			}
6082
		}
6083
6084
		$timestamp = (int) $environment['timestamp'];
6085
		$nonce     = stripslashes( (string) $environment['nonce'] );
6086
6087
		if ( ! $this->connection_manager ) {
6088
			$this->connection_manager = new Connection_Manager();
6089
		}
6090
6091
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
6092
			// De-nonce the nonce, at least for 5 minutes.
6093
			// 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)
6094
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6095
			if ( $old_nonce_time < time() - 300 ) {
6096
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6097
			}
6098
		}
6099
6100
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6101
		$data_filters = array(
6102
			'state'        => 'opaque',
6103
			'client_id'    => 'int',
6104
			'client_title' => 'string',
6105
			'client_image' => 'url',
6106
		);
6107
6108
		foreach ( $data_filters as $key => $sanitation ) {
6109
			if ( ! isset( $data->$key ) ) {
6110
				wp_die( $die_error );
6111
			}
6112
6113
			switch ( $sanitation ) {
6114
				case 'int':
6115
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6116
					break;
6117
				case 'opaque':
6118
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6119
					break;
6120
				case 'string':
6121
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6122
					break;
6123
				case 'url':
6124
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6125
					break;
6126
			}
6127
		}
6128
6129
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6130
			wp_die( $die_error );
6131
		}
6132
	}
6133
6134
	function login_message_json_api_authorization( $message ) {
6135
		return '<p class="message">' . sprintf(
6136
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6137
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6138
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6139
	}
6140
6141
	/**
6142
	 * Get $content_width, but with a <s>twist</s> filter.
6143
	 */
6144
	public static function get_content_width() {
6145
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6146
			? $GLOBALS['content_width']
6147
			: false;
6148
		/**
6149
		 * Filter the Content Width value.
6150
		 *
6151
		 * @since 2.2.3
6152
		 *
6153
		 * @param string $content_width Content Width value.
6154
		 */
6155
		return apply_filters( 'jetpack_content_width', $content_width );
6156
	}
6157
6158
	/**
6159
	 * Pings the WordPress.com Mirror Site for the specified options.
6160
	 *
6161
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6162
	 *
6163
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6164
	 */
6165
	public function get_cloud_site_options( $option_names ) {
6166
		$option_names = array_filter( (array) $option_names, 'is_string' );
6167
6168
		$xml = new Jetpack_IXR_Client();
6169
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6170
		if ( $xml->isError() ) {
6171
			return array(
6172
				'error_code' => $xml->getErrorCode(),
6173
				'error_msg'  => $xml->getErrorMessage(),
6174
			);
6175
		}
6176
		$cloud_site_options = $xml->getResponse();
6177
6178
		return $cloud_site_options;
6179
	}
6180
6181
	/**
6182
	 * Checks if the site is currently in an identity crisis.
6183
	 *
6184
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6185
	 */
6186
	public static function check_identity_crisis() {
6187
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6188
			return false;
6189
		}
6190
6191
		return Jetpack_Options::get_option( 'sync_error_idc' );
6192
	}
6193
6194
	/**
6195
	 * Checks whether the home and siteurl specifically are allowed.
6196
	 * Written so that we don't have re-check $key and $value params every time
6197
	 * we want to check if this site is allowed, for example in footer.php
6198
	 *
6199
	 * @since  3.8.0
6200
	 * @return bool True = already allowed False = not on the allowed list.
6201
	 */
6202
	public static function is_staging_site() {
6203
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6204
		return ( new Status() )->is_staging_site();
6205
	}
6206
6207
	/**
6208
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6209
	 *
6210
	 * @since 4.4.0
6211
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6212
	 *
6213
	 * @return bool
6214
	 */
6215 View Code Duplication
	public static function validate_sync_error_idc_option() {
6216
		$is_valid = false;
6217
6218
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6219
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6220
		if ( $sync_error && self::sync_idc_optin() ) {
6221
			$local_options = self::get_sync_error_idc_option();
6222
			// Ensure all values are set.
6223
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6224
6225
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6226
				if (
6227
						isset( $sync_error['wpcom_home'] ) &&
6228
						isset( $sync_error['wpcom_siteurl'] ) &&
6229
						$sync_error['wpcom_home'] === $local_options['home'] &&
6230
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6231
				) {
6232
					$is_valid = false;
6233
					// Enable migrate_for_idc so that sync actions are accepted.
6234
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6235
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6236
					$is_valid = true;
6237
				}
6238
			}
6239
		}
6240
6241
		/**
6242
		 * Filters whether the sync_error_idc option is valid.
6243
		 *
6244
		 * @since 4.4.0
6245
		 *
6246
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6247
		 */
6248
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6249
6250
		if ( ! $is_valid && $sync_error ) {
6251
			// Since the option exists, and did not validate, delete it
6252
			Jetpack_Options::delete_option( 'sync_error_idc' );
6253
		}
6254
6255
		return $is_valid;
6256
	}
6257
6258
	/**
6259
	 * Normalizes a url by doing three things:
6260
	 *  - Strips protocol
6261
	 *  - Strips www
6262
	 *  - Adds a trailing slash
6263
	 *
6264
	 * @since 4.4.0
6265
	 * @param string $url
6266
	 * @return WP_Error|string
6267
	 */
6268 View Code Duplication
	public static function normalize_url_protocol_agnostic( $url ) {
6269
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6270
		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...
6271
			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...
6272
		}
6273
6274
		// Strip www and protocols
6275
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6276
		return $url;
6277
	}
6278
6279
	/**
6280
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6281
	 *
6282
	 * @since 4.4.0
6283
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6284
	 *
6285
	 * @param array $response
6286
	 * @return array Array of the local urls, wpcom urls, and error code
6287
	 */
6288 View Code Duplication
	public static function get_sync_error_idc_option( $response = array() ) {
6289
		// Since the local options will hit the database directly, store the values
6290
		// in a transient to allow for autoloading and caching on subsequent views.
6291
		$local_options = get_transient( 'jetpack_idc_local' );
6292
		if ( false === $local_options ) {
6293
			$local_options = array(
6294
				'home'    => Functions::home_url(),
6295
				'siteurl' => Functions::site_url(),
6296
			);
6297
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6298
		}
6299
6300
		$options = array_merge( $local_options, $response );
6301
6302
		$returned_values = array();
6303
		foreach ( $options as $key => $option ) {
6304
			if ( 'error_code' === $key ) {
6305
				$returned_values[ $key ] = $option;
6306
				continue;
6307
			}
6308
6309
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6310
				continue;
6311
			}
6312
6313
			$returned_values[ $key ] = $normalized_url;
6314
		}
6315
6316
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6317
6318
		return $returned_values;
6319
	}
6320
6321
	/**
6322
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6323
	 * If set to true, the site will be put into staging mode.
6324
	 *
6325
	 * @since 4.3.2
6326
	 * @return bool
6327
	 */
6328 View Code Duplication
	public static function sync_idc_optin() {
6329
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6330
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6331
		} else {
6332
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6333
		}
6334
6335
		/**
6336
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
6337
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
6338
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6339
		 *
6340
		 * @since 4.3.2
6341
		 *
6342
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6343
		 */
6344
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6345
	}
6346
6347
	/**
6348
	 * Maybe Use a .min.css stylesheet, maybe not.
6349
	 *
6350
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6351
	 */
6352
	public static function maybe_min_asset( $url, $path, $plugin ) {
6353
		// Short out on things trying to find actual paths.
6354
		if ( ! $path || empty( $plugin ) ) {
6355
			return $url;
6356
		}
6357
6358
		$path = ltrim( $path, '/' );
6359
6360
		// Strip out the abspath.
6361
		$base = dirname( plugin_basename( $plugin ) );
6362
6363
		// Short out on non-Jetpack assets.
6364
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6365
			return $url;
6366
		}
6367
6368
		// File name parsing.
6369
		$file              = "{$base}/{$path}";
6370
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6371
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6372
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6373
		$extension         = array_shift( $file_name_parts_r );
6374
6375
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6376
			// Already pointing at the minified version.
6377
			if ( 'min' === $file_name_parts_r[0] ) {
6378
				return $url;
6379
			}
6380
6381
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6382
			if ( file_exists( $min_full_path ) ) {
6383
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6384
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6385
				if ( 'css' === $extension ) {
6386
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6387
					self::$min_assets[ $key ] = $path;
6388
				}
6389
			}
6390
		}
6391
6392
		return $url;
6393
	}
6394
6395
	/**
6396
	 * If the asset is minified, let's flag .min as the suffix.
6397
	 *
6398
	 * Attached to `style_loader_src` filter.
6399
	 *
6400
	 * @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...
6401
	 * @param string $handle The registered handle of the script in question.
6402
	 * @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...
6403
	 */
6404
	public static function set_suffix_on_min( $src, $handle ) {
6405
		if ( false === strpos( $src, '.min.css' ) ) {
6406
			return $src;
6407
		}
6408
6409
		if ( ! empty( self::$min_assets ) ) {
6410
			foreach ( self::$min_assets as $file => $path ) {
6411
				if ( false !== strpos( $src, $file ) ) {
6412
					wp_style_add_data( $handle, 'suffix', '.min' );
6413
					return $src;
6414
				}
6415
			}
6416
		}
6417
6418
		return $src;
6419
	}
6420
6421
	/**
6422
	 * Maybe inlines a stylesheet.
6423
	 *
6424
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6425
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6426
	 *
6427
	 * Attached to `style_loader_tag` filter.
6428
	 *
6429
	 * @param string $tag The tag that would link to the external asset.
6430
	 * @param string $handle The registered handle of the script in question.
6431
	 *
6432
	 * @return string
6433
	 */
6434
	public static function maybe_inline_style( $tag, $handle ) {
6435
		global $wp_styles;
6436
		$item = $wp_styles->registered[ $handle ];
6437
6438
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6439
			return $tag;
6440
		}
6441
6442
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6443
			$href = $matches[1];
6444
			// Strip off query string
6445
			if ( $pos = strpos( $href, '?' ) ) {
6446
				$href = substr( $href, 0, $pos );
6447
			}
6448
			// Strip off fragment
6449
			if ( $pos = strpos( $href, '#' ) ) {
6450
				$href = substr( $href, 0, $pos );
6451
			}
6452
		} else {
6453
			return $tag;
6454
		}
6455
6456
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6457
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6458
			return $tag;
6459
		}
6460
6461
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6462
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6463
			// And this isn't the pass that actually deals with the RTL version...
6464
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6465
				// Short out, as the RTL version will deal with it in a moment.
6466
				return $tag;
6467
			}
6468
		}
6469
6470
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6471
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6472
		if ( $css ) {
6473
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6474
			if ( empty( $item->extra['after'] ) ) {
6475
				wp_add_inline_style( $handle, $css );
6476
			} else {
6477
				array_unshift( $item->extra['after'], $css );
6478
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6479
			}
6480
		}
6481
6482
		return $tag;
6483
	}
6484
6485
	/**
6486
	 * Loads a view file from the views
6487
	 *
6488
	 * Data passed in with the $data parameter will be available in the
6489
	 * template file as $data['value']
6490
	 *
6491
	 * @param string $template - Template file to load
6492
	 * @param array  $data - Any data to pass along to the template
6493
	 * @return boolean - If template file was found
6494
	 **/
6495
	public function load_view( $template, $data = array() ) {
6496
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6497
6498
		if ( file_exists( $views_dir . $template ) ) {
6499
			require_once $views_dir . $template;
6500
			return true;
6501
		}
6502
6503
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6504
		return false;
6505
	}
6506
6507
	/**
6508
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6509
	 */
6510
	public function deprecated_hooks() {
6511
		$filter_deprecated_list = array(
6512
			'jetpack_bail_on_shortcode'                    => array(
6513
				'replacement' => 'jetpack_shortcodes_to_include',
6514
				'version'     => 'jetpack-3.1.0',
6515
			),
6516
			'wpl_sharing_2014_1'                           => array(
6517
				'replacement' => null,
6518
				'version'     => 'jetpack-3.6.0',
6519
			),
6520
			'jetpack-tools-to-include'                     => array(
6521
				'replacement' => 'jetpack_tools_to_include',
6522
				'version'     => 'jetpack-3.9.0',
6523
			),
6524
			'jetpack_identity_crisis_options_to_check'     => array(
6525
				'replacement' => null,
6526
				'version'     => 'jetpack-4.0.0',
6527
			),
6528
			'update_option_jetpack_single_user_site'       => array(
6529
				'replacement' => null,
6530
				'version'     => 'jetpack-4.3.0',
6531
			),
6532
			'audio_player_default_colors'                  => array(
6533
				'replacement' => null,
6534
				'version'     => 'jetpack-4.3.0',
6535
			),
6536
			'add_option_jetpack_featured_images_enabled'   => array(
6537
				'replacement' => null,
6538
				'version'     => 'jetpack-4.3.0',
6539
			),
6540
			'add_option_jetpack_update_details'            => array(
6541
				'replacement' => null,
6542
				'version'     => 'jetpack-4.3.0',
6543
			),
6544
			'add_option_jetpack_updates'                   => array(
6545
				'replacement' => null,
6546
				'version'     => 'jetpack-4.3.0',
6547
			),
6548
			'add_option_jetpack_network_name'              => array(
6549
				'replacement' => null,
6550
				'version'     => 'jetpack-4.3.0',
6551
			),
6552
			'add_option_jetpack_network_allow_new_registrations' => array(
6553
				'replacement' => null,
6554
				'version'     => 'jetpack-4.3.0',
6555
			),
6556
			'add_option_jetpack_network_add_new_users'     => array(
6557
				'replacement' => null,
6558
				'version'     => 'jetpack-4.3.0',
6559
			),
6560
			'add_option_jetpack_network_site_upload_space' => array(
6561
				'replacement' => null,
6562
				'version'     => 'jetpack-4.3.0',
6563
			),
6564
			'add_option_jetpack_network_upload_file_types' => array(
6565
				'replacement' => null,
6566
				'version'     => 'jetpack-4.3.0',
6567
			),
6568
			'add_option_jetpack_network_enable_administration_menus' => array(
6569
				'replacement' => null,
6570
				'version'     => 'jetpack-4.3.0',
6571
			),
6572
			'add_option_jetpack_is_multi_site'             => array(
6573
				'replacement' => null,
6574
				'version'     => 'jetpack-4.3.0',
6575
			),
6576
			'add_option_jetpack_is_main_network'           => array(
6577
				'replacement' => null,
6578
				'version'     => 'jetpack-4.3.0',
6579
			),
6580
			'add_option_jetpack_main_network_site'         => array(
6581
				'replacement' => null,
6582
				'version'     => 'jetpack-4.3.0',
6583
			),
6584
			'jetpack_sync_all_registered_options'          => array(
6585
				'replacement' => null,
6586
				'version'     => 'jetpack-4.3.0',
6587
			),
6588
			'jetpack_has_identity_crisis'                  => array(
6589
				'replacement' => 'jetpack_sync_error_idc_validation',
6590
				'version'     => 'jetpack-4.4.0',
6591
			),
6592
			'jetpack_is_post_mailable'                     => array(
6593
				'replacement' => null,
6594
				'version'     => 'jetpack-4.4.0',
6595
			),
6596
			'jetpack_seo_site_host'                        => array(
6597
				'replacement' => null,
6598
				'version'     => 'jetpack-5.1.0',
6599
			),
6600
			'jetpack_installed_plugin'                     => array(
6601
				'replacement' => 'jetpack_plugin_installed',
6602
				'version'     => 'jetpack-6.0.0',
6603
			),
6604
			'jetpack_holiday_snow_option_name'             => array(
6605
				'replacement' => null,
6606
				'version'     => 'jetpack-6.0.0',
6607
			),
6608
			'jetpack_holiday_chance_of_snow'               => array(
6609
				'replacement' => null,
6610
				'version'     => 'jetpack-6.0.0',
6611
			),
6612
			'jetpack_holiday_snow_js_url'                  => array(
6613
				'replacement' => null,
6614
				'version'     => 'jetpack-6.0.0',
6615
			),
6616
			'jetpack_is_holiday_snow_season'               => array(
6617
				'replacement' => null,
6618
				'version'     => 'jetpack-6.0.0',
6619
			),
6620
			'jetpack_holiday_snow_option_updated'          => array(
6621
				'replacement' => null,
6622
				'version'     => 'jetpack-6.0.0',
6623
			),
6624
			'jetpack_holiday_snowing'                      => array(
6625
				'replacement' => null,
6626
				'version'     => 'jetpack-6.0.0',
6627
			),
6628
			'jetpack_sso_auth_cookie_expirtation'          => array(
6629
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6630
				'version'     => 'jetpack-6.1.0',
6631
			),
6632
			'jetpack_cache_plans'                          => array(
6633
				'replacement' => null,
6634
				'version'     => 'jetpack-6.1.0',
6635
			),
6636
6637
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6638
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6639
				'version'     => 'jetpack-6.5.0',
6640
			),
6641
			'jetpack_enable_site_verification'             => array(
6642
				'replacement' => null,
6643
				'version'     => 'jetpack-6.5.0',
6644
			),
6645
			'can_display_jetpack_manage_notice'            => array(
6646
				'replacement' => null,
6647
				'version'     => 'jetpack-7.3.0',
6648
			),
6649
			'atd_http_post_timeout'                        => array(
6650
				'replacement' => null,
6651
				'version'     => 'jetpack-7.3.0',
6652
			),
6653
			'atd_service_domain'                           => array(
6654
				'replacement' => null,
6655
				'version'     => 'jetpack-7.3.0',
6656
			),
6657
			'atd_load_scripts'                             => array(
6658
				'replacement' => null,
6659
				'version'     => 'jetpack-7.3.0',
6660
			),
6661
			'jetpack_widget_authors_exclude'               => array(
6662
				'replacement' => 'jetpack_widget_authors_params',
6663
				'version'     => 'jetpack-7.7.0',
6664
			),
6665
			// Removed in Jetpack 7.9.0
6666
			'jetpack_pwa_manifest'                         => array(
6667
				'replacement' => null,
6668
				'version'     => 'jetpack-7.9.0',
6669
			),
6670
			'jetpack_pwa_background_color'                 => array(
6671
				'replacement' => null,
6672
				'version'     => 'jetpack-7.9.0',
6673
			),
6674
			'jetpack_check_mobile'                         => array(
6675
				'replacement' => null,
6676
				'version'     => 'jetpack-8.3.0',
6677
			),
6678
			'jetpack_mobile_stylesheet'                    => array(
6679
				'replacement' => null,
6680
				'version'     => 'jetpack-8.3.0',
6681
			),
6682
			'jetpack_mobile_template'                      => array(
6683
				'replacement' => null,
6684
				'version'     => 'jetpack-8.3.0',
6685
			),
6686
			'jetpack_mobile_theme_menu'                    => array(
6687
				'replacement' => null,
6688
				'version'     => 'jetpack-8.3.0',
6689
			),
6690
			'minileven_show_featured_images'               => array(
6691
				'replacement' => null,
6692
				'version'     => 'jetpack-8.3.0',
6693
			),
6694
			'minileven_attachment_size'                    => array(
6695
				'replacement' => null,
6696
				'version'     => 'jetpack-8.3.0',
6697
			),
6698
			'instagram_cache_oembed_api_response_body'     => array(
6699
				'replacement' => null,
6700
				'version'     => 'jetpack-9.1.0',
6701
			),
6702
			'jetpack_can_make_outbound_https'              => array(
6703
				'replacement' => null,
6704
				'version'     => 'jetpack-9.1.0',
6705
			),
6706
		);
6707
6708
		foreach ( $filter_deprecated_list as $tag => $args ) {
6709
			if ( has_filter( $tag ) ) {
6710
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6711
			}
6712
		}
6713
6714
		$action_deprecated_list = array(
6715
			'jetpack_updated_theme'        => array(
6716
				'replacement' => 'jetpack_updated_themes',
6717
				'version'     => 'jetpack-6.2.0',
6718
			),
6719
			'atd_http_post_error'          => array(
6720
				'replacement' => null,
6721
				'version'     => 'jetpack-7.3.0',
6722
			),
6723
			'mobile_reject_mobile'         => array(
6724
				'replacement' => null,
6725
				'version'     => 'jetpack-8.3.0',
6726
			),
6727
			'mobile_force_mobile'          => array(
6728
				'replacement' => null,
6729
				'version'     => 'jetpack-8.3.0',
6730
			),
6731
			'mobile_app_promo_download'    => array(
6732
				'replacement' => null,
6733
				'version'     => 'jetpack-8.3.0',
6734
			),
6735
			'mobile_setup'                 => array(
6736
				'replacement' => null,
6737
				'version'     => 'jetpack-8.3.0',
6738
			),
6739
			'jetpack_mobile_footer_before' => array(
6740
				'replacement' => null,
6741
				'version'     => 'jetpack-8.3.0',
6742
			),
6743
			'wp_mobile_theme_footer'       => array(
6744
				'replacement' => null,
6745
				'version'     => 'jetpack-8.3.0',
6746
			),
6747
			'minileven_credits'            => array(
6748
				'replacement' => null,
6749
				'version'     => 'jetpack-8.3.0',
6750
			),
6751
			'jetpack_mobile_header_before' => array(
6752
				'replacement' => null,
6753
				'version'     => 'jetpack-8.3.0',
6754
			),
6755
			'jetpack_mobile_header_after'  => array(
6756
				'replacement' => null,
6757
				'version'     => 'jetpack-8.3.0',
6758
			),
6759
		);
6760
6761
		foreach ( $action_deprecated_list as $tag => $args ) {
6762
			if ( has_action( $tag ) ) {
6763
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6764
			}
6765
		}
6766
	}
6767
6768
	/**
6769
	 * Converts any url in a stylesheet, to the correct absolute url.
6770
	 *
6771
	 * Considerations:
6772
	 *  - Normal, relative URLs     `feh.png`
6773
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6774
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6775
	 *  - Absolute URLs             `http://domain.com/feh.png`
6776
	 *  - Domain root relative URLs `/feh.png`
6777
	 *
6778
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6779
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6780
	 *
6781
	 * @return mixed|string
6782
	 */
6783
	public static function absolutize_css_urls( $css, $css_file_url ) {
6784
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6785
		$css_dir = dirname( $css_file_url );
6786
		$p       = wp_parse_url( $css_dir );
6787
		$domain  = sprintf(
6788
			'%1$s//%2$s%3$s%4$s',
6789
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6790
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6791
			$p['host'],
6792
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6793
		);
6794
6795
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6796
			$find = $replace = array();
6797
			foreach ( $matches as $match ) {
6798
				$url = trim( $match['path'], "'\" \t" );
6799
6800
				// If this is a data url, we don't want to mess with it.
6801
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6802
					continue;
6803
				}
6804
6805
				// If this is an absolute or protocol-agnostic url,
6806
				// we don't want to mess with it.
6807
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6808
					continue;
6809
				}
6810
6811
				switch ( substr( $url, 0, 1 ) ) {
6812
					case '/':
6813
						$absolute = $domain . $url;
6814
						break;
6815
					default:
6816
						$absolute = $css_dir . '/' . $url;
6817
				}
6818
6819
				$find[]    = $match[0];
6820
				$replace[] = sprintf( 'url("%s")', $absolute );
6821
			}
6822
			$css = str_replace( $find, $replace, $css );
6823
		}
6824
6825
		return $css;
6826
	}
6827
6828
	/**
6829
	 * This methods removes all of the registered css files on the front end
6830
	 * from Jetpack in favor of using a single file. In effect "imploding"
6831
	 * all the files into one file.
6832
	 *
6833
	 * Pros:
6834
	 * - Uses only ONE css asset connection instead of 15
6835
	 * - Saves a minimum of 56k
6836
	 * - Reduces server load
6837
	 * - Reduces time to first painted byte
6838
	 *
6839
	 * Cons:
6840
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6841
	 *      should not cause any issues with themes.
6842
	 * - Plugins/themes dequeuing styles no longer do anything. See
6843
	 *      jetpack_implode_frontend_css filter for a workaround
6844
	 *
6845
	 * For some situations developers may wish to disable css imploding and
6846
	 * instead operate in legacy mode where each file loads seperately and
6847
	 * can be edited individually or dequeued. This can be accomplished with
6848
	 * the following line:
6849
	 *
6850
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6851
	 *
6852
	 * @since 3.2
6853
	 **/
6854
	public function implode_frontend_css( $travis_test = false ) {
6855
		$do_implode = true;
6856
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6857
			$do_implode = false;
6858
		}
6859
6860
		// Do not implode CSS when the page loads via the AMP plugin.
6861
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6862
			$do_implode = false;
6863
		}
6864
6865
		/**
6866
		 * Allow CSS to be concatenated into a single jetpack.css file.
6867
		 *
6868
		 * @since 3.2.0
6869
		 *
6870
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6871
		 */
6872
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6873
6874
		// Do not use the imploded file when default behavior was altered through the filter
6875
		if ( ! $do_implode ) {
6876
			return;
6877
		}
6878
6879
		// We do not want to use the imploded file in dev mode, or if not connected
6880
		if ( ( new Status() )->is_offline_mode() || ! self::is_connection_ready() ) {
6881
			if ( ! $travis_test ) {
6882
				return;
6883
			}
6884
		}
6885
6886
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6887
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6888
			return;
6889
		}
6890
6891
		/*
6892
		 * Now we assume Jetpack is connected and able to serve the single
6893
		 * file.
6894
		 *
6895
		 * In the future there will be a check here to serve the file locally
6896
		 * or potentially from the Jetpack CDN
6897
		 *
6898
		 * For now:
6899
		 * - Enqueue a single imploded css file
6900
		 * - Zero out the style_loader_tag for the bundled ones
6901
		 * - Be happy, drink scotch
6902
		 */
6903
6904
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6905
6906
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6907
6908
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6909
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6910
	}
6911
6912
	function concat_remove_style_loader_tag( $tag, $handle ) {
6913
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6914
			$tag = '';
6915
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6916
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6917
			}
6918
		}
6919
6920
		return $tag;
6921
	}
6922
6923
	/**
6924
	 * @deprecated
6925
	 * @see Automattic\Jetpack\Assets\add_aync_script
6926
	 */
6927
	public function script_add_async( $tag, $handle, $src ) {
6928
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6929
	}
6930
6931
	/*
6932
	 * Check the heartbeat data
6933
	 *
6934
	 * Organizes the heartbeat data by severity.  For example, if the site
6935
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6936
	 *
6937
	 * Data will be added to "caution" array, if it either:
6938
	 *  - Out of date Jetpack version
6939
	 *  - Out of date WP version
6940
	 *  - Out of date PHP version
6941
	 *
6942
	 * $return array $filtered_data
6943
	 */
6944
	public static function jetpack_check_heartbeat_data() {
6945
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6946
6947
		$good    = array();
6948
		$caution = array();
6949
		$bad     = array();
6950
6951
		foreach ( $raw_data as $stat => $value ) {
6952
6953
			// Check jetpack version
6954
			if ( 'version' == $stat ) {
6955
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6956
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6957
					continue;
6958
				}
6959
			}
6960
6961
			// Check WP version
6962
			if ( 'wp-version' == $stat ) {
6963
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6964
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6965
					continue;
6966
				}
6967
			}
6968
6969
			// Check PHP version
6970
			if ( 'php-version' == $stat ) {
6971
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6972
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6973
					continue;
6974
				}
6975
			}
6976
6977
			// Check ID crisis
6978
			if ( 'identitycrisis' == $stat ) {
6979
				if ( 'yes' == $value ) {
6980
					$bad[ $stat ] = $value;
6981
					continue;
6982
				}
6983
			}
6984
6985
			// The rest are good :)
6986
			$good[ $stat ] = $value;
6987
		}
6988
6989
		$filtered_data = array(
6990
			'good'    => $good,
6991
			'caution' => $caution,
6992
			'bad'     => $bad,
6993
		);
6994
6995
		return $filtered_data;
6996
	}
6997
6998
	/*
6999
	 * This method is used to organize all options that can be reset
7000
	 * without disconnecting Jetpack.
7001
	 *
7002
	 * It is used in class.jetpack-cli.php to reset options
7003
	 *
7004
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
7005
	 *
7006
	 * @return array of options to delete.
7007
	 */
7008
	public static function get_jetpack_options_for_reset() {
7009
		return Jetpack_Options::get_options_for_reset();
7010
	}
7011
7012
	/*
7013
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
7014
	 * so we can bring them directly to their site in calypso.
7015
	 *
7016
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
7017
	 *
7018
	 * @param string | url
7019
	 * @return string | url without the guff
7020
	 */
7021
	public static function build_raw_urls( $url ) {
7022
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
7023
7024
		return ( new Status() )->get_site_suffix( $url );
7025
	}
7026
7027
	/**
7028
	 * Stores and prints out domains to prefetch for page speed optimization.
7029
	 *
7030
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
7031
	 *
7032
	 * @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...
7033
	 */
7034
	public static function dns_prefetch( $urls = null ) {
7035
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
7036
		if ( $urls ) {
7037
			Assets::add_resource_hint( $urls );
7038
		}
7039
	}
7040
7041
	public function wp_dashboard_setup() {
7042
		if ( self::is_connection_ready() ) {
7043
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
7044
		}
7045
7046
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
7047
			$jetpack_logo = new Jetpack_Logo();
7048
			$widget_title = sprintf(
7049
				/* translators: Placeholder is a Jetpack logo. */
7050
				__( 'Stats by %s', 'jetpack' ),
7051
				$jetpack_logo->get_jp_emblem( true )
7052
			);
7053
7054
			// Wrap title in span so Logo can be properly styled.
7055
			$widget_title = sprintf(
7056
				'<span>%s</span>',
7057
				$widget_title
7058
			);
7059
7060
			wp_add_dashboard_widget(
7061
				'jetpack_summary_widget',
7062
				$widget_title,
7063
				array( __CLASS__, 'dashboard_widget' )
7064
			);
7065
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
7066
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
7067
7068
			// If we're inactive and not in offline mode, sort our box to the top.
7069
			if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
7070
				global $wp_meta_boxes;
7071
7072
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7073
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7074
7075
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7076
			}
7077
		}
7078
	}
7079
7080
	/**
7081
	 * @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...
7082
	 * @return mixed
7083
	 */
7084
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7085
		if ( ! is_array( $sorted ) ) {
7086
			return $sorted;
7087
		}
7088
7089
		foreach ( $sorted as $box_context => $ids ) {
7090
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7091
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7092
				continue;
7093
			}
7094
7095
			$ids_array = explode( ',', $ids );
7096
			$key       = array_search( 'dashboard_stats', $ids_array );
7097
7098
			if ( false !== $key ) {
7099
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7100
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7101
				$sorted[ $box_context ] = implode( ',', $ids_array );
7102
				// We've found it, stop searching, and just return.
7103
				break;
7104
			}
7105
		}
7106
7107
		return $sorted;
7108
	}
7109
7110
	public static function dashboard_widget() {
7111
		/**
7112
		 * Fires when the dashboard is loaded.
7113
		 *
7114
		 * @since 3.4.0
7115
		 */
7116
		do_action( 'jetpack_dashboard_widget' );
7117
	}
7118
7119
	public static function dashboard_widget_footer() {
7120
		?>
7121
		<footer>
7122
7123
		<div class="protect">
7124
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7125
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7126
				<p class="blocked-count">
7127
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7128
				</p>
7129
				<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>
7130
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7131
				<a href="
7132
				<?php
7133
				echo esc_url(
7134
					wp_nonce_url(
7135
						self::admin_url(
7136
							array(
7137
								'action' => 'activate',
7138
								'module' => 'protect',
7139
							)
7140
						),
7141
						'jetpack_activate-protect'
7142
					)
7143
				);
7144
				?>
7145
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7146
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7147
				</a>
7148
			<?php else : ?>
7149
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7150
			<?php endif; ?>
7151
		</div>
7152
7153
		<div class="akismet">
7154
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7155
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7156
				<p class="blocked-count">
7157
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7158
				</p>
7159
				<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>
7160
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7161
				<a href="
7162
				<?php
7163
				echo esc_url(
7164
					wp_nonce_url(
7165
						add_query_arg(
7166
							array(
7167
								'action' => 'activate',
7168
								'plugin' => 'akismet/akismet.php',
7169
							),
7170
							admin_url( 'plugins.php' )
7171
						),
7172
						'activate-plugin_akismet/akismet.php'
7173
					)
7174
				);
7175
				?>
7176
							" class="button button-jetpack">
7177
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7178
				</a>
7179
			<?php else : ?>
7180
				<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>
7181
			<?php endif; ?>
7182
		</div>
7183
7184
		</footer>
7185
		<?php
7186
	}
7187
7188
	/*
7189
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7190
	 */
7191
	function jetpack_icon_user_connected( $columns ) {
7192
		$columns['user_jetpack'] = '';
7193
		return $columns;
7194
	}
7195
7196
	/*
7197
	 * Show Jetpack icon if the user is linked.
7198
	 */
7199
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7200
		if ( 'user_jetpack' === $col && self::connection()->is_user_connected( $user_id ) ) {
7201
			$jetpack_logo = new Jetpack_Logo();
7202
			$emblem_html  = sprintf(
7203
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7204
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7205
				$jetpack_logo->get_jp_emblem()
7206
			);
7207
			return $emblem_html;
7208
		}
7209
7210
		return $val;
7211
	}
7212
7213
	/*
7214
	 * Style the Jetpack user column
7215
	 */
7216
	function jetpack_user_col_style() {
7217
		global $current_screen;
7218
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7219
			?>
7220
			<style>
7221
				.fixed .column-user_jetpack {
7222
					width: 21px;
7223
				}
7224
				.jp-emblem-user-admin svg {
7225
					width: 20px;
7226
					height: 20px;
7227
				}
7228
				.jp-emblem-user-admin path {
7229
					fill: #00BE28;
7230
				}
7231
			</style>
7232
			<?php
7233
		}
7234
	}
7235
7236
	/**
7237
	 * Checks if Akismet is active and working.
7238
	 *
7239
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7240
	 * that implied usage of methods present since more recent version.
7241
	 * See https://github.com/Automattic/jetpack/pull/9585
7242
	 *
7243
	 * @since  5.1.0
7244
	 *
7245
	 * @return bool True = Akismet available. False = Aksimet not available.
7246
	 */
7247
	public static function is_akismet_active() {
7248
		static $status = null;
7249
7250
		if ( ! is_null( $status ) ) {
7251
			return $status;
7252
		}
7253
7254
		// Check if a modern version of Akismet is active.
7255
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7256
			$status = false;
7257
			return $status;
7258
		}
7259
7260
		// Make sure there is a key known to Akismet at all before verifying key.
7261
		$akismet_key = Akismet::get_api_key();
7262
		if ( ! $akismet_key ) {
7263
			$status = false;
7264
			return $status;
7265
		}
7266
7267
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7268
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7269
7270
		// 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.
7271
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7272
		// We cache the result of the Akismet key verification for ten minutes.
7273
		if ( ! $akismet_key_state || $recheck ) {
7274
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7275
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7276
		}
7277
7278
		$status = 'valid' === $akismet_key_state;
7279
7280
		return $status;
7281
	}
7282
7283
	/**
7284
	 * @deprecated
7285
	 *
7286
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7287
	 */
7288
	public static function is_function_in_backtrace() {
7289
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7290
	}
7291
7292
	/**
7293
	 * Given a minified path, and a non-minified path, will return
7294
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7295
	 *
7296
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7297
	 * root Jetpack directory.
7298
	 *
7299
	 * @since 5.6.0
7300
	 *
7301
	 * @param string $min_path
7302
	 * @param string $non_min_path
7303
	 * @return string The URL to the file
7304
	 */
7305
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7306
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7307
	}
7308
7309
	/**
7310
	 * Checks for whether Jetpack Backup is enabled.
7311
	 * Will return true if the state of Backup is anything except "unavailable".
7312
	 *
7313
	 * @return bool|int|mixed
7314
	 */
7315
	public static function is_rewind_enabled() {
7316
		// Rewind is a paid feature, therefore requires a user-level connection.
7317
		if ( ! static::connection()->has_connected_owner() ) {
7318
			return false;
7319
		}
7320
7321
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7322
		if ( false === $rewind_enabled ) {
7323
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7324
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7325
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7326
				&& ! empty( $rewind_data['state'] )
7327
				&& 'active' === $rewind_data['state'] )
7328
				? 1
7329
				: 0;
7330
7331
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7332
		}
7333
		return $rewind_enabled;
7334
	}
7335
7336
	/**
7337
	 * Return Calypso environment value; used for developing Jetpack and pairing
7338
	 * it with different Calypso enrionments, such as localhost.
7339
	 *
7340
	 * @since 7.4.0
7341
	 *
7342
	 * @return string Calypso environment
7343
	 */
7344
	public static function get_calypso_env() {
7345
		if ( isset( $_GET['calypso_env'] ) ) {
7346
			return sanitize_key( $_GET['calypso_env'] );
7347
		}
7348
7349
		if ( getenv( 'CALYPSO_ENV' ) ) {
7350
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7351
		}
7352
7353
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7354
			return sanitize_key( CALYPSO_ENV );
7355
		}
7356
7357
		return '';
7358
	}
7359
7360
	/**
7361
	 * Returns the hostname with protocol for Calypso.
7362
	 * Used for developing Jetpack with Calypso.
7363
	 *
7364
	 * @since 8.4.0
7365
	 *
7366
	 * @return string Calypso host.
7367
	 */
7368
	public static function get_calypso_host() {
7369
		$calypso_env = self::get_calypso_env();
7370
		switch ( $calypso_env ) {
7371
			case 'development':
7372
				return 'http://calypso.localhost:3000/';
7373
			case 'wpcalypso':
7374
				return 'https://wpcalypso.wordpress.com/';
7375
			case 'horizon':
7376
				return 'https://horizon.wordpress.com/';
7377
			default:
7378
				return 'https://wordpress.com/';
7379
		}
7380
	}
7381
7382
	/**
7383
	 * Handles activating default modules as well general cleanup for the new connection.
7384
	 *
7385
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7386
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7387
	 * @param boolean $send_state_messages          Whether to send state messages.
7388
	 * @return void
7389
	 */
7390
	public static function handle_post_authorization_actions(
7391
		$activate_sso = false,
7392
		$redirect_on_activation_error = false,
7393
		$send_state_messages = true
7394
	) {
7395
		$other_modules = $activate_sso
7396
			? array( 'sso' )
7397
			: array();
7398
7399
		if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
7400
			$active_modules = Jetpack_Options::get_option( 'active_modules' );
7401
			self::delete_active_modules();
7402
7403
			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...
7404
		} else {
7405
			// Default modules that don't require a user were already activated on site_register.
7406
			// This time let's activate only those that require a user, this assures we don't reactivate manually deactivated modules while the site was user-less.
7407
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
7408
			Jetpack_Options::update_option( 'active_modules_initialized', true );
7409
		}
7410
7411
		// Since this is a fresh connection, be sure to clear out IDC options
7412
		Jetpack_IDC::clear_all_idc_options();
7413
7414
		if ( $send_state_messages ) {
7415
			self::state( 'message', 'authorized' );
7416
		}
7417
	}
7418
7419
	/**
7420
	 * Returns a boolean for whether backups UI should be displayed or not.
7421
	 *
7422
	 * @return bool Should backups UI be displayed?
7423
	 */
7424
	public static function show_backups_ui() {
7425
		/**
7426
		 * Whether UI for backups should be displayed.
7427
		 *
7428
		 * @since 6.5.0
7429
		 *
7430
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7431
		 */
7432
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7433
	}
7434
7435
	/*
7436
	 * Deprecated manage functions
7437
	 */
7438
	function prepare_manage_jetpack_notice() {
7439
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7440
	}
7441
	function manage_activate_screen() {
7442
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7443
	}
7444
	function admin_jetpack_manage_notice() {
7445
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7446
	}
7447
	function opt_out_jetpack_manage_url() {
7448
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7449
	}
7450
	function opt_in_jetpack_manage_url() {
7451
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7452
	}
7453
	function opt_in_jetpack_manage_notice() {
7454
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7455
	}
7456
	function can_display_jetpack_manage_notice() {
7457
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7458
	}
7459
7460
	/**
7461
	 * Clean leftoveruser meta.
7462
	 *
7463
	 * Delete Jetpack-related user meta when it is no longer needed.
7464
	 *
7465
	 * @since 7.3.0
7466
	 *
7467
	 * @param int $user_id User ID being updated.
7468
	 */
7469
	public static function user_meta_cleanup( $user_id ) {
7470
		$meta_keys = array(
7471
			// AtD removed from Jetpack 7.3
7472
			'AtD_options',
7473
			'AtD_check_when',
7474
			'AtD_guess_lang',
7475
			'AtD_ignored_phrases',
7476
		);
7477
7478
		foreach ( $meta_keys as $meta_key ) {
7479
			if ( get_user_meta( $user_id, $meta_key ) ) {
7480
				delete_user_meta( $user_id, $meta_key );
7481
			}
7482
		}
7483
	}
7484
7485
	/**
7486
	 * Checks if a Jetpack site is both active and not in offline mode.
7487
	 *
7488
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7489
	 *
7490
	 * @deprecated 8.8.0
7491
	 *
7492
	 * @return bool True if Jetpack is active and not in offline mode.
7493
	 */
7494
	public static function is_active_and_not_development_mode() {
7495
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7496
		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...
7497
			return false;
7498
		}
7499
		return true;
7500
	}
7501
7502
	/**
7503
	 * Checks if a Jetpack site is both active and not in offline mode.
7504
	 *
7505
	 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
7506
	 *
7507
	 * @since 8.8.0
7508
	 *
7509
	 * @return bool True if Jetpack is active and not in offline mode.
7510
	 */
7511
	public static function is_active_and_not_offline_mode() {
7512
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
7513
			return false;
7514
		}
7515
		return true;
7516
	}
7517
7518
	/**
7519
	 * Returns the list of products that we have available for purchase.
7520
	 */
7521
	public static function get_products_for_purchase() {
7522
		$products = array();
7523
		if ( ! is_multisite() ) {
7524
			$products[] = array(
7525
				'key'               => 'backup',
7526
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7527
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7528
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7529
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7530
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7531
				'options'           => array(
7532
					array(
7533
						'type'        => 'daily',
7534
						'slug'        => 'jetpack-backup-daily',
7535
						'key'         => 'jetpack_backup_daily',
7536
						'name'        => __( 'Daily Backups', 'jetpack' ),
7537
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7538
					),
7539
					array(
7540
						'type'        => 'realtime',
7541
						'slug'        => 'jetpack-backup-realtime',
7542
						'key'         => 'jetpack_backup_realtime',
7543
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7544
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7545
					),
7546
				),
7547
				'default_option'    => 'realtime',
7548
				'show_promotion'    => true,
7549
				'discount_percent'  => 70,
7550
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7551
			);
7552
7553
			$products[] = array(
7554
				'key'               => 'scan',
7555
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7556
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7557
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7558
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7559
				'show_promotion'    => true,
7560
				'discount_percent'  => 30,
7561
				'options'           => array(
7562
					array(
7563
						'type' => 'scan',
7564
						'slug' => 'jetpack-scan',
7565
						'key'  => 'jetpack_scan',
7566
						'name' => __( 'Daily Scan', 'jetpack' ),
7567
					),
7568
				),
7569
				'default_option'    => 'scan',
7570
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7571
			);
7572
		}
7573
7574
		$products[] = array(
7575
			'key'               => 'search',
7576
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7577
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7578
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7579
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7580
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7581
			'options'           => array(
7582
				array(
7583
					'type' => 'search',
7584
					'slug' => 'jetpack-search',
7585
					'key'  => 'jetpack_search',
7586
					'name' => __( 'Search', 'jetpack' ),
7587
				),
7588
			),
7589
			'tears'             => array(),
7590
			'default_option'    => 'search',
7591
			'show_promotion'    => false,
7592
			'included_in_plans' => array( 'search-plan' ),
7593
		);
7594
7595
		$products[] = array(
7596
			'key'               => 'anti-spam',
7597
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7598
			'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' ),
7599
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7600
			'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' ),
7601
			'options'           => array(
7602
				array(
7603
					'type' => 'anti-spam',
7604
					'slug' => 'jetpack-anti-spam',
7605
					'key'  => 'jetpack_anti_spam',
7606
					'name' => __( 'Anti-Spam', 'jetpack' ),
7607
				),
7608
			),
7609
			'default_option'    => 'anti-spam',
7610
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7611
		);
7612
7613
		return $products;
7614
	}
7615
}
7616