Completed
Push — try/refactor-secrets-and-token... ( 1bc8a1...a17499 )
by
unknown
33:04 queued 24:10
created

Jetpack::log_settings_change()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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