Completed
Push — add/userless-connection-flow ( a20a1f...6af410 )
by
unknown
09:50
created

Jetpack::get_module()   F

Complexity

Conditions 13
Paths 1025

Size

Total Lines 91

Duplication

Lines 12
Ratio 13.19 %

Importance

Changes 0
Metric Value
cc 13
nc 1025
nop 1
dl 12
loc 91
rs 2.1563
c 0
b 0
f 0

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3815
		if ( ! $token || is_wp_error( $token ) ) {
3816
			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...
3817
		}
3818
3819
		$uploaded_files = array();
3820
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3821
		unset( $GLOBALS['post'] );
3822
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3823
			$file = array();
3824
			foreach ( $media_keys as $media_key ) {
3825
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3826
			}
3827
3828
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3829
3830
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3831
			if ( $hmac_provided !== $hmac_file ) {
3832
				$uploaded_files[ $index ] = (object) array(
3833
					'error'             => 'invalid_hmac',
3834
					'error_description' => 'The corresponding HMAC for this file does not match',
3835
				);
3836
				continue;
3837
			}
3838
3839
			$_FILES['.jetpack.upload.'] = $file;
3840
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3841
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3842
				$post_id = 0;
3843
			}
3844
3845
			if ( $update_media_item ) {
3846
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3847
					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...
3848
				}
3849
3850
				$media_array = $_FILES['media'];
3851
3852
				$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...
3853
				$file_array['type']     = $media_array['type'][0];
3854
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3855
				$file_array['error']    = $media_array['error'][0];
3856
				$file_array['size']     = $media_array['size'][0];
3857
3858
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3859
3860
				if ( is_wp_error( $edited_media_item ) ) {
3861
					return $edited_media_item;
3862
				}
3863
3864
				$response = (object) array(
3865
					'id'   => (string) $post_id,
3866
					'file' => (string) $edited_media_item->post_title,
3867
					'url'  => (string) wp_get_attachment_url( $post_id ),
3868
					'type' => (string) $edited_media_item->post_mime_type,
3869
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3870
				);
3871
3872
				return (array) array( $response );
3873
			}
3874
3875
			$attachment_id = media_handle_upload(
3876
				'.jetpack.upload.',
3877
				$post_id,
3878
				array(),
3879
				array(
3880
					'action' => 'jetpack_upload_file',
3881
				)
3882
			);
3883
3884
			if ( ! $attachment_id ) {
3885
				$uploaded_files[ $index ] = (object) array(
3886
					'error'             => 'unknown',
3887
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3888
				);
3889
			} elseif ( is_wp_error( $attachment_id ) ) {
3890
				$uploaded_files[ $index ] = (object) array(
3891
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3892
					'error_description' => $attachment_id->get_error_message(),
3893
				);
3894
			} else {
3895
				$attachment               = get_post( $attachment_id );
3896
				$uploaded_files[ $index ] = (object) array(
3897
					'id'   => (string) $attachment_id,
3898
					'file' => $attachment->post_title,
3899
					'url'  => wp_get_attachment_url( $attachment_id ),
3900
					'type' => $attachment->post_mime_type,
3901
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3902
				);
3903
				// Zip files uploads are not supported unless they are done for installation purposed
3904
				// lets delete them in case something goes wrong in this whole process
3905
				if ( 'application/zip' === $attachment->post_mime_type ) {
3906
					// Schedule a cleanup for 2 hours from now in case of failed install.
3907
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3908
				}
3909
			}
3910
		}
3911
		if ( ! is_null( $global_post ) ) {
3912
			$GLOBALS['post'] = $global_post;
3913
		}
3914
3915
		return $uploaded_files;
3916
	}
3917
3918
	/**
3919
	 * Add help to the Jetpack page
3920
	 *
3921
	 * @since Jetpack (1.2.3)
3922
	 * @return false if not the Jetpack page
3923
	 */
3924
	function admin_help() {
3925
		$current_screen = get_current_screen();
3926
3927
		// Overview
3928
		$current_screen->add_help_tab(
3929
			array(
3930
				'id'      => 'home',
3931
				'title'   => __( 'Home', 'jetpack' ),
3932
				'content' =>
3933
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3934
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3935
					'<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>',
3936
			)
3937
		);
3938
3939
		// Screen Content
3940
		if ( current_user_can( 'manage_options' ) ) {
3941
			$current_screen->add_help_tab(
3942
				array(
3943
					'id'      => 'settings',
3944
					'title'   => __( 'Settings', 'jetpack' ),
3945
					'content' =>
3946
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3947
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3948
						'<ol>' .
3949
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3950
							'<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>' .
3951
						'</ol>' .
3952
						'<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>',
3953
				)
3954
			);
3955
		}
3956
3957
		// Help Sidebar
3958
		$support_url = Redirect::get_url( 'jetpack-support' );
3959
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3960
		$current_screen->set_help_sidebar(
3961
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3962
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3963
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3964
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3965
		);
3966
	}
3967
3968
	function admin_menu_css() {
3969
		wp_enqueue_style( 'jetpack-icons' );
3970
	}
3971
3972
	function admin_menu_order() {
3973
		return true;
3974
	}
3975
3976
	function jetpack_menu_order( $menu_order ) {
3977
		$jp_menu_order = array();
3978
3979
		foreach ( $menu_order as $index => $item ) {
3980
			if ( $item != 'jetpack' ) {
3981
				$jp_menu_order[] = $item;
3982
			}
3983
3984
			if ( $index == 0 ) {
3985
				$jp_menu_order[] = 'jetpack';
3986
			}
3987
		}
3988
3989
		return $jp_menu_order;
3990
	}
3991
3992
	function admin_banner_styles() {
3993
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3994
3995
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3996
			wp_register_style(
3997
				'jetpack-dops-style',
3998
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3999
				array(),
4000
				JETPACK__VERSION
4001
			);
4002
		}
4003
4004
		wp_enqueue_style(
4005
			'jetpack',
4006
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4007
			array( 'jetpack-dops-style' ),
4008
			JETPACK__VERSION . '-20121016'
4009
		);
4010
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4011
		wp_style_add_data( 'jetpack', 'suffix', $min );
4012
	}
4013
4014
	function plugin_action_links( $actions ) {
4015
4016
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4017
4018
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
4019
			return array_merge(
4020
				$jetpack_home,
4021
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4022
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4023
				$actions
4024
			);
4025
		}
4026
4027
		return array_merge( $jetpack_home, $actions );
4028
	}
4029
4030
	/**
4031
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4032
	 *
4033
	 * @param string $hook The current admin page.
4034
	 *
4035
	 * @return void
4036
	 */
