Completed
Push — update/phpcs-comment-likes ( acaac7...fc086f )
by
unknown
465:39 queued 455:18
created

Jetpack::is_rewind_enabled()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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