Completed
Push — add/auto-activate-modules-on-u... ( f57438 )
by
unknown
125:19 queued 115:11
created

Jetpack::get_log()   B

Complexity

Conditions 11
Paths 7

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
nc 7
nop 2
dl 0
loc 36
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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_active() ) {
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
		/*
731
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
732
		 * We should make sure to only do this for front end links.
733
		 */
734
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
735
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
736
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
737
738
			/*
739
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
740
			 * so they point moderation links on emails to Calypso.
741
			 */
742
			jetpack_require_lib( 'functions.wp-notify' );
743
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
744
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
745
		}
746
747
		add_action(
748
			'plugins_loaded',
749
			function () {
750
				if ( User_Agent_Info::is_mobile_app() ) {
751
					add_filter( 'get_edit_post_link', '__return_empty_string' );
752
				}
753
			}
754
		);
755
756
		// Update the site's Jetpack plan and products from API on heartbeats.
757
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
758
759
		/**
760
		 * This is the hack to concatenate all css files into one.
761
		 * For description and reasoning see the implode_frontend_css method.
762
		 *
763
		 * Super late priority so we catch all the registered styles.
764
		 */
765
		if ( ! is_admin() ) {
766
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
767
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
768
		}
769
770
		/**
771
		 * These are sync actions that we need to keep track of for jitms
772
		 */
773
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
774
775
		// Actually push the stats on shutdown.
776
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
777
			add_action( 'shutdown', array( $this, 'push_stats' ) );
778
		}
779
780
		// After a successful connection.
781
		add_action( 'jetpack_site_registered', array( $this, 'site_registered' ) );
782
783
		// Actions for Manager::authorize().
784
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
785
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
786
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
787
788
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
789
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
790
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
791
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
792
793
		// Filters for the Manager::get_token() urls and request body.
794
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
795
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
796
797
		// Actions for successful reconnect.
798
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
799
800
		// Actions for licensing.
801
		Licensing::instance()->initialize();
802
803
		// Filters for Sync Callables.
804
		add_filter( 'jetpack_sync_callable_whitelist', array( $this, 'filter_sync_callable_whitelist' ), 10, 1 );
805
806
		// Make resources use static domain when possible.
807
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
808
	}
809
810
	/**
811
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
812
	 * Config object.
813
	 */
814
	public function configure() {
815
		$config = new Config();
816
817
		foreach (
818
			array(
819
				'sync',
820
			)
821
			as $feature
822
		) {
823
			$config->ensure( $feature );
824
		}
825
826
		$config->ensure(
827
			'connection',
828
			array(
829
				'slug' => 'jetpack',
830
				'name' => 'Jetpack',
831
			)
832
		);
833
834
		if ( is_admin() ) {
835
			$config->ensure( 'jitm' );
836
		}
837
838
		if ( ! $this->connection_manager ) {
839
			$this->connection_manager = new Connection_Manager( 'jetpack' );
840
841
			/**
842
			 * Filter to activate Jetpack Connection UI.
843
			 * INTERNAL USE ONLY.
844
			 *
845
			 * @since 9.5.0
846
			 *
847
			 * @param bool false Whether to activate the Connection UI.
848
			 */
849
			if ( apply_filters( 'jetpack_connection_ui_active', false ) ) {
850
				Automattic\Jetpack\ConnectionUI\Admin::init();
851
			}
852
		}
853
854
		/*
855
		 * Load things that should only be in Network Admin.
856
		 *
857
		 * For now blow away everything else until a more full
858
		 * understanding of what is needed at the network level is
859
		 * available
860
		 */
861
		if ( is_multisite() ) {
862
			$network = Jetpack_Network::init();
863
			$network->set_connection( $this->connection_manager );
864
		}
865
866
		if ( $this->connection_manager->is_active() ) {
867
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
868
869
			Jetpack_Heartbeat::init();
870
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
871
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
872
				Jetpack_Search_Performance_Logger::init();
873
			}
874
		}
875
876
		// Initialize remote file upload request handlers.
877
		$this->add_remote_request_handlers();