4037
	public function deactivate_dialog( $hook ) {
4038
		if (
4039
			'plugins.php' === $hook
4040
			&& self::is_active()
4041
		) {
4042
4043
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4044
4045
			if ( count( $active_plugins_using_connection ) > 1 ) {
4046
4047
				add_thickbox();
4048
4049
				wp_register_script(
4050
					'jp-tracks',
4051
					'//stats.wp.com/w.js',
4052
					array(),
4053
					gmdate( 'YW' ),
4054
					true
4055
				);
4056
4057
				wp_register_script(
4058
					'jp-tracks-functions',
4059
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4060
					array( 'jp-tracks' ),
4061
					JETPACK__VERSION,
4062
					false
4063
				);
4064
4065
				wp_enqueue_script(
4066
					'jetpack-deactivate-dialog-js',
4067
					Assets::get_file_url_for_environment(
4068
						'_inc/build/jetpack-deactivate-dialog.min.js',
4069
						'_inc/jetpack-deactivate-dialog.js'
4070
					),
4071
					array( 'jquery', 'jp-tracks-functions' ),
4072
					JETPACK__VERSION,
4073
					true
4074
				);
4075
4076
				wp_localize_script(
4077
					'jetpack-deactivate-dialog-js',
4078
					'deactivate_dialog',
4079
					array(
4080
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4081
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4082
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4083
					)
4084
				);
4085
4086
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4087
4088
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4089
			}
4090
		}
4091
	}
4092
4093
	/**
4094
	 * Outputs the content of the deactivation modal
4095
	 *
4096
	 * @return void
4097
	 */
4098
	public function deactivate_dialog_content() {
4099
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4100
		unset( $active_plugins_using_connection['jetpack'] );
4101
		$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 4099 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...
4102
	}
4103
4104
	/**
4105
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4106
	 *
4107
	 * @param string $login_url The wp-login URL.
4108
	 * @param string $redirect  URL to redirect users after logging in.
4109
	 * @since Jetpack 8.4
4110
	 * @return string
4111
	 */
4112
	public function login_url( $login_url, $redirect ) {
4113
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4114
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4115
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4116
		}
4117
		return $login_url;
4118
	}
4119
4120
	/**
4121
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4122
	 *
4123
	 * @since Jetpack 8.4
4124
	 */
4125
	public function login_init() {
4126
		// phpcs:ignore WordPress.Security.NonceVerification
4127
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4128
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4129
			wp_safe_redirect(
4130
				add_query_arg(
4131
					array(
4132
						'forceInstall' => 1,
4133
						'url'          => rawurlencode( get_site_url() ),
4134
					),
4135
					// @todo provide way to go to specific calypso env.
4136
					self::get_calypso_host() . 'jetpack/connect'
4137
				)
4138
			);
4139
			exit;
4140
		}
4141
	}
4142
4143
	/*
4144
	 * Registration flow:
4145
	 * 1 - ::admin_page_load() action=register
4146
	 * 2 - ::try_registration()
4147
	 * 3 - ::register()
4148
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4149
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4150
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4151
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4152
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4153
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4154
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4155
	 *       jetpack_id, jetpack_secret, jetpack_public
4156
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4157
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4158
	 * 5 - user logs in with WP.com account
4159
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4160
	 *		- Manager::authorize()
4161
	 *		- Manager::get_token()
4162
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4163
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4164
	 *			- which responds with access_token, token_type, scope
4165
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4166
	 *		- Jetpack::activate_default_modules()
4167
	 *     		- Deactivates deprecated plugins
4168
	 *     		- Activates all default modules
4169
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4170
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4171
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4172
	 *     Done!
4173
	 */
4174
4175
	/**
4176
	 * Handles the page load events for the Jetpack admin page
4177
	 */
4178
	function admin_page_load() {
4179
		$error = false;
4180
4181
		// Make sure we have the right body class to hook stylings for subpages off of.
4182
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4183
4184
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4185
			// Should only be used in intermediate redirects to preserve state across redirects
4186
			self::restate();
4187
		}
4188
4189
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4190
			// @todo: Add validation against a known allowed list.
4191
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4192
			// User clicked in the iframe to link their accounts
4193
			if ( ! self::connection()->is_user_connected() ) {
4194
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4195
4196
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4197
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4198
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4199
4200
				if ( isset( $_GET['notes_iframe'] ) ) {
4201
					$connect_url .= '&notes_iframe';
4202
				}
4203
				wp_redirect( $connect_url );
4204
				exit;
4205
			} else {
4206
				if ( ! isset( $_GET['calypso_env'] ) ) {
4207
					self::state( 'message', 'already_authorized' );
4208
					wp_safe_redirect( self::admin_url() );
4209
					exit;
4210
				} else {
4211
					$connect_url  = $this->build_connect_url( true, false, $from );
4212
					$connect_url .= '&already_authorized=true';
4213
					wp_redirect( $connect_url );
4214
					exit;
4215
				}
4216
			}
4217
		}
4218
4219
		if ( isset( $_GET['action'] ) ) {
4220
			switch ( $_GET['action'] ) {
4221
				case 'authorize_redirect':
4222
					self::log( 'authorize_redirect' );
4223
4224
					add_filter(
4225
						'allowed_redirect_hosts',
4226
						function ( $domains ) {
4227
							$domains[] = 'jetpack.com';
4228
							$domains[] = 'jetpack.wordpress.com';
4229
							$domains[] = 'wordpress.com';
4230
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4231
							return array_unique( $domains );
4232
						}
4233
					);
4234
4235
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4236
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4237
4238
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4239
						// The destination URL is missing or invalid, nothing to do here.
4240
						exit;
4241
					}
4242
4243
					if ( static::is_active() && static::connection()->is_user_connected() ) {
4244
						// The user is either already connected, or finished the connection process.
4245
						wp_safe_redirect( $dest_url );
4246
						exit;
4247
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4248
						// The user decided not to proceed with setting up the connection.
4249
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4250
						exit;
4251
					}
4252
4253
					$redirect_url = self::admin_url(
4254
						array(
4255
							'page'     => 'jetpack',
4256
							'action'   => 'authorize_redirect',
4257
							'dest_url' => rawurlencode( $dest_url ),
4258
							'done'     => '1',
4259
						)
4260
					);
4261
4262
					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...
4263
					exit;
4264
				case 'authorize':
4265
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4266
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4267
					exit;
4268
				case 'register':
4269
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4270
						$error = 'cheatin';
4271
						break;
4272
					}
4273
					check_admin_referer( 'jetpack-register' );
4274
					self::log( 'register' );
4275
					self::maybe_set_version_option();
4276
					$registered = self::try_registration();
4277
					if ( is_wp_error( $registered ) ) {
4278
						$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...
4279
						self::state( 'error', $error );
4280
						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...
4281
4282
						/**
4283
						 * Jetpack registration Error.
4284
						 *
4285
						 * @since 7.5.0
4286
						 *
4287
						 * @param string|int $error The error code.
4288
						 * @param \WP_Error $registered The error object.
4289
						 */
4290
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4291
						break;
4292
					}
4293
4294
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4295
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4296
4297
					/**
4298
					 * Jetpack registration Success.
4299
					 *
4300
					 * @since 7.5.0
4301
					 *
4302
					 * @param string $from 'from' GET parameter;
4303
					 */
4304
					do_action( 'jetpack_connection_register_success', $from );
4305
4306
					$url = $this->build_connect_url( true, $redirect, $from );
4307
4308
					if ( ! empty( $_GET['onboarding'] ) ) {
4309
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4310
					}
4311
4312
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4313
						$url = add_query_arg( 'auth_approved', 'true', $url );
4314
					}
4315
4316
					wp_redirect( $url );
4317
					exit;
4318
				case 'activate':
4319
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4320
						$error = 'cheatin';
4321
						break;
4322
					}
4323
4324
					$module = stripslashes( $_GET['module'] );
4325
					check_admin_referer( "jetpack_activate-$module" );
4326
					self::log( 'activate', $module );
4327
					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...
