Completed
Push — e2e/e2e-remove-jest-playwright ( dbca74...b3c4ec )
by
unknown
218:11 queued 207:57
created

Jetpack::is_module()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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