878
879
		/*
880
		 * Enable enhanced handling of previewing sites in Calypso
881
		 */
882
		if ( self::is_active() ) {
883
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
884
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
885
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
886
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
887
		}
888
889
		if ( ( new Tracking( $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) ) {
0 ignored issues
show
Documentation introduced by
new \Automattic\Jetpack\Status() is of type object<Automattic\Jetpack\Status>, but the function expects a object<Automattic\Jetpac...omattic\Jetpack\Status>.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$this->connection_manager is of type object<Automattic\Jetpack\Connection\Manager>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
890
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
891
		} else {
892
			/**
893
			 * Initialize tracking right after the user agrees to the terms of service.
894
			 */
895
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
896
		}
897
	}
898
899
	/**
900
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
901
	 * initialization code.
902
	 *
903
	 * @action plugins_loaded
904
	 */
905
	public function late_initialization() {
906
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
907
908
		Partner::init();
909
910
		/**
911
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
912
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
913
		 *
914
		 * @since 8.1.0
915
		 *
916
		 * @param Jetpack $jetpack the main plugin class object.
917
		 */
918
		do_action( 'jetpack_loaded', $this );
919
920
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
921
	}
922
923
	/**
924
	 * Sets up the XMLRPC request handlers.
925
	 *
926
	 * @deprecated since 7.7.0
927
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
928
	 *
929
	 * @param array                 $request_params Incoming request parameters.
930
	 * @param Boolean               $is_active      Whether the connection is currently active.
931
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
932
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
933
	 */
934 View Code Duplication
	public function setup_xmlrpc_handlers(
935
		$request_params,
936
		$is_active,
937
		$is_signed,
938
		Jetpack_XMLRPC_Server $xmlrpc_server = null
939
	) {
940
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
941
942
		if ( ! $this->connection_manager ) {
943
			$this->connection_manager = new Connection_Manager();
944
		}
945
946
		return $this->connection_manager->setup_xmlrpc_handlers(
947
			$request_params,
948
			$is_active,
949
			$is_signed,
950
			$xmlrpc_server
951
		);
952
	}
953
954
	/**
955
	 * Initialize REST API registration connector.
956
	 *
957
	 * @deprecated since 7.7.0
958
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
959
	 */
960 View Code Duplication
	public function initialize_rest_api_registration_connector() {
961
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
962
963
		if ( ! $this->connection_manager ) {
964
			$this->connection_manager = new Connection_Manager();
965
		}
966
967
		$this->connection_manager->initialize_rest_api_registration_connector();
968
	}
969
970
	/**
971
	 * This is ported over from the manage module, which has been deprecated and baked in here.
972
	 *
973
	 * @param $domains
974
	 */
975
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
976
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
977
	}
978
979
	/**
980
	 * Return $domains, with 'wordpress.com' appended.
981
	 * This is ported over from the manage module, which has been deprecated and baked in here.
982
	 *
983
	 * @param $domains
984
	 * @return array
985
	 */
986
	function allow_wpcom_domain( $domains ) {
987
		if ( empty( $domains ) ) {
988
			$domains = array();
989
		}
990
		$domains[] = 'wordpress.com';
991
		return array_unique( $domains );
992
	}
993
994
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
995
		$post = get_post( $post_id );
996
997
		if ( empty( $post ) ) {
998
			return $default_url;
999
		}
1000
1001
		$post_type = $post->post_type;
1002
1003
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1004
		// https://en.support.wordpress.com/custom-post-types/
1005
		$allowed_post_types = array(
1006
			'post',
1007
			'page',
1008
			'jetpack-portfolio',
1009
			'jetpack-testimonial',
1010
		);
1011
1012
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1013
			return $default_url;
1014
		}
1015
1016
		return Redirect::get_url(
1017
			'calypso-edit-' . $post_type,
1018
			array(
1019
				'path' => $post_id,
1020
			)
1021
		);
1022
	}
1023
1024
	function point_edit_comment_links_to_calypso( $url ) {
1025
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1026
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
The variable $query_args does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

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