4328
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4329
					}
4330
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4331
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4332
					exit;
4333
				case 'activate_default_modules':
4334
					check_admin_referer( 'activate_default_modules' );
4335
					self::log( 'activate_default_modules' );
4336
					self::restate();
4337
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4338
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4339
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4340
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4341
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4342
					exit;
4343
				case 'disconnect':
4344
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4345
						$error = 'cheatin';
4346
						break;
4347
					}
4348
4349
					check_admin_referer( 'jetpack-disconnect' );
4350
					self::log( 'disconnect' );
4351
					self::disconnect();
4352
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4353
					exit;
4354
				case 'reconnect':
4355
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4356
						$error = 'cheatin';
4357
						break;
4358
					}
4359
4360
					check_admin_referer( 'jetpack-reconnect' );
4361
					self::log( 'reconnect' );
4362
					$this->disconnect();
4363
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4364
					exit;
4365 View Code Duplication
				case 'deactivate':
4366
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4367
						$error = 'cheatin';
4368
						break;
4369
					}
4370
4371
					$modules = stripslashes( $_GET['module'] );
4372
					check_admin_referer( "jetpack_deactivate-$modules" );
4373
					foreach ( explode( ',', $modules ) as $module ) {
4374
						self::log( 'deactivate', $module );
4375
						self::deactivate_module( $module );
4376
						self::state( 'message', 'module_deactivated' );
4377
					}
4378
					self::state( 'module', $modules );
4379
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4380
					exit;
4381
				case 'unlink':
4382
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4383
					check_admin_referer( 'jetpack-unlink' );
4384
					self::log( 'unlink' );
4385
					Connection_Manager::disconnect_user();
4386
					self::state( 'message', 'unlinked' );
4387
					if ( 'sub-unlink' == $redirect ) {
4388
						wp_safe_redirect( admin_url() );
4389
					} else {
4390
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4391
					}
4392
					exit;
4393
				case 'onboard':
4394
					if ( ! current_user_can( 'manage_options' ) ) {
4395
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4396
					} else {
4397
						self::create_onboarding_token();
4398
						$url = $this->build_connect_url( true );
4399
4400
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4401
							$url = add_query_arg( 'onboarding', $token, $url );
4402
						}
4403
4404
						$calypso_env = $this->get_calypso_env();
4405
						if ( ! empty( $calypso_env ) ) {
4406
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4407
						}
4408
4409
						wp_redirect( $url );
4410
						exit;
4411
					}
4412
					exit;
4413
				default:
4414
					/**
4415
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4416
					 *
4417
					 * @since 2.6.0
4418
					 *
4419
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4420
					 */
4421
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4422
			}
4423
		}
4424
4425
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4426
			self::activate_new_modules( true );
4427
		}
4428
4429
		$message_code = self::state( 'message' );
4430
		if ( self::state( 'optin-manage' ) ) {
4431
			$activated_manage = $message_code;
4432
			$message_code     = 'jetpack-manage';
4433
		}
4434
4435
		switch ( $message_code ) {
4436
			case 'jetpack-manage':
4437
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4438
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4439
				$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>';
4440
				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...
4441
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4442
				}
4443
				break;
4444
4445
		}
4446
4447
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4448
4449
		if ( ! empty( $deactivated_plugins ) ) {
4450
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4451
			$deactivated_titles  = array();
4452
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4453
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4454
					continue;
4455
				}
4456
4457
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4458
			}
4459
4460
			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...
4461
				if ( $this->message ) {
4462
					$this->message .= "<br /><br />\n";
4463
				}
4464
4465
				$this->message .= wp_sprintf(
4466
					_n(
4467
						'Jetpack contains the most recent version of the old %l plugin.',
4468
						'Jetpack contains the most recent versions of the old %l plugins.',
4469
						count( $deactivated_titles ),
4470
						'jetpack'
4471
					),
4472
					$deactivated_titles
4473
				);
4474
4475
				$this->message .= "<br />\n";
4476
4477
				$this->message .= _n(
4478
					'The old version has been deactivated and can be removed from your site.',
4479
					'The old versions have been deactivated and can be removed from your site.',
4480
					count( $deactivated_titles ),
4481
					'jetpack'
4482
				);
4483
			}
4484
		}
4485
4486
		$this->privacy_checks = self::state( 'privacy_checks' );
4487
4488
		if ( $this->message || $this->error || $this->privacy_checks ) {
4489
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4490
		}
4491
4492
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4493
	}
4494
4495
	function admin_notices() {
4496
4497
		if ( $this->error ) {
4498
			?>
4499
<div id="message" class="jetpack-message jetpack-err">
4500
	<div class="squeezer">
4501
		<h2>
4502
			<?php
4503
			echo wp_kses(
4504
				$this->error,
4505
				array(
4506
					'a'      => array( 'href' => array() ),
4507
					'small'  => true,
4508
					'code'   => true,
4509
					'strong' => true,
4510
					'br'     => true,
4511
					'b'      => true,
4512
				)
4513
			);
4514
			?>
4515
			</h2>
4516
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4517
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4518
<?php	endif; ?>
4519
	</div>
4520
</div>
4521
			<?php
4522
		}
4523
4524
		if ( $this->message ) {
4525
			?>
4526
<div id="message" class="jetpack-message">
4527
	<div class="squeezer">
4528
		<h2>
4529
			<?php
4530
			echo wp_kses(
4531
				$this->message,
4532
				array(
4533
					'strong' => array(),
4534
					'a'      => array( 'href' => true ),
4535
					'br'     => true,
4536
				)
4537
			);
4538
			?>
4539
			</h2>
4540
	</div>
4541
</div>
4542
			<?php
4543
		}
4544
4545
		if ( $this->privacy_checks ) :
4546
			$module_names = $module_slugs = array();
4547
4548
			$privacy_checks = explode( ',', $this->privacy_checks );
4549
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4550
			foreach ( $privacy_checks as $module_slug ) {
4551
				$module = self::get_module( $module_slug );
4552
				if ( ! $module ) {
4553
					continue;
4554
				}
4555
4556
				$module_slugs[] = $module_slug;
4557
				$module_names[] = "<strong>{$module['name']}</strong>";
4558
			}
4559
4560
			$module_slugs = join( ',', $module_slugs );
4561
			?>
4562
<div id="message" class="jetpack-message jetpack-err">
4563
	<div class="squeezer">
4564
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4565
		<p>
4566
			<?php
4567
			echo wp_kses(
4568
				wptexturize(
4569
					wp_sprintf(
4570
						_nx(
4571
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4572
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4573
							count( $privacy_checks ),
4574
							'%l = list of Jetpack module/feature names',
4575
							'jetpack'
4576
						),
4577
						$module_names
4578
					)
4579
				),
4580
				array( 'strong' => true )
4581
			);
4582
4583
			echo "\n<br />\n";
4584
4585
			echo wp_kses(
4586
				sprintf(
4587
					_nx(
4588
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4589
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4590
						count( $privacy_checks ),
4591
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4592
						'jetpack'
4593
					),
4594
					wp_nonce_url(
4595
						self::admin_url(
4596
							array(
4597
								'page'   => 'jetpack',
4598
								'action' => 'deactivate',
4599
								'module' => urlencode( $module_slugs ),
4600
							)
4601
						),
4602
						"jetpack_deactivate-$module_slugs"
4603
					),
4604
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4605
				),
4606
				array(
4607
					'a' => array(
4608
						'href'  => true,
4609
						'title' => true,
4610
					),
4611
				)
4612
			);
4613
			?>
4614
		</p>
4615
	</div>
4616
</div>
4617
			<?php
4618
endif;
4619
	}
4620
4621
	/**
4622
	 * We can't always respond to a signed XML-RPC request with a
4623
	 * helpful error message. In some circumstances, doing so could
4624
	 * leak information.
4625
	 *
4626
	 * Instead, track that the error occurred via a Jetpack_Option,
4627
	 * and send that data back in the heartbeat.
4628
	 * All this does is increment a number, but it's enough to find
4629
	 * trends.
4630
	 *
4631
	 * @param WP_Error $xmlrpc_error The error produced during
4632
	 *                               signature validation.
4633
	 */
4634
	function track_xmlrpc_error( $xmlrpc_error ) {
4635
		$code = is_wp_error( $xmlrpc_error )
4636
			? $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...
4637
			: 'should-not-happen';
4638
4639
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4640
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4641
			// No need to update the option if we already have
4642
			// this code stored.
4643
			return;
4644
		}
4645
		$xmlrpc_errors[ $code ] = true;
4646
4647
		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...
4648
	}
4649
4650
	/**
4651
	 * Initialize the jetpack stats instance only when needed
4652
	 *
4653
	 * @return void
4654
	 */
4655
	private function initialize_stats() {
4656
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4657
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4658
		}
4659
	}
4660
4661
	/**
4662
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4663
	 */
4664
	function stat( $group, $detail ) {
4665
		$this->initialize_stats();
4666
		$this->a8c_mc_stats_instance->add( $group, $detail );
4667
4668
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4669
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4670
	}
4671
4672
	/**
4673
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4674
	 */
4675
	function do_stats( $method = '' ) {
4676
		$this->initialize_stats();
4677
		if ( 'server_side' === $method ) {
4678
			$this->a8c_mc_stats_instance->do_server_side_stats();
4679
		} else {
4680
			$this->a8c_mc_stats_instance->do_stats();
4681
		}
4682
4683
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4684
		$this->stats = array();
4685
	}
4686
4687
	/**
4688
	 * Runs stats code for a one-off, server-side.
4689
	 *
4690
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4691
	 *
4692
	 * @return bool If it worked.
4693
	 */
4694
	static function do_server_side_stat( $args ) {
4695
		$url                   = self::build_stats_url( $args );
4696
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4697
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4698
	}
4699
4700
	/**
4701
	 * Builds the stats url.
4702
	 *
4703
	 * @param $args array|string The arguments to append to the URL.
4704
	 *
4705
	 * @return string The URL to be pinged.
4706
	 */
4707
	static function build_stats_url( $args ) {
4708
4709
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4710
		return $a8c_mc_stats_instance->build_stats_url( $args );
4711
4712
	}
4713
4714
	/**
4715
	 * Get the role of the current user.
4716
	 *
4717
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4718
	 *
4719
	 * @access public
4720
	 * @static
4721
	 *
4722
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4723
	 */
4724
	public static function translate_current_user_to_role() {
4725
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4726
4727
		$roles = new Roles();
4728
		return $roles->translate_current_user_to_role();
4729
	}
4730
4731
	/**
4732
	 * Get the role of a particular user.
4733
	 *
4734
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4735
	 *
4736
	 * @access public
4737
	 * @static
4738
	 *
4739
	 * @param \WP_User $user User object.
4740
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4741
	 */
4742
	public static function translate_user_to_role( $user ) {
4743
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4744
4745
		$roles = new Roles();
4746
		return $roles->translate_user_to_role( $user );
4747
	}
4748
4749
	/**
4750
	 * Get the minimum capability for a role.
4751
	 *
4752
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4753
	 *
4754
	 * @access public
4755
	 * @static
4756
	 *
4757
	 * @param string $role Role name.
4758
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4759
	 */
4760
	public static function translate_role_to_cap( $role ) {
4761
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4762
4763
		$roles = new Roles();
4764
		return $roles->translate_role_to_cap( $role );
4765
	}
4766
4767
	/**
4768
	 * Sign a user role with the master access token.
4769
	 * If not specified, will default to the current user.
4770
	 *
4771
	 * @deprecated since 7.7
4772
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4773
	 *
4774
	 * @access public
4775
	 * @static
4776
	 *
4777
	 * @param string $role    User role.
4778
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|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...
4779
	 * @return string Signed user role.
4780
	 */
4781
	public static function sign_role( $role, $user_id = null ) {
4782
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4783
		return self::connection()->sign_role( $role, $user_id );
4784
	}
4785
4786
	/**
4787
	 * Builds a URL to the Jetpack connection auth page
4788
	 *
4789
	 * @since 3.9.5
4790
	 *
4791
	 * @param bool        $raw If true, URL will not be escaped.
4792
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4793
	 *                              If string, will be a custom redirect.
4794
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4795
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4796
	 *
4797
	 * @return string Connect URL
4798
	 */
4799
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4800
		$site_id    = Jetpack_Options::get_option( 'id' );
4801
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4802
4803
		if ( $register || ! $blog_token || ! $site_id ) {
4804
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4805
4806
			if ( ! empty( $redirect ) ) {
4807
				$url = add_query_arg(
4808
					'redirect',
4809
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4810
					$url
4811
				);
4812
			}
4813
4814
			if ( is_network_admin() ) {
4815
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4816
			}
4817
4818
			$calypso_env = self::get_calypso_env();
4819
4820
			if ( ! empty( $calypso_env ) ) {
4821
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4822
			}
4823
		} else {
4824
4825
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4826
			// because otherwise this logic can get us in to a loop.
4827
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4828
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4829
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4830
4831
				$response = Client::wpcom_json_api_request_as_blog(
4832
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4833
					'1.1'
4834
				);
4835
4836
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4837
4838
					// Generating a register URL instead to refresh the existing token
4839
					return $this->build_connect_url( $raw, $redirect, $from, true );
4840
				}
4841
			}
4842
4843
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4799 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...
4844
		}
4845
4846
		if ( $from ) {
4847
			$url = add_query_arg( 'from', $from, $url );
4848
		}
4849
4850
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4851
		/**
4852
		 * Filter the URL used when connecting a user to a WordPress.com account.
4853
		 *
4854
		 * @since 8.1.0
4855
		 *
4856
		 * @param string $url Connection URL.
4857
		 * @param bool   $raw If true, URL will not be escaped.
4858
		 */
4859
		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...
4860
	}
4861
4862
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4863
4864
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4865
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4866
4867
		if ( $iframe ) {
4868
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4869
		}
4870
4871
		$c8n = self::connection();
4872
		$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...
4873
4874
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4875
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4876
4877
		if ( $iframe ) {
4878
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4879
		}
4880
4881
		/**
4882
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4883
		 *
4884
		 * @since 8.9.0
4885
		 *
4886
		 * @param string $url Connection URL.
4887
		 */
4888
		return apply_filters( 'jetpack_build_authorize_url', $url );
4889
	}
4890
4891
	/**
4892
	 * Filters the connection URL parameter array.
4893
	 *
4894
	 * @param array $args default URL parameters used by the package.
4895
	 * @return array the modified URL arguments array.
4896
	 */
4897
	public static function filter_connect_request_body( $args ) {
4898
		if (
4899
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4900
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4901
		) {
4902
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4903
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4904
				? $gp_locale->slug
4905
				: '';
4906
		}
4907
4908
		$tracking        = new Tracking();
4909
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4910
4911
		$args = array_merge(
4912
			$args,
4913
			array(
4914
				'_ui' => $tracks_identity['_ui'],
4915
				'_ut' => $tracks_identity['_ut'],
4916
			)
4917
		);
4918
4919
		$calypso_env = self::get_calypso_env();
4920
4921
		if ( ! empty( $calypso_env ) ) {
4922
			$args['calypso_env'] = $calypso_env;
4923
		}
4924
4925
		return $args;
4926
	}
4927
4928
	/**
4929
	 * Filters the URL that will process the connection data. It can be different from the URL
4930
	 * that we send the user to after everything is done.
4931
	 *
4932
	 * @param String $processing_url the default redirect URL used by the package.
4933
	 * @return String the modified URL.
4934
	 *
4935
	 * @deprecated since Jetpack 9.5.0
4936
	 */
4937
	public static function filter_connect_processing_url( $processing_url ) {
4938
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4939
4940
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4941
		return $processing_url;
4942
	}
4943
4944
	/**
4945
	 * Filters the redirection URL that is used for connect requests. The redirect
4946
	 * URL should return the user back to the Jetpack console.
4947
	 *
4948
	 * @param String $redirect the default redirect URL used by the package.
4949
	 * @return String the modified URL.
4950
	 */
4951
	public static function filter_connect_redirect_url( $redirect ) {
4952
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4953
		$redirect           = $redirect
4954
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4955
			: $jetpack_admin_page;
4956
4957
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4958
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4959
		}
4960
4961
		return $redirect;
4962
	}
4963
4964
	/**
4965
	 * This action fires at the beginning of the Manager::authorize method.
4966
	 */
4967
	public static function authorize_starting() {
4968
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4969
		// Checking if site has been active/connected previously before recording unique connection.
4970
		if ( ! $jetpack_unique_connection ) {
4971
			// jetpack_unique_connection option has never been set.
4972
			$jetpack_unique_connection = array(
4973
				'connected'    => 0,
4974
				'disconnected' => 0,
4975
				'version'      => '3.6.1',
4976
			);
4977
4978
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4979
4980
			// Track unique connection.
4981
			$jetpack = self::init();
4982
4983
			$jetpack->stat( 'connections', 'unique-connection' );
4984
			$jetpack->do_stats( 'server_side' );
4985
		}
4986
4987
		// Increment number of times connected.
4988
		$jetpack_unique_connection['connected'] += 1;
4989
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4990
	}
4991
4992
	/**
4993
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4994
	 * linked.
4995
	 */
4996
	public static function authorize_ending_linked() {
4997
		// Don't activate anything since we are just connecting a user.
4998
		self::state( 'message', 'linked' );
4999
	}
5000
5001
	/**
5002
	 * This action fires at the end of the Manager::authorize method when the master user is
5003
	 * authorized.
5004
	 *
5005
	 * @param array $data The request data.
5006
	 */
5007
	public static function authorize_ending_authorized( $data ) {
5008
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5009
		self::invalidate_onboarding_token();
5010
5011
		// If redirect_uri is SSO, ensure SSO module is enabled.
5012
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5013
5014
		/** This filter is documented in class.jetpack-cli.php */
5015
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5016
5017
		$activate_sso = (
5018
			isset( $redirect_options['action'] ) &&
5019
			'jetpack-sso' === $redirect_options['action'] &&
5020
			$jetpack_start_enable_sso
5021
		);
5022
5023
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5024
5025
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5026
	}
5027
5028
	/**
5029
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5030
	 * reconnect process is completed.
5031
	 * Note that this currently only happens when we don't need the user to re-authorize
5032
	 * their WP.com account, eg in cases where we are restoring a connection with
5033
	 * unhealthy blog token.
5034
	 */
5035
	public static function reconnection_completed() {
5036
		self::state( 'message', 'reconnection_completed' );
5037
	}
5038
5039
	/**
5040
	 * Get our assumed site creation date.
5041
	 * Calculated based on the earlier date of either:
5042
	 * - Earliest admin user registration date.
5043
	 * - Earliest date of post of any post type.
5044
	 *
5045
	 * @since 7.2.0
5046
	 * @deprecated since 7.8.0
5047
	 *
5048
	 * @return string Assumed site creation date and time.
5049
	 */
5050
	public static function get_assumed_site_creation_date() {
5051
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5052
		return self::connection()->get_assumed_site_creation_date();
5053
	}
5054
5055 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5056
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5057
5058
		if ( $activation_source_name ) {
5059
			$args['_as'] = urlencode( $activation_source_name );
5060
		}
5061
5062
		if ( $activation_source_keyword ) {
5063
			$args['_ak'] = urlencode( $activation_source_keyword );
5064
		}
5065
	}
5066
5067
	function build_reconnect_url( $raw = false ) {
5068
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5069
		return $raw ? $url : esc_url( $url );
5070
	}
5071
5072
	public static function admin_url( $args = null ) {
5073
		$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...
5074
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5075
		return $url;
5076
	}
5077
5078
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5079
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5080
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5081
	}
5082
5083
	function dismiss_jetpack_notice() {
5084
5085
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5086
			return;
5087
		}
5088
5089
		switch ( $_GET['jetpack-notice'] ) {
5090
			case 'dismiss':
5091
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5092
5093
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5094
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5095
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5096
				}
5097
				break;
5098
		}
5099
	}
5100
5101
	public static function sort_modules( $a, $b ) {
5102
		if ( $a['sort'] == $b['sort'] ) {
5103
			return 0;
5104
		}
5105
5106
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5107
	}
5108
5109
	function ajax_recheck_ssl() {
5110
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5111
		$result = self::permit_ssl( true );
5112
		wp_send_json(
5113
			array(
5114
				'enabled' => $result,
5115
				'message' => get_transient( 'jetpack_https_test_message' ),
5116
			)
5117
		);
5118
	}
5119
5120
	/* Client API */
5121
5122
	/**
5123
	 * Returns the requested Jetpack API URL
5124
	 *
5125
	 * @deprecated since 7.7
5126
	 * @return string
5127
	 */
5128
	public static function api_url( $relative_url ) {
5129
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5130
		$connection = self::connection();
5131
		return $connection->api_url( $relative_url );
5132
	}
5133
5134
	/**
5135
	 * @deprecated 8.0
5136
	 *
5137
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5138
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5139
	 */
5140
	public static function fix_url_for_bad_hosts( $url ) {
5141
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5142
		return $url;
5143
	}
5144
5145
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5146
		// Default to a blog token.
5147
		$token_type = 'blog';
5148
5149
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5150
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5151
			if ( ! empty( $_GET['onboarding'] ) ) {
5152
				$jpo = $_GET;
5153
			} else {
5154
				$jpo = json_decode( $request_data, true );
5155
			}
5156
5157
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5158
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5159
5160
			if (
5161
				isset( $jpo_user )
5162
				&& isset( $jpo_token )
5163
				&& is_email( $jpo_user )
5164
				&& ctype_alnum( $jpo_token )
5165
				&& isset( $_GET['rest_route'] )
5166
				&& self::validate_onboarding_token_action(
5167
					$jpo_token,
5168
					$_GET['rest_route']
5169
				)
5170
			) {
5171
				$jp_user = get_user_by( 'email', $jpo_user );
5172
				if ( is_a( $jp_user, 'WP_User' ) ) {
5173
					wp_set_current_user( $jp_user->ID );
5174
					$user_can = is_multisite()
5175
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5176
						: current_user_can( 'manage_options' );
5177
					if ( $user_can ) {
5178
						$token_type              = 'user';
5179
						$token->external_user_id = $jp_user->ID;
5180
					}
5181
				}
5182
			}
5183
5184
			$token_data['type']    = $token_type;
5185
			$token_data['user_id'] = $token->external_user_id;
5186
		}
5187
5188
		return $token_data;
5189
	}
5190
5191
	/**
5192
	 * Create a random secret for validating onboarding payload
5193
	 *
5194
	 * @return string Secret token
5195
	 */
5196
	public static function create_onboarding_token() {
5197
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5198
			$token = wp_generate_password( 32, false );
5199
			Jetpack_Options::update_option( 'onboarding', $token );
5200
		}
5201
5202
		return $token;
5203
	}
5204
5205
	/**
5206
	 * Remove the onboarding token
5207
	 *
5208
	 * @return bool True on success, false on failure
5209
	 */
5210
	public static function invalidate_onboarding_token() {
5211
		return Jetpack_Options::delete_option( 'onboarding' );
5212
	}
5213
5214
	/**
5215
	 * Validate an onboarding token for a specific action
5216
	 *
5217
	 * @return boolean True if token/action pair is accepted, false if not
5218
	 */
5219
	public static function validate_onboarding_token_action( $token, $action ) {
5220
		// Compare tokens, bail if tokens do not match
5221
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5222
			return false;
5223
		}
5224
5225
		// List of valid actions we can take
5226
		$valid_actions = array(
5227
			'/jetpack/v4/settings',
5228
		);
5229
5230
		// Only allow valid actions.
5231
		if ( ! in_array( $action, $valid_actions ) ) {
5232
			return false;
5233
		}
5234
5235
		return true;
5236
	}
5237
5238
	/**
5239
	 * Checks to see if the URL is using SSL to connect with Jetpack
5240
	 *
5241
	 * @since 2.3.3
5242
	 * @return boolean
5243
	 */
5244
	public static function permit_ssl( $force_recheck = false ) {
5245
		// Do some fancy tests to see if ssl is being supported
5246
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5247
			$message = '';
5248
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5249
				$ssl = 0;
5250
			} else {
5251
				$ssl = 1;
5252
5253
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5254
					$ssl     = 0;
5255
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5256
				} else {
5257
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5258
					if ( is_wp_error( $response ) ) {
5259
						$ssl     = 0;
5260
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5261
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5262
						$ssl     = 0;
5263
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5264
					}
5265
				}
5266
			}
5267
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5268
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5269
		}
5270
5271
		return (bool) $ssl;
5272
	}
5273
5274
	/*
5275
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5276
	 */
5277
	public function alert_auto_ssl_fail() {
5278
		if ( ! current_user_can( 'manage_options' ) ) {
5279
			return;
5280
		}
5281
5282
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5283
		?>
5284
5285
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5286
			<div class="jp-banner__content">
5287
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5288
				<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>
5289
				<p>
5290
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5291
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5292
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5293
				</p>
5294
				<p>
5295
					<?php
5296
					printf(
5297
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5298
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5299
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5300
					);
5301
					?>
5302
				</p>
5303
			</div>
5304
		</div>
5305
		<style>
5306
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5307
		</style>
5308
		<script type="text/javascript">
5309
			jQuery( document ).ready( function( $ ) {
5310
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5311
					var $this = $( this );
5312
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5313
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5314
					e.preventDefault();
5315
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5316
					$.post( ajaxurl, data )
5317
					  .done( function( response ) {
5318
						  if ( response.enabled ) {
5319
							  $( '#jetpack-ssl-warning' ).hide();
5320
						  } else {
5321
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5322
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5323
						  }
5324
					  }.bind( $this ) );
5325
				} );
5326
			} );
5327
		</script>
5328
5329
		<?php
5330
	}
5331
5332
	/**
5333
	 * Returns the Jetpack XML-RPC API
5334
	 *
5335
	 * @deprecated 8.0 Use Connection_Manager instead.
5336
	 * @return string
5337
	 */
5338
	public static function xmlrpc_api_url() {
5339
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5340
		return self::connection()->xmlrpc_api_url();
5341
	}
5342
5343
	/**
5344
	 * Returns the connection manager object.
5345
	 *
5346
	 * @return Automattic\Jetpack\Connection\Manager
5347
	 */
5348
	public static function connection() {
5349
		$jetpack = static::init();
5350
5351
		// If the connection manager hasn't been instantiated, do that now.
5352
		if ( ! $jetpack->connection_manager ) {
5353
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5354
		}
5355
5356
		return $jetpack->connection_manager;
5357
	}
5358
5359
	/**
5360
	 * Creates two secret tokens and the end of life timestamp for them.
5361
	 *
5362
	 * Note these tokens are unique per call, NOT static per site for connecting.
5363
	 *
5364
	 * @since 2.6
5365
	 * @param String  $action  The action name.
5366
	 * @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...
5367
	 * @param Integer $exp     Expiration time in seconds.
5368
	 * @return array
5369
	 */
5370
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5371
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5372
	}
5373
5374
	public static function get_secrets( $action, $user_id ) {
5375
		$secrets = self::connection()->get_secrets( $action, $user_id );
5376
5377
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5378
			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...
5379
		}
5380
5381
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5382
			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...
5383
		}
5384
5385
		return $secrets;
5386
	}
5387
5388
	/**
5389
	 * @deprecated 7.5 Use Connection_Manager instead.
5390
	 *
5391
	 * @param $action
5392
	 * @param $user_id
5393
	 */
5394
	public static function delete_secrets( $action, $user_id ) {
5395
		return self::connection()->delete_secrets( $action, $user_id );
5396
	}
5397
5398
	/**
5399
	 * Builds the timeout limit for queries talking with the wpcom servers.
5400
	 *
5401
	 * Based on local php max_execution_time in php.ini
5402
	 *
5403
	 * @since 2.6
5404
	 * @return int
5405
	 * @deprecated
5406
	 **/
5407
	public function get_remote_query_timeout_limit() {
5408
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5409
		return self::get_max_execution_time();
5410
	}
5411
5412
	/**
5413
	 * Builds the timeout limit for queries talking with the wpcom servers.
5414
	 *
5415
	 * Based on local php max_execution_time in php.ini
5416
	 *
5417
	 * @since 5.4
5418
	 * @return int
5419
	 **/
5420
	public static function get_max_execution_time() {
5421
		$timeout = (int) ini_get( 'max_execution_time' );
5422
5423
		// Ensure exec time set in php.ini
5424
		if ( ! $timeout ) {
5425
			$timeout = 30;
5426
		}
5427
		return $timeout;
5428
	}
5429
5430
	/**
5431
	 * Sets a minimum request timeout, and returns the current timeout
5432
	 *
5433
	 * @since 5.4
5434
	 **/
5435 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5436
		$timeout = self::get_max_execution_time();
5437
		if ( $timeout < $min_timeout ) {
5438
			$timeout = $min_timeout;
5439
			set_time_limit( $timeout );
5440
		}
5441
		return $timeout;
5442
	}
5443
5444
	/**
5445
	 * Takes the response from the Jetpack register new site endpoint and
5446
	 * verifies it worked properly.
5447
	 *
5448
	 * @since 2.6
5449
	 * @deprecated since 7.7.0
5450
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5451
	 **/
5452
	public function validate_remote_register_response() {
5453
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5454
	}
5455
5456
	/**
5457
	 * @return bool|WP_Error
5458
	 */
5459
	public static function register() {
5460
		$tracking = new Tracking();
5461
		$tracking->record_user_event( 'jpc_register_begin' );
5462
5463
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5464
5465
		$connection   = self::connection();
5466
		$registration = $connection->register();
5467
5468
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5469
5470
		if ( ! $registration || is_wp_error( $registration ) ) {
5471
			return $registration;
5472
		}
5473
5474
		return true;
5475
	}
5476
5477
	/**
5478
	 * Filters the registration request body to include tracking properties.
5479
	 *
5480
	 * @param array $properties
5481
	 * @return array amended properties.
5482
	 */
5483 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5484
		$tracking        = new Tracking();
5485
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5486
5487
		return array_merge(
5488
			$properties,
5489
			array(
5490
				'_ui' => $tracks_identity['_ui'],
5491
				'_ut' => $tracks_identity['_ut'],
5492
			)
5493
		);
5494
	}
5495
5496
	/**
5497
	 * Filters the token request body to include tracking properties.
5498
	 *
5499
	 * @param array $properties
5500
	 * @return array amended properties.
5501
	 */
5502 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5503
		$tracking        = new Tracking();
5504
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5505
5506
		return array_merge(
5507
			$properties,
5508
			array(
5509
				'_ui' => $tracks_identity['_ui'],
5510
				'_ut' => $tracks_identity['_ut'],
5511
			)
5512
		);
5513
	}
5514
5515
	/**
5516
	 * If the db version is showing something other that what we've got now, bump it to current.
5517
	 *
5518
	 * @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...
5519
	 */
5520
	public static function maybe_set_version_option() {
5521
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5522
		if ( JETPACK__VERSION != $version ) {
5523
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5524
5525
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5526
				/** This action is documented in class.jetpack.php */
5527
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5528
			}
5529
5530
			return true;
5531
		}
5532
		return false;
5533
	}
5534
5535
	/* Client Server API */
5536
5537
	/**
5538
	 * Loads the Jetpack XML-RPC client.
5539
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5540
	 *
5541
	 * @deprecated since 7.7.0
5542
	 */
5543
	public static function load_xml_rpc_client() {
5544
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5545
	}
5546
5547
	/**
5548
	 * Resets the saved authentication state in between testing requests.
5549
	 *
5550
	 * @deprecated since 8.9.0
5551
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5552
	 */
5553
	public function reset_saved_auth_state() {
5554
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5555
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5556
	}
5557
5558
	/**
5559
	 * Verifies the signature of the current request.
5560
	 *
5561
	 * @deprecated since 7.7.0
5562
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5563
	 *
5564
	 * @return false|array
5565
	 */
5566
	public function verify_xml_rpc_signature() {
5567
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5568
		return self::connection()->verify_xml_rpc_signature();
5569
	}
5570
5571
	/**
5572
	 * Verifies the signature of the current request.
5573
	 *
5574
	 * This function has side effects and should not be used. Instead,
5575
	 * use the memoized version `->verify_xml_rpc_signature()`.
5576
	 *
5577
	 * @deprecated since 7.7.0
5578
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5579
	 * @internal
5580
	 */
5581
	private function internal_verify_xml_rpc_signature() {
5582
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5583
	}
5584
5585
	/**
5586
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5587
	 *
5588
	 * @deprecated since 7.7.0
5589
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5590
	 *
5591
	 * @param \WP_User|mixed $user     User object if authenticated.
5592
	 * @param string         $username Username.
5593
	 * @param string         $password Password string.
5594
	 * @return \WP_User|mixed Authenticated user or error.
5595
	 */
5596 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5597
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5598
5599
		if ( ! $this->connection_manager ) {
5600
			$this->connection_manager = new Connection_Manager();
5601
		}
5602
5603
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5604
	}
5605
5606
	/**
5607
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5608
	 * Uses the existing XMLRPC request signing implementation.
5609
	 *
5610
	 * @deprecated since 8.9.0
5611
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5612
	 */
5613
	function wp_rest_authenticate( $user ) {
5614
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5615
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5616
	}
5617
5618
	/**
5619
	 * Report authentication status to the WP REST API.
5620
	 *
5621
	 * @deprecated since 8.9.0
5622
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5623
	 *
5624
	 * @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...
5625
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5626
	 */
5627
	public function wp_rest_authentication_errors( $value ) {
5628
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5629
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5630
	}
5631
5632
	/**
5633
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5634
	 * Capture it here so we can verify the signature later.
5635
	 *
5636
	 * @deprecated since 7.7.0
5637
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5638
	 *
5639
	 * @param array $methods XMLRPC methods.
5640
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5641
	 */
5642 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5643
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5644
5645
		if ( ! $this->connection_manager ) {
5646
			$this->connection_manager = new Connection_Manager();
5647
		}
5648
5649
		return $this->connection_manager->xmlrpc_methods( $methods );
5650
	}
5651
5652
	/**
5653
	 * Register additional public XMLRPC methods.
5654
	 *
5655
	 * @deprecated since 7.7.0
5656
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5657
	 *
5658
	 * @param array $methods Public XMLRPC methods.
5659
	 * @return array Public XMLRPC methods, with the getOptions one.
5660
	 */
5661 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5662
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5663
5664
		if ( ! $this->connection_manager ) {
5665
			$this->connection_manager = new Connection_Manager();
5666
		}
5667
5668
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5669
	}
5670
5671
	/**
5672
	 * Handles a getOptions XMLRPC method call.
5673
	 *
5674
	 * @deprecated since 7.7.0
5675
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5676
	 *
5677
	 * @param array $args method call arguments.
5678
	 * @return array an amended XMLRPC server options array.
5679
	 */
5680 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5681
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5682
5683
		if ( ! $this->connection_manager ) {
5684
			$this->connection_manager = new Connection_Manager();
5685
		}
5686
5687
		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...
5688
	}
5689
5690
	/**
5691
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5692
	 *
5693
	 * @deprecated since 7.7.0
5694
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5695
	 *
5696
	 * @param array $options Standard Core options.
5697
	 * @return array Amended options.
5698
	 */
5699 View Code Duplication
	public function xmlrpc_options( $options ) {
5700
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5701
5702
		if ( ! $this->connection_manager ) {
5703
			$this->connection_manager = new Connection_Manager();
5704
		}
5705
5706
		return $this->connection_manager->xmlrpc_options( $options );
5707
	}
5708
5709
	/**
5710
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5711
	 * SET: state( $key, $value );
5712
	 * GET: $value = state( $key );
5713
	 *
5714
	 * @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...
5715
	 * @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...
5716
	 * @param bool   $restate private
5717
	 */
5718
	public static function state( $key = null, $value = null, $restate = false ) {
5719
		static $state = array();
5720
		static $path, $domain;
5721
		if ( ! isset( $path ) ) {
5722
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5723
			$admin_url = self::admin_url();
5724
			$bits      = wp_parse_url( $admin_url );
5725
5726
			if ( is_array( $bits ) ) {
5727
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5728
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5729
			} else {
5730
				$path = $domain = null;
5731
			}
5732
		}
5733
5734
		// Extract state from cookies and delete cookies
5735
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5736
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5737
			unset( $_COOKIE['jetpackState'] );
5738
			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...
5739
				if ( strlen( $v ) ) {
5740
					$state[ $k ] = $v;
5741
				}
5742
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5743
			}
5744
		}
5745
5746
		if ( $restate ) {
5747
			foreach ( $state as $k => $v ) {
5748
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5749
			}
5750
			return;
5751
		}
5752
5753
		// Get a state variable.
5754
		if ( isset( $key ) && ! isset( $value ) ) {
5755
			if ( array_key_exists( $key, $state ) ) {
5756
				return $state[ $key ];
5757
			}
5758
			return null;
5759
		}
5760
5761
		// Set a state variable.
5762
		if ( isset( $key ) && isset( $value ) ) {
5763
			if ( is_array( $value ) && isset( $value[0] ) ) {
5764
				$value = $value[0];
5765
			}
5766
			$state[ $key ] = $value;
5767
			if ( ! headers_sent() ) {
5768
				if ( self::should_set_cookie( $key ) ) {
5769
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5770
				}
5771
			}
5772
		}
5773
	}
5774
5775
	public static function restate() {
5776
		self::state( null, null, true );
5777
	}
5778
5779
	/**
5780
	 * Determines whether the jetpackState[$key] value should be added to the
5781
	 * cookie.
5782
	 *
5783
	 * @param string $key The state key.
5784
	 *
5785
	 * @return boolean Whether the value should be added to the cookie.
5786
	 */
5787
	public static function should_set_cookie( $key ) {
5788
		global $current_screen;
5789
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5790
5791
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5792
			return false;
5793
		}
5794
5795
		return true;
5796
	}
5797
5798
	public static function check_privacy( $file ) {
5799
		static $is_site_publicly_accessible = null;
5800
5801
		if ( is_null( $is_site_publicly_accessible ) ) {
5802
			$is_site_publicly_accessible = false;
5803
5804
			$rpc = new Jetpack_IXR_Client();
5805
5806
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5807
			if ( $success ) {
5808
				$response = $rpc->getResponse();
5809
				if ( $response ) {
5810
					$is_site_publicly_accessible = true;
5811
				}
5812
			}
5813
5814
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5815
		}
5816
5817
		if ( $is_site_publicly_accessible ) {
5818
			return;
5819
		}
5820
5821
		$module_slug = self::get_module_slug( $file );
5822
5823
		$privacy_checks = self::state( 'privacy_checks' );
5824
		if ( ! $privacy_checks ) {
5825
			$privacy_checks = $module_slug;
5826
		} else {
5827
			$privacy_checks .= ",$module_slug";
5828
		}
5829
5830
		self::state( 'privacy_checks', $privacy_checks );
5831
	}
5832
5833
	/**
5834
	 * Helper method for multicall XMLRPC.
5835
	 *
5836
	 * @deprecated since 8.9.0
5837
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5838
	 *
5839
	 * @param ...$args Args for the async_call.
5840
	 */
5841
	public static function xmlrpc_async_call( ...$args ) {
5842
5843
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5844
5845
		global $blog_id;
5846
		static $clients = array();
5847
5848
		$client_blog_id = is_multisite() ? $blog_id : 0;
5849
5850
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5851
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => Connection_Manager::CONNECTION_OWNER ) );
5852
			if ( function_exists( 'ignore_user_abort' ) ) {
5853
				ignore_user_abort( true );
5854
			}
5855
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5856
		}
5857
5858
		if ( ! empty( $args[0] ) ) {
5859
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5860
		} elseif ( is_multisite() ) {
5861
			foreach ( $clients as $client_blog_id => $client ) {
5862
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5863
					continue;
5864
				}
5865
5866
				$switch_success = switch_to_blog( $client_blog_id, true );
5867
				if ( ! $switch_success ) {
5868
					continue;
5869
				}
5870
5871
				flush();
5872
				$client->query();
5873
5874
				restore_current_blog();
5875
			}
5876
		} else {
5877
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5878
				flush();
5879
				$clients[0]->query();
5880
			}
5881
		}
5882
	}
5883
5884
	/**
5885
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5886
	 *
5887
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5888
	 *
5889
	 * @param string $url WordPress.com static resource URL.
5890
	 */
5891
	public static function staticize_subdomain( $url ) {
5892
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5893
		return Assets::staticize_subdomain( $url );
5894
	}
5895
5896
	/* JSON API Authorization */
5897
5898
	/**
5899
	 * Handles the login action for Authorizing the JSON API
5900
	 */
5901
	function login_form_json_api_authorization() {
5902
		$this->verify_json_api_authorization_request();
5903
5904
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5905
5906
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5907
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5908
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5909
	}
5910
5911
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5912
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5913
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5914
			return $url;
5915
		}
5916
5917
		$parsed_url = wp_parse_url( $url );
5918
		$url        = strtok( $url, '?' );
5919
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5920
		if ( ! empty( $parsed_url['query'] ) ) {
5921
			$url .= "&{$parsed_url['query']}";
5922
		}
5923
5924
		return $url;
5925
	}
5926
5927
	// Make sure the POSTed request is handled by the same action
5928
	function preserve_action_in_login_form_for_json_api_authorization() {
5929
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5930
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5931
	}
5932
5933
	// If someone logs in to approve API access, store the Access Code in usermeta
5934
	function store_json_api_authorization_token( $user_login, $user ) {
5935
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5936
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5937
		$token = wp_generate_password( 32, false );
5938
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5939
	}
5940
5941
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5942
	function allow_wpcom_public_api_domain( $domains ) {
5943
		$domains[] = 'public-api.wordpress.com';
5944
		return $domains;
5945
	}
5946
5947
	static function is_redirect_encoded( $redirect_url ) {
5948
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5949
	}
5950
5951
	// Add all wordpress.com environments to the safe redirect allowed list.
5952
	function allow_wpcom_environments( $domains ) {
5953
		$domains[] = 'wordpress.com';
5954
		$domains[] = 'wpcalypso.wordpress.com';
5955
		$domains[] = 'horizon.wordpress.com';
5956
		$domains[] = 'calypso.localhost';
5957
		return $domains;
5958
	}
5959
5960
	// Add the Access Code details to the public-api.wordpress.com redirect
5961
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5962
		return add_query_arg(
5963
			urlencode_deep(
5964
				array(
5965
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5966
					'jetpack-user-id' => (int) $user->ID,
5967
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5968
				)
5969
			),
5970
			$redirect_to
5971
		);
5972
	}
5973
5974
	/**
5975
	 * Verifies the request by checking the signature
5976
	 *
5977
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5978
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5979
	 *
5980
	 * @param null|array $environment
5981
	 */
5982
	function verify_json_api_authorization_request( $environment = null ) {
5983
		$environment = is_null( $environment )
5984
			? $_REQUEST
5985
			: $environment;
5986
5987
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion 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...
5988
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

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