Completed
Push — update/conversation-remove-par... ( 498b22...5ced53 )
by
unknown
18:38 queued 07:08
created

Jetpack::get_file_data()   B

Complexity

Conditions 7
Paths 24

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

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

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

Loading history...
555
	 */
556
	static function update_active_modules( $modules ) {
557
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
558
		$active_modules       = self::get_active_modules();
559
		$new_active_modules   = array_diff( $modules, $current_modules );
560
		$new_inactive_modules = array_diff( $active_modules, $modules );
561
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
562
		$reindexed_modules    = array_values( $new_current_modules );
563
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
564
565
		foreach ( $new_active_modules as $module ) {
566
			/**
567
			 * Fires when a specific module is activated.
568
			 *
569
			 * @since 1.9.0
570
			 *
571
			 * @param string $module Module slug.
572
			 * @param boolean $success whether the module was activated. @since 4.2
573
			 */
574
			do_action( 'jetpack_activate_module', $module, $success );
575
			/**
576
			 * Fires when a module is activated.
577
			 * The dynamic part of the filter, $module, is the module slug.
578
			 *
579
			 * @since 1.9.0
580
			 *
581
			 * @param string $module Module slug.
582
			 */
583
			do_action( "jetpack_activate_module_$module", $module );
584
		}
585
586
		foreach ( $new_inactive_modules as $module ) {
587
			/**
588
			 * Fired after a module has been deactivated.
589
			 *
590
			 * @since 4.2.0
591
			 *
592
			 * @param string $module Module slug.
593
			 * @param boolean $success whether the module was deactivated.
594
			 */
595
			do_action( 'jetpack_deactivate_module', $module, $success );
596
			/**
597
			 * Fires when a module is deactivated.
598
			 * The dynamic part of the filter, $module, is the module slug.
599
			 *
600
			 * @since 1.9.0
601
			 *
602
			 * @param string $module Module slug.
603
			 */
604
			do_action( "jetpack_deactivate_module_$module", $module );
605
		}
606
607
		return $success;
608
	}
609
610
	static function delete_active_modules() {
611
		self::update_active_modules( array() );
612
	}
613
614
	/**
615
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
616
	 * available.
617
	 */
618
	public function add_configure_hook() {
619
		global $wp_filter;
620
621
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
622
		if ( false !== $current_priority ) {
623
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
624
		}
625
626
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
627
		sort( $taken_priorities );
628
629
		$first_priority = array_shift( $taken_priorities );
630
631
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
632
			$new_priority = - PHP_INT_MAX;
633
		} else {
634
			$new_priority = $first_priority - 1;
635
		}
636
637
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
638
	}
639
640
	/**
641
	 * Constructor.  Initializes WordPress hooks
642
	 */
643
	private function __construct() {
644
		/*
645
		 * Check for and alert any deprecated hooks
646
		 */
647
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
648
649
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
650
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
651
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
652
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
653
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
654
655
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
656
657
		add_filter(
658
			'jetpack_signature_check_token',
659
			array( __CLASS__, 'verify_onboarding_token' ),
660
			10,
661
			3
662
		);
663
664
		/**
665
		 * Prepare Gutenberg Editor functionality
666
		 */
667
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
668
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
669
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
670
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
671
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
672
673
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
674
675
		// Unlink user before deleting the user from WP.com.
676
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
677
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
678
679
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
680
681
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
682
		add_action( 'login_init', array( $this, 'login_init' ) );
683
684
		// Set up the REST authentication hooks.
685
		Connection_Rest_Authentication::init();
686
687
		add_action( 'admin_init', array( $this, 'admin_init' ) );
688
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
689
690
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
691
692
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
693
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
694
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
695
696
		// returns HTTPS support status
697
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
698
699
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
700
701
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
702
703
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
704
705
		/**
706
		 * These actions run checks to load additional files.
707
		 * They check for external files or plugins, so they need to run as late as possible.
708
		 */
709
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
710
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
711
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
712
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
713
714
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
715
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
716
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
717
718
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
719
720
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
721
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
722
723
		// A filter to control all just in time messages
724
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
725
726
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
727
728
		/*
729
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
730
		 * We should make sure to only do this for front end links.
731
		 */
732
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
733
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
734
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
735
736
			/*
737
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
738
			 * so they point moderation links on emails to Calypso.
739
			 */
740
			jetpack_require_lib( 'functions.wp-notify' );
741
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
742
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
743
		}
744
745
		add_action(
746
			'plugins_loaded',
747
			function () {
748
				if ( User_Agent_Info::is_mobile_app() ) {
749
					add_filter( 'get_edit_post_link', '__return_empty_string' );
750
				}
751
			}
752
		);
753
754
		// Update the site's Jetpack plan and products from API on heartbeats.
755
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
756
757
		/**
758
		 * This is the hack to concatenate all css files into one.
759
		 * For description and reasoning see the implode_frontend_css method.
760
		 *
761
		 * Super late priority so we catch all the registered styles.
762
		 */
763
		if ( ! is_admin() ) {
764
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
765
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
766
		}
767
768
		/**
769
		 * These are sync actions that we need to keep track of for jitms
770
		 */
771
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
772
773
		// Actually push the stats on shutdown.
774
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
775
			add_action( 'shutdown', array( $this, 'push_stats' ) );
776
		}
777
778
		// Actions for Manager::authorize().
779
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
780
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
781
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
782
783
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
784
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
785
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
786
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
787
788
		// Filters for the Manager::get_token() urls and request body.
789
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
790
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
791
792
		// Actions for successful reconnect.
793
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
794
795
		// Actions for licensing.
796
		Licensing::instance()->initialize();
797
798
		// Make resources use static domain when possible.
799
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
800
	}
801
802
	/**
803
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
804
	 * Config object.
805
	 */
806
	public function configure() {
807
		$config = new Config();
808
809
		foreach (
810
			array(
811
				'sync',
812
			)
813
			as $feature
814
		) {
815
			$config->ensure( $feature );
816
		}
817
818
		$config->ensure(
819
			'connection',
820
			array(
821
				'slug' => 'jetpack',
822
				'name' => 'Jetpack',
823
			)
824
		);
825
826
		if ( is_admin() ) {
827
			$config->ensure( 'jitm' );
828
		}
829
830
		if ( ! $this->connection_manager ) {
831
			$this->connection_manager = new Connection_Manager( 'jetpack' );
832
833
			/**
834
			 * Filter to activate Jetpack Connection UI.
835
			 * INTERNAL USE ONLY.
836
			 *
837
			 * @since 9.5.0
838
			 *
839
			 * @param bool false Whether to activate the Connection UI.
840
			 */
841
			if ( apply_filters( 'jetpack_connection_ui_active', false ) ) {
842
				Automattic\Jetpack\ConnectionUI\Admin::init();
843
			}
844
		}
845
846
		/*
847
		 * Load things that should only be in Network Admin.
848
		 *
849
		 * For now blow away everything else until a more full
850
		 * understanding of what is needed at the network level is
851
		 * available
852
		 */
853
		if ( is_multisite() ) {
854
			$network = Jetpack_Network::init();
855
			$network->set_connection( $this->connection_manager );
856
		}
857
858
		if ( $this->connection_manager->is_active() ) {
859
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
860
861
			Jetpack_Heartbeat::init();
862
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
863
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
864
				Jetpack_Search_Performance_Logger::init();
865
			}
866
		}
867
868
		// Initialize remote file upload request handlers.
869
		$this->add_remote_request_handlers();
870
871
		/*
872
		 * Enable enhanced handling of previewing sites in Calypso
873
		 */
874
		if ( self::is_active() ) {
875
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
876
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
877
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
878
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
879
		}
880
881
		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...
882
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
883
		} else {
884
			/**
885
			 * Initialize tracking right after the user agrees to the terms of service.
886
			 */
887
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
888
		}
889
	}
890
891
	/**
892
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
893
	 * initialization code.
894
	 *
895
	 * @action plugins_loaded
896
	 */
897
	public function late_initialization() {
898
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
899
900
		Partner::init();
901
902
		/**
903
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
904
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
905
		 *
906
		 * @since 8.1.0
907
		 *
908
		 * @param Jetpack $jetpack the main plugin class object.
909
		 */
910
		do_action( 'jetpack_loaded', $this );
911
912
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
913
	}
914
915
	/**
916
	 * Sets up the XMLRPC request handlers.
917
	 *
918
	 * @deprecated since 7.7.0
919
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
920
	 *
921
	 * @param array                 $request_params Incoming request parameters.
922
	 * @param Boolean               $is_active      Whether the connection is currently active.
923
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
924
	 * @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...
925
	 */
926 View Code Duplication
	public function setup_xmlrpc_handlers(
927
		$request_params,
928
		$is_active,
929
		$is_signed,
930
		Jetpack_XMLRPC_Server $xmlrpc_server = null
931
	) {
932
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
933
934
		if ( ! $this->connection_manager ) {
935
			$this->connection_manager = new Connection_Manager();
936
		}
937
938
		return $this->connection_manager->setup_xmlrpc_handlers(
939
			$request_params,
940
			$is_active,
941
			$is_signed,
942
			$xmlrpc_server
943
		);
944
	}
945
946
	/**
947
	 * Initialize REST API registration connector.
948
	 *
949
	 * @deprecated since 7.7.0
950
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
951
	 */
952 View Code Duplication
	public function initialize_rest_api_registration_connector() {
953
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
954
955
		if ( ! $this->connection_manager ) {
956
			$this->connection_manager = new Connection_Manager();
957
		}
958
959
		$this->connection_manager->initialize_rest_api_registration_connector();
960
	}
961
962
	/**
963
	 * This is ported over from the manage module, which has been deprecated and baked in here.
964
	 *
965
	 * @param $domains
966
	 */
967
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
968
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
969
	}
970
971
	/**
972
	 * Return $domains, with 'wordpress.com' appended.
973
	 * This is ported over from the manage module, which has been deprecated and baked in here.
974
	 *
975
	 * @param $domains
976
	 * @return array
977
	 */
978
	function allow_wpcom_domain( $domains ) {
979
		if ( empty( $domains ) ) {
980
			$domains = array();
981
		}
982
		$domains[] = 'wordpress.com';
983
		return array_unique( $domains );
984
	}
985
986
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
987
		$post = get_post( $post_id );
988
989
		if ( empty( $post ) ) {
990
			return $default_url;
991
		}
992
993
		$post_type = $post->post_type;
994
995
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
996
		// https://en.support.wordpress.com/custom-post-types/
997
		$allowed_post_types = array(
998
			'post',
999
			'page',
1000
			'jetpack-portfolio',
1001
			'jetpack-testimonial',
1002
		);
1003
1004
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1005
			return $default_url;
1006
		}
1007
1008
		return Redirect::get_url(
1009
			'calypso-edit-' . $post_type,
1010
			array(
1011
				'path' => $post_id,
1012
			)
1013
		);
1014
	}
1015
1016
	function point_edit_comment_links_to_calypso( $url ) {
1017
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1018
		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...
1019
1020
		return Redirect::get_url(
1021
			'calypso-edit-comment',
1022
			array(
1023
				'path' => $query_args['amp;c'],
1024
			)
1025
		);
1026
1027
	}
1028
1029
	function jetpack_track_last_sync_callback( $params ) {
1030
		/**
1031
		 * Filter to turn off jitm caching
1032
		 *
1033
		 * @since 5.4.0
1034
		 *
1035
		 * @param bool false Whether to cache just in time messages
1036
		 */
1037
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1038
			return $params;
1039
		}
1040
1041
		if ( is_array( $params ) && isset( $params[0] ) ) {
1042
			$option = $params[0];
1043
			if ( 'active_plugins' === $option ) {
1044
				// use the cache if we can, but not terribly important if it gets evicted
1045
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1046
			}
1047
		}
1048
1049
		return $params;
1050
	}
1051
1052
	function jetpack_connection_banner_callback() {
1053
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1054
1055
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1056
		if (
1057
			isset( $_REQUEST['dismissBanner'] ) &&
1058
			! Jetpack_Connection_Banner::force_display()
1059
		) {
1060
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1061
			wp_send_json_success();
1062
		}
1063
1064
		wp_die();
1065
	}
1066
1067
	/**
1068
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1069
	 * Only used in our alternate XML-RPC endpoint, where we want to
1070
	 * ensure that Core and other plugins' methods are not exposed.
1071
	 *
1072
	 * @deprecated since 7.7.0
1073
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1074
	 *
1075
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1076
	 * @return array Filtered $methods
1077
	 */
1078 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1079
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1080
1081
		if ( ! $this->connection_manager ) {
1082
			$this->connection_manager = new Connection_Manager();
1083
		}
1084
1085
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1086
	}
1087
1088
	/**
1089
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1090
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1091
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1092
	 * which is accessible via a different URI. Most of the below is copied directly
1093
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1094
	 *
1095
	 * @deprecated since 7.7.0
1096
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1097
	 */
1098 View Code Duplication
	public function alternate_xmlrpc() {
1099
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1100
1101
		if ( ! $this->connection_manager ) {
1102
			$this->connection_manager = new Connection_Manager();
1103
		}
1104
1105
		$this->connection_manager->alternate_xmlrpc();
1106
	}
1107
1108
	/**
1109
	 * The callback for the JITM ajax requests.
1110
	 *
1111
	 * @deprecated since 7.9.0
1112
	 */
1113
	function jetpack_jitm_ajax_callback() {
1114
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1115
	}
1116
1117
	/**
1118
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1119
	 */
1120
	function push_stats() {
1121
		if ( ! empty( $this->stats ) ) {
1122
			$this->do_stats( 'server_side' );
1123
		}
1124
	}
1125
1126
	/**
1127
	 * Sets the Jetpack custom capabilities.
1128
	 *
1129
	 * @param string[] $caps    Array of the user's capabilities.
1130
	 * @param string   $cap     Capability name.
1131
	 * @param int      $user_id The user ID.
1132
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1133
	 */
1134
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1135
		$is_offline_mode = ( new Status() )->is_offline_mode();
1136
		switch ( $cap ) {
1137
			case 'jetpack_manage_modules':
1138
			case 'jetpack_activate_modules':
1139
			case 'jetpack_deactivate_modules':
1140
				$caps = array( 'manage_options' );
1141
				break;
1142
			case 'jetpack_configure_modules':
1143
				$caps = array( 'manage_options' );
1144
				break;
1145
			case 'jetpack_manage_autoupdates':
1146
				$caps = array(
1147
					'manage_options',
1148
					'update_plugins',
1149
				);
1150
				break;
1151
			case 'jetpack_network_admin_page':
1152
			case 'jetpack_network_settings_page':
1153
				$caps = array( 'manage_network_plugins' );
1154
				break;
1155
			case 'jetpack_network_sites_page':
1156
				$caps = array( 'manage_sites' );
1157
				break;
1158
			case 'jetpack_admin_page':
1159
				if ( $is_offline_mode ) {
1160
					$caps = array( 'manage_options' );
1161
					break;
1162
				} else {
1163
					$caps = array( 'read' );
1164
				}
1165
				break;
1166
		}
1167
		return $caps;
1168
	}
1169
1170
	/**
1171
	 * Require a Jetpack authentication.
1172
	 *
1173
	 * @deprecated since 7.7.0
1174
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1175
	 */
1176 View Code Duplication
	public function require_jetpack_authentication() {
1177
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1178
1179
		if ( ! $this->connection_manager ) {
1180
			$this->connection_manager = new Connection_Manager();
1181
		}
1182
1183
		$this->connection_manager->require_jetpack_authentication();
1184
	}
1185
1186
	/**
1187
	 * Register assets for use in various modules and the Jetpack admin page.
1188
	 *
1189
	 * @uses wp_script_is, wp_register_script, plugins_url
1190
	 * @action wp_loaded
1191
	 * @return null
1192
	 */
1193
	public function register_assets() {
1194 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1195
			wp_register_script(
1196
				'jetpack-gallery-settings',
1197
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1198
				array( 'media-views' ),
1199
				'20121225'
1200
			);
1201
		}
1202
1203
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1204
			wp_register_script(
1205
				'jetpack-twitter-timeline',
1206
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1207
				array( 'jquery' ),
1208
				'4.0.0',
1209
				true
1210
			);
1211
		}
1212
1213
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1214
			wp_register_script(
1215
				'jetpack-facebook-embed',
1216
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1217
				array(),
1218
				null,
1219
				true
1220
			);
1221
1222
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1223
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1224
			if ( ! is_numeric( $fb_app_id ) ) {
1225
				$fb_app_id = '';
1226
			}
1227
			wp_localize_script(
1228
				'jetpack-facebook-embed',
1229
				'jpfbembed',
1230
				array(
1231
					'appid'  => $fb_app_id,
1232
					'locale' => $this->get_locale(),
1233
				)
1234
			);
1235
		}
1236
1237
		/**
1238
		 * As jetpack_register_genericons is by default fired off a hook,
1239
		 * the hook may have already fired by this point.
1240
		 * So, let's just trigger it manually.
1241
		 */
1242
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1243
		jetpack_register_genericons();
1244
1245
		/**
1246
		 * Register the social logos
1247
		 */
1248
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1249
		jetpack_register_social_logos();
1250
1251 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1252
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1253
		}
1254
	}
1255
1256
	/**
1257
	 * Guess locale from language code.
1258
	 *
1259
	 * @param string $lang Language code.
1260
	 * @return string|bool
1261
	 */
1262 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1263
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1264
			return 'en_US';
1265
		}
1266
1267
		if ( ! class_exists( 'GP_Locales' ) ) {
1268
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1269
				return false;
1270
			}
1271
1272
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1273
		}
1274
1275
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1276
			// WP.com: get_locale() returns 'it'
1277
			$locale = GP_Locales::by_slug( $lang );
1278
		} else {
1279
			// Jetpack: get_locale() returns 'it_IT';
1280
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1281
		}
1282
1283
		if ( ! $locale ) {
1284
			return false;
1285
		}
1286
1287
		if ( empty( $locale->facebook_locale ) ) {
1288
			if ( empty( $locale->wp_locale ) ) {
1289
				return false;
1290
			} else {
1291
				// Facebook SDK is smart enough to fall back to en_US if a
1292
				// locale isn't supported. Since supported Facebook locales
1293
				// can fall out of sync, we'll attempt to use the known
1294
				// wp_locale value and rely on said fallback.
1295
				return $locale->wp_locale;
1296
			}
1297
		}
1298
1299
		return $locale->facebook_locale;
1300
	}
1301
1302
	/**
1303
	 * Get the locale.
1304
	 *
1305
	 * @return string|bool
1306
	 */
1307
	function get_locale() {
1308
		$locale = $this->guess_locale_from_lang( get_locale() );
1309
1310
		if ( ! $locale ) {
1311
			$locale = 'en_US';
1312
		}
1313
1314
		return $locale;
1315
	}
1316
1317
	/**
1318
	 * Return the network_site_url so that .com knows what network this site is a part of.
1319
	 *
1320
	 * @param  bool $option
1321
	 * @return string
1322
	 */
1323
	public function jetpack_main_network_site_option( $option ) {
1324
		return network_site_url();
1325
	}
1326
	/**
1327
	 * Network Name.
1328
	 */
1329
	static function network_name( $option = null ) {
1330
		global $current_site;
1331
		return $current_site->site_name;
1332
	}
1333
	/**
1334
	 * Does the network allow new user and site registrations.
1335
	 *
1336
	 * @return string
1337
	 */
1338
	static function network_allow_new_registrations( $option = null ) {
1339
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1340
	}
1341
	/**
1342
	 * Does the network allow admins to add new users.
1343
	 *
1344
	 * @return boolian
1345
	 */
1346
	static function network_add_new_users( $option = null ) {
1347
		return (bool) get_site_option( 'add_new_users' );
1348
	}
1349
	/**
1350
	 * File upload psace left per site in MB.
1351
	 *  -1 means NO LIMIT.
1352
	 *
1353
	 * @return number
1354
	 */
1355
	static function network_site_upload_space( $option = null ) {
1356
		// value in MB
1357
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1358
	}
1359
1360
	/**
1361
	 * Network allowed file types.
1362
	 *
1363
	 * @return string
1364
	 */
1365
	static function network_upload_file_types( $option = null ) {
1366
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1367
	}
1368
1369
	/**
1370
	 * Maximum file upload size set by the network.
1371
	 *
1372
	 * @return number
1373
	 */
1374
	static function network_max_upload_file_size( $option = null ) {
1375
		// value in KB
1376
		return get_site_option( 'fileupload_maxk', 300 );
1377
	}
1378
1379
	/**
1380
	 * Lets us know if a site allows admins to manage the network.
1381
	 *
1382
	 * @return array
1383
	 */
1384
	static function network_enable_administration_menus( $option = null ) {
1385
		return get_site_option( 'menu_items' );
1386
	}
1387
1388
	/**
1389
	 * If a user has been promoted to or demoted from admin, we need to clear the
1390
	 * jetpack_other_linked_admins transient.
1391
	 *
1392
	 * @since 4.3.2
1393
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1394
	 *
1395
	 * @param int    $user_id   The user ID whose role changed.
1396
	 * @param string $role      The new role.
1397
	 * @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...
1398
	 */
1399
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1400
		if ( 'administrator' == $role
1401
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1402
			|| is_null( $old_roles )
1403
		) {
1404
			delete_transient( 'jetpack_other_linked_admins' );
1405
		}
1406
	}
1407
1408
	/**
1409
	 * Checks to see if there are any other users available to become primary
1410
	 * Users must both:
1411
	 * - Be linked to wpcom
1412
	 * - Be an admin
1413
	 *
1414
	 * @return mixed False if no other users are linked, Int if there are.
1415
	 */
1416
	static function get_other_linked_admins() {
1417
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1418
1419
		if ( false === $other_linked_users ) {
1420
			$admins = get_users( array( 'role' => 'administrator' ) );
1421
			if ( count( $admins ) > 1 ) {
1422
				$available = array();
1423
				foreach ( $admins as $admin ) {
1424
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1425
						$available[] = $admin->ID;
1426
					}
1427
				}
1428
1429
				$count_connected_admins = count( $available );
1430
				if ( count( $available ) > 1 ) {
1431
					$other_linked_users = $count_connected_admins;
1432
				} else {
1433
					$other_linked_users = 0;
1434
				}
1435
			} else {
1436
				$other_linked_users = 0;
1437
			}
1438
1439
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1440
		}
1441
1442
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1443
	}
1444
1445
	/**
1446
	 * Return whether we are dealing with a multi network setup or not.
1447
	 * The reason we are type casting this is because we want to avoid the situation where
1448
	 * the result is false since when is_main_network_option return false it cases
1449
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1450
	 * database which could be set to anything as opposed to what this function returns.
1451
	 *
1452
	 * @param  bool $option
1453
	 *
1454
	 * @return boolean
1455
	 */
1456
	public function is_main_network_option( $option ) {
1457
		// return '1' or ''
1458
		return (string) (bool) self::is_multi_network();
1459
	}
1460
1461
	/**
1462
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1463
	 *
1464
	 * @param  string $option
1465
	 * @return boolean
1466
	 */
1467
	public function is_multisite( $option ) {
1468
		return (string) (bool) is_multisite();
1469
	}
1470
1471
	/**
1472
	 * Implemented since there is no core is multi network function
1473
	 * Right now there is no way to tell if we which network is the dominant network on the system
1474
	 *
1475
	 * @since  3.3
1476
	 * @return boolean
1477
	 */
1478 View Code Duplication
	public static function is_multi_network() {
1479
		global  $wpdb;
1480
1481
		// if we don't have a multi site setup no need to do any more
1482
		if ( ! is_multisite() ) {
1483
			return false;
1484
		}
1485
1486
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1487
		if ( $num_sites > 1 ) {
1488
			return true;
1489
		} else {
1490
			return false;
1491
		}
1492
	}
1493
1494
	/**
1495
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1496
	 *
1497
	 * @return null
1498
	 */
1499
	function update_jetpack_main_network_site_option() {
1500
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1501
	}
1502
	/**
1503
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1504
	 */
1505
	function update_jetpack_network_settings() {
1506
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1507
		// Only sync this info for the main network site.
1508
	}
1509
1510
	/**
1511
	 * Get back if the current site is single user site.
1512
	 *
1513
	 * @return bool
1514
	 */
1515 View Code Duplication
	public static function is_single_user_site() {
1516
		global $wpdb;
1517
1518
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1519
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1520
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1521
		}
1522
		return 1 === (int) $some_users;
1523
	}
1524
1525
	/**
1526
	 * Returns true if the site has file write access false otherwise.
1527
	 *
1528
	 * @return string ( '1' | '0' )
1529
	 **/
1530
	public static function file_system_write_access() {
1531
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1532
			require_once ABSPATH . 'wp-admin/includes/file.php';
1533
		}
1534
1535
		require_once ABSPATH . 'wp-admin/includes/template.php';
1536
1537
		$filesystem_method = get_filesystem_method();
1538
		if ( $filesystem_method === 'direct' ) {
1539
			return 1;
1540
		}
1541
1542
		ob_start();
1543
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1544
		ob_end_clean();
1545
		if ( $filesystem_credentials_are_stored ) {
1546
			return 1;
1547
		}
1548
		return 0;
1549
	}
1550
1551
	/**
1552
	 * Finds out if a site is using a version control system.
1553
	 *
1554
	 * @return string ( '1' | '0' )
1555
	 **/
1556
	public static function is_version_controlled() {
1557
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1558
		return (string) (int) Functions::is_version_controlled();
1559
	}
1560
1561
	/**
1562
	 * Determines whether the current theme supports featured images or not.
1563
	 *
1564
	 * @return string ( '1' | '0' )
1565
	 */
1566
	public static function featured_images_enabled() {
1567
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1568
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1569
	}
1570
1571
	/**
1572
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1573
	 *
1574
	 * @deprecated 4.7 use get_avatar_url instead.
1575
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1576
	 * @param int               $size Size of the avatar image
1577
	 * @param string            $default URL to a default image to use if no avatar is available
1578
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1579
	 *
1580
	 * @return array
1581
	 */
1582
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1583
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1584
		return get_avatar_url(
1585
			$id_or_email,
1586
			array(
1587
				'size'          => $size,
1588
				'default'       => $default,
1589
				'force_default' => $force_display,
1590
			)
1591
		);
1592
	}
1593
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1594
	/**
1595
	 * jetpack_updates is saved in the following schema:
1596
	 *
1597
	 * array (
1598
	 *      'plugins'                       => (int) Number of plugin updates available.
1599
	 *      'themes'                        => (int) Number of theme updates available.
1600
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1601
	 *      'translations'                  => (int) Number of translation updates available.
1602
	 *      'total'                         => (int) Total of all available updates.
1603
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1604
	 * )
1605
	 *
1606
	 * @return array
1607
	 */
1608
	public static function get_updates() {
1609
		$update_data = wp_get_update_data();
1610
1611
		// Stores the individual update counts as well as the total count.
1612
		if ( isset( $update_data['counts'] ) ) {
1613
			$updates = $update_data['counts'];
1614
		}
1615
1616
		// If we need to update WordPress core, let's find the latest version number.
1617 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1618
			$cur = get_preferred_from_update_core();
1619
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1620
				$updates['wp_update_version'] = $cur->current;
1621
			}
1622
		}
1623
		return isset( $updates ) ? $updates : array();
1624
	}
1625
	// phpcs:enable
1626
1627
	public static function get_update_details() {
1628
		$update_details = array(
1629
			'update_core'    => get_site_transient( 'update_core' ),
1630
			'update_plugins' => get_site_transient( 'update_plugins' ),
1631
			'update_themes'  => get_site_transient( 'update_themes' ),
1632
		);
1633
		return $update_details;
1634
	}
1635
1636
	public static function refresh_update_data() {
1637
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1638
1639
	}
1640
1641
	public static function refresh_theme_data() {
1642
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1643
	}
1644
1645
	/**
1646
	 * Is Jetpack active?
1647
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1648
	 *
1649
	 * @return bool
1650
	 */
1651
	public static function is_active() {
1652
		return self::connection()->is_active();
1653
	}
1654
1655
	/**
1656
	 * Make an API call to WordPress.com for plan status
1657
	 *
1658
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1659
	 *
1660
	 * @return bool True if plan is updated, false if no update
1661
	 */
1662
	public static function refresh_active_plan_from_wpcom() {
1663
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1664
		return Jetpack_Plan::refresh_from_wpcom();
1665
	}
1666
1667
	/**
1668
	 * Get the plan that this Jetpack site is currently using
1669
	 *
1670
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1671
	 * @return array Active Jetpack plan details.
1672
	 */
1673
	public static function get_active_plan() {
1674
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1675
		return Jetpack_Plan::get();
1676
	}
1677
1678
	/**
1679
	 * Determine whether the active plan supports a particular feature
1680
	 *
1681
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1682
	 * @return bool True if plan supports feature, false if not.
1683
	 */
1684
	public static function active_plan_supports( $feature ) {
1685
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1686
		return Jetpack_Plan::supports( $feature );
1687
	}
1688
1689
	/**
1690
	 * Deprecated: Is Jetpack in development (offline) mode?
1691
	 *
1692
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1693
	 * and themes still use it, and we do not want to flood them with notices.
1694
	 *
1695
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1696
	 *
1697
	 * @deprecated since 8.0.
1698
	 */
1699
	public static function is_development_mode() {
1700
		return ( new Status() )->is_offline_mode();
1701
	}
1702
1703
	/**
1704
	 * Whether the site is currently onboarding or not.
1705
	 * A site is considered as being onboarded if it currently has an onboarding token.
1706
	 *
1707
	 * @since 5.8
1708
	 *
1709
	 * @access public
1710
	 * @static
1711
	 *
1712
	 * @return bool True if the site is currently onboarding, false otherwise
1713
	 */
1714
	public static function is_onboarding() {
1715
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1716
	}
1717
1718
	/**
1719
	 * Determines reason for Jetpack offline mode.
1720
	 */
1721
	public static function development_mode_trigger_text() {
1722
		$status = new Status();
1723
1724
		if ( ! $status->is_offline_mode() ) {
1725
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1726
		}
1727
1728
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1729
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1730
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1731
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1732
		} elseif ( $status->is_local_site() ) {
1733
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1734
			/** This filter is documented in packages/status/src/class-status.php */
1735
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1736
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1737
		} else {
1738
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1739
		}
1740
1741
		return $notice;
1742
1743
	}
1744
	/**
1745
	 * Get Jetpack offline mode notice text and notice class.
1746
	 *
1747
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1748
	 */
1749
	public static function show_development_mode_notice() {
1750 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1751
			$notice = sprintf(
1752
				/* translators: %s is a URL */
1753
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1754
				Redirect::get_url( 'jetpack-support-development-mode' )
1755
			);
1756
1757
			$notice .= ' ' . self::development_mode_trigger_text();
1758
1759
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1760
		}
1761
1762
		// Throw up a notice if using a development version and as for feedback.
1763
		if ( self::is_development_version() ) {
1764
			/* translators: %s is a URL */
1765
			$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' ) );
1766
1767
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1768
		}
1769
		// Throw up a notice if using staging mode
1770 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1771
			/* translators: %s is a URL */
1772
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1773
1774
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1775
		}
1776
	}
1777
1778
	/**
1779
	 * Whether Jetpack's version maps to a public release, or a development version.
1780
	 */
1781
	public static function is_development_version() {
1782
		/**
1783
		 * Allows filtering whether this is a development version of Jetpack.
1784
		 *
1785
		 * This filter is especially useful for tests.
1786
		 *
1787
		 * @since 4.3.0
1788
		 *
1789
		 * @param bool $development_version Is this a develoment version of Jetpack?
1790
		 */
1791
		return (bool) apply_filters(
1792
			'jetpack_development_version',
1793
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1794
		);
1795
	}
1796
1797
	/**
1798
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1799
	 */
1800
	public static function is_user_connected( $user_id = false ) {
1801
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1802
		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...
1803
	}
1804
1805
	/**
1806
	 * Get the wpcom user data of the current|specified connected user.
1807
	 */
1808
	public static function get_connected_user_data( $user_id = null ) {
1809
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1810
		return self::connection()->get_connected_user_data( $user_id );
1811
	}
1812
1813
	/**
1814
	 * Get the wpcom email of the current|specified connected user.
1815
	 */
1816
	public static function get_connected_user_email( $user_id = null ) {
1817
		if ( ! $user_id ) {
1818
			$user_id = get_current_user_id();
1819
		}
1820
1821
		$xml = new Jetpack_IXR_Client(
1822
			array(
1823
				'user_id' => $user_id,
1824
			)
1825
		);
1826
		$xml->query( 'wpcom.getUserEmail' );
1827
		if ( ! $xml->isError() ) {
1828
			return $xml->getResponse();
1829
		}
1830
		return false;
1831
	}
1832
1833
	/**
1834
	 * Get the wpcom email of the master user.
1835
	 */
1836
	public static function get_master_user_email() {
1837
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1838
		if ( $master_user_id ) {
1839
			return self::get_connected_user_email( $master_user_id );
1840
		}
1841
		return '';
1842
	}
1843
1844
	/**
1845
	 * Whether the current user is the connection owner.
1846
	 *
1847
	 * @deprecated since 7.7
1848
	 *
1849
	 * @return bool Whether the current user is the connection owner.
1850
	 */
1851
	public function current_user_is_connection_owner() {
1852
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1853
		return self::connection()->is_connection_owner();
1854
	}
1855
1856
	/**
1857
	 * Gets current user IP address.
1858
	 *
1859
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1860
	 *
1861
	 * @return string                  Current user IP address.
1862
	 */
1863
	public static function current_user_ip( $check_all_headers = false ) {
1864
		if ( $check_all_headers ) {
1865
			foreach ( array(
1866
				'HTTP_CF_CONNECTING_IP',
1867
				'HTTP_CLIENT_IP',
1868
				'HTTP_X_FORWARDED_FOR',
1869
				'HTTP_X_FORWARDED',
1870
				'HTTP_X_CLUSTER_CLIENT_IP',
1871
				'HTTP_FORWARDED_FOR',
1872
				'HTTP_FORWARDED',
1873
				'HTTP_VIA',
1874
			) as $key ) {
1875
				if ( ! empty( $_SERVER[ $key ] ) ) {
1876
					return $_SERVER[ $key ];
1877
				}
1878
			}
1879
		}
1880
1881
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1882
	}
1883
1884
	/**
1885
	 * Synchronize connected user role changes
1886
	 */
1887
	function user_role_change( $user_id ) {
1888
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1889
		Users::user_role_change( $user_id );
1890
	}
1891
1892
	/**
1893
	 * Loads the currently active modules.
1894
	 */
1895
	public static function load_modules() {
1896
		$is_offline_mode = ( new Status() )->is_offline_mode();
1897
		if (
1898
			! self::is_active()
1899
			&& ! $is_offline_mode
1900
			&& ! self::is_onboarding()
1901
			&& (
1902
				! is_multisite()
1903
				|| ! get_site_option( 'jetpack_protect_active' )
1904
			)
1905
		) {
1906
			return;
1907
		}
1908
1909
		$version = Jetpack_Options::get_option( 'version' );
1910 View Code Duplication
		if ( ! $version ) {
1911
			$version = $old_version = JETPACK__VERSION . ':' . time();
1912
			/** This action is documented in class.jetpack.php */
1913
			do_action( 'updating_jetpack_version', $version, false );
1914
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1915
		}
1916
		list( $version ) = explode( ':', $version );
1917
1918
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1919
1920
		$modules_data = array();
1921
1922
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1923
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1924
			$updated_modules = array();
1925
			foreach ( $modules as $module ) {
1926
				$modules_data[ $module ] = self::get_module( $module );
1927
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1928
					continue;
1929
				}
1930
1931
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1932
					continue;
1933
				}
1934
1935
				$updated_modules[] = $module;
1936
			}
1937
1938
			$modules = array_diff( $modules, $updated_modules );
1939
		}
1940
1941
		foreach ( $modules as $index => $module ) {
1942
			// If we're in offline mode, disable modules requiring a connection.
1943
			if ( $is_offline_mode ) {
1944
				// Prime the pump if we need to
1945
				if ( empty( $modules_data[ $module ] ) ) {
1946
					$modules_data[ $module ] = self::get_module( $module );
1947
				}
1948
				// If the module requires a connection, but we're in local mode, don't include it.
1949
				if ( $modules_data[ $module ]['requires_connection'] ) {
1950
					continue;
1951
				}
1952
			}
1953
1954
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1955
				continue;
1956
			}
1957
1958
			if ( ! include_once self::get_module_path( $module ) ) {
1959
				unset( $modules[ $index ] );
1960
				self::update_active_modules( array_values( $modules ) );
1961
				continue;
1962
			}
1963
1964
			/**
1965
			 * Fires when a specific module is loaded.
1966
			 * The dynamic part of the hook, $module, is the module slug.
1967
			 *
1968
			 * @since 1.1.0
1969
			 */
1970
			do_action( 'jetpack_module_loaded_' . $module );
1971
		}
1972
1973
		/**
1974
		 * Fires when all the modules are loaded.
1975
		 *
1976
		 * @since 1.1.0
1977
		 */
1978
		do_action( 'jetpack_modules_loaded' );
1979
1980
		// 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.
1981
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1982
	}
1983
1984
	/**
1985
	 * Check if Jetpack's REST API compat file should be included
1986
	 *
1987
	 * @action plugins_loaded
1988
	 * @return null
1989
	 */
1990
	public function check_rest_api_compat() {
1991
		/**
1992
		 * Filters the list of REST API compat files to be included.
1993
		 *
1994
		 * @since 2.2.5
1995
		 *
1996
		 * @param array $args Array of REST API compat files to include.
1997
		 */
1998
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1999
2000
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2001
			require_once $_jetpack_rest_api_compat_include;
2002
		}
2003
	}
2004
2005
	/**
2006
	 * Gets all plugins currently active in values, regardless of whether they're
2007
	 * traditionally activated or network activated.
2008
	 *
2009
	 * @todo Store the result in core's object cache maybe?
2010
	 */
2011
	public static function get_active_plugins() {
2012
		$active_plugins = (array) get_option( 'active_plugins', array() );
2013
2014
		if ( is_multisite() ) {
2015
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2016
			// whereas active_plugins stores them in the values.
2017
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2018
			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...
2019
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2020
			}
2021
		}
2022
2023
		sort( $active_plugins );
2024
2025
		return array_unique( $active_plugins );
2026
	}
2027
2028
	/**
2029
	 * Gets and parses additional plugin data to send with the heartbeat data
2030
	 *
2031
	 * @since 3.8.1
2032
	 *
2033
	 * @return array Array of plugin data
2034
	 */
2035
	public static function get_parsed_plugin_data() {
2036
		if ( ! function_exists( 'get_plugins' ) ) {
2037
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2038
		}
2039
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2040
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2041
		$active_plugins = self::get_active_plugins();
2042
2043
		$plugins = array();
2044
		foreach ( $all_plugins as $path => $plugin_data ) {
2045
			$plugins[ $path ] = array(
2046
				'is_active' => in_array( $path, $active_plugins ),
2047
				'file'      => $path,
2048
				'name'      => $plugin_data['Name'],
2049
				'version'   => $plugin_data['Version'],
2050
				'author'    => $plugin_data['Author'],
2051
			);
2052
		}
2053
2054
		return $plugins;
2055
	}
2056
2057
	/**
2058
	 * Gets and parses theme data to send with the heartbeat data
2059
	 *
2060
	 * @since 3.8.1
2061
	 *
2062
	 * @return array Array of theme data
2063
	 */
2064
	public static function get_parsed_theme_data() {
2065
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2066
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2067
2068
		$themes = array();
2069
		foreach ( $all_themes as $slug => $theme_data ) {
2070
			$theme_headers = array();
2071
			foreach ( $header_keys as $header_key ) {
2072
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2073
			}
2074
2075
			$themes[ $slug ] = array(
2076
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2077
				'slug'            => $slug,
2078
				'theme_root'      => $theme_data->get_theme_root_uri(),
2079
				'parent'          => $theme_data->parent(),
2080
				'headers'         => $theme_headers,
2081
			);
2082
		}
2083
2084
		return $themes;
2085
	}
2086
2087
	/**
2088
	 * Checks whether a specific plugin is active.
2089
	 *
2090
	 * We don't want to store these in a static variable, in case
2091
	 * there are switch_to_blog() calls involved.
2092
	 */
2093
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2094
		return in_array( $plugin, self::get_active_plugins() );
2095
	}
2096
2097
	/**
2098
	 * Check if Jetpack's Open Graph tags should be used.
2099
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2100
	 *
2101
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2102
	 * @action plugins_loaded
2103
	 * @return null
2104
	 */
2105
	public function check_open_graph() {
2106
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2107
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2108
		}
2109
2110
		$active_plugins = self::get_active_plugins();
2111
2112
		if ( ! empty( $active_plugins ) ) {
2113
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2114
				if ( in_array( $plugin, $active_plugins ) ) {
2115
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2116
					break;
2117
				}
2118
			}
2119
		}
2120
2121
		/**
2122
		 * Allow the addition of Open Graph Meta Tags to all pages.
2123
		 *
2124
		 * @since 2.0.3
2125
		 *
2126
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2127
		 */
2128
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2129
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2130
		}
2131
	}
2132
2133
	/**
2134
	 * Check if Jetpack's Twitter tags should be used.
2135
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2136
	 *
2137
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2138
	 * @action plugins_loaded
2139
	 * @return null
2140
	 */
2141
	public function check_twitter_tags() {
2142
2143
		$active_plugins = self::get_active_plugins();
2144
2145
		if ( ! empty( $active_plugins ) ) {
2146
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2147
				if ( in_array( $plugin, $active_plugins ) ) {
2148
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2149
					break;
2150
				}
2151
			}
2152
		}
2153
2154
		/**
2155
		 * Allow Twitter Card Meta tags to be disabled.
2156
		 *
2157
		 * @since 2.6.0
2158
		 *
2159
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2160
		 */
2161
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2162
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2163
		}
2164
	}
2165
2166
	/**
2167
	 * Allows plugins to submit security reports.
2168
	 *
2169
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2170
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2171
	 * @param array  $args         See definitions above
2172
	 */
2173
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2174
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2175
	}
2176
2177
	/* Jetpack Options API */
2178
2179
	public static function get_option_names( $type = 'compact' ) {
2180
		return Jetpack_Options::get_option_names( $type );
2181
	}
2182
2183
	/**
2184
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2185
	 *
2186
	 * @param string $name    Option name
2187
	 * @param mixed  $default (optional)
2188
	 */
2189
	public static function get_option( $name, $default = false ) {
2190
		return Jetpack_Options::get_option( $name, $default );
2191
	}
2192
2193
	/**
2194
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2195
	 *
2196
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2197
	 * @param string $name  Option name
2198
	 * @param mixed  $value Option value
2199
	 */
2200
	public static function update_option( $name, $value ) {
2201
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2202
		return Jetpack_Options::update_option( $name, $value );
2203
	}
2204
2205
	/**
2206
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2207
	 *
2208
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2209
	 * @param array $array array( option name => option value, ... )
2210
	 */
2211
	public static function update_options( $array ) {
2212
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2213
		return Jetpack_Options::update_options( $array );
2214
	}
2215
2216
	/**
2217
	 * Deletes the given option.  May be passed multiple option names as an array.
2218
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2219
	 *
2220
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2221
	 * @param string|array $names
2222
	 */
2223
	public static function delete_option( $names ) {
2224
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2225
		return Jetpack_Options::delete_option( $names );
2226
	}
2227
2228
	/**
2229
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2230
	 *
2231
	 * Enters a user token into the user_tokens option
2232
	 *
2233
	 * @param int    $user_id The user id.
2234
	 * @param string $token The user token.
2235
	 * @param bool   $is_master_user Whether the user is the master user.
2236
	 * @return bool
2237
	 */
2238
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2239
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2240
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2241
	}
2242
2243
	/**
2244
	 * Returns an array of all PHP files in the specified absolute path.
2245
	 * Equivalent to glob( "$absolute_path/*.php" ).
2246
	 *
2247
	 * @param string $absolute_path The absolute path of the directory to search.
2248
	 * @return array Array of absolute paths to the PHP files.
2249
	 */
2250
	public static function glob_php( $absolute_path ) {
2251
		if ( function_exists( 'glob' ) ) {
2252
			return glob( "$absolute_path/*.php" );
2253
		}
2254
2255
		$absolute_path = untrailingslashit( $absolute_path );
2256
		$files         = array();
2257
		if ( ! $dir = @opendir( $absolute_path ) ) {
2258
			return $files;
2259
		}
2260
2261
		while ( false !== $file = readdir( $dir ) ) {
2262
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2263
				continue;
2264
			}
2265
2266
			$file = "$absolute_path/$file";
2267
2268
			if ( ! is_file( $file ) ) {
2269
				continue;
2270
			}
2271
2272
			$files[] = $file;
2273
		}
2274
2275
		closedir( $dir );
2276
2277
		return $files;
2278
	}
2279
2280
	public static function activate_new_modules( $redirect = false ) {
2281
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2282
			return;
2283
		}
2284
2285
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2286 View Code Duplication
		if ( ! $jetpack_old_version ) {
2287
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2288
			/** This action is documented in class.jetpack.php */
2289
			do_action( 'updating_jetpack_version', $version, false );
2290
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2291
		}
2292
2293
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2294
2295
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2296
			return;
2297
		}
2298
2299
		$active_modules     = self::get_active_modules();
2300
		$reactivate_modules = array();
2301
		foreach ( $active_modules as $active_module ) {
2302
			$module = self::get_module( $active_module );
2303
			if ( ! isset( $module['changed'] ) ) {
2304
				continue;
2305
			}
2306
2307
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2308
				continue;
2309
			}
2310
2311
			$reactivate_modules[] = $active_module;
2312
			self::deactivate_module( $active_module );
2313
		}
2314
2315
		$new_version = JETPACK__VERSION . ':' . time();
2316
		/** This action is documented in class.jetpack.php */
2317
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2318
		Jetpack_Options::update_options(
2319
			array(
2320
				'version'     => $new_version,
2321
				'old_version' => $jetpack_old_version,
2322
			)
2323
		);
2324
2325
		self::state( 'message', 'modules_activated' );
2326
2327
		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...
2328
2329
		if ( $redirect ) {
2330
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2331
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2332
				$page = $_GET['page'];
2333
			}
2334
2335
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2336
			exit;
2337
		}
2338
	}
2339
2340
	/**
2341
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2342
	 * Make sure to tuck away module "library" files in a sub-directory.
2343
	 */
2344
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2345
		static $modules = null;
2346
2347
		if ( ! isset( $modules ) ) {
2348
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2349
			// Use the cache if we're on the front-end and it's available...
2350
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2351
				$modules = $available_modules_option[ JETPACK__VERSION ];
2352
			} else {
2353
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2354
2355
				$modules = array();
2356
2357
				foreach ( $files as $file ) {
2358
					if ( ! $headers = self::get_module( $file ) ) {
2359
						continue;
2360
					}
2361
2362
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2363
				}
2364
2365
				Jetpack_Options::update_option(
2366
					'available_modules',
2367
					array(
2368
						JETPACK__VERSION => $modules,
2369
					)
2370
				);
2371
			}
2372
		}
2373
2374
		/**
2375
		 * Filters the array of modules available to be activated.
2376
		 *
2377
		 * @since 2.4.0
2378
		 *
2379
		 * @param array $modules Array of available modules.
2380
		 * @param string $min_version Minimum version number required to use modules.
2381
		 * @param string $max_version Maximum version number required to use modules.
2382
		 */
2383
		$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...
2384
2385
		if ( ! $min_version && ! $max_version ) {
2386
			return array_keys( $mods );
2387
		}
2388
2389
		$r = array();
2390
		foreach ( $mods as $slug => $introduced ) {
2391
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2392
				continue;
2393
			}
2394
2395
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2396
				continue;
2397
			}
2398
2399
			$r[] = $slug;
2400
		}
2401
2402
		return $r;
2403
	}
2404
2405
	/**
2406
	 * Default modules loaded on activation.
2407
	 */
2408
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2409
		$return = array();
2410
2411
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2412
			$module_data = self::get_module( $module );
2413
2414
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2415
				case 'yes':
2416
					$return[] = $module;
2417
					break;
2418
				case 'public':
2419
					if ( Jetpack_Options::get_option( 'public' ) ) {
2420
						$return[] = $module;
2421
					}
2422
					break;
2423
				case 'no':
2424
				default:
2425
					break;
2426
			}
2427
		}
2428
		/**
2429
		 * Filters the array of default modules.
2430
		 *
2431
		 * @since 2.5.0
2432
		 *
2433
		 * @param array $return Array of default modules.
2434
		 * @param string $min_version Minimum version number required to use modules.
2435
		 * @param string $max_version Maximum version number required to use modules.
2436
		 */
2437
		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...
2438
	}
2439
2440
	/**
2441
	 * Checks activated modules during auto-activation to determine
2442
	 * if any of those modules are being deprecated.  If so, close
2443
	 * them out, and add any replacement modules.
2444
	 *
2445
	 * Runs at priority 99 by default.
2446
	 *
2447
	 * This is run late, so that it can still activate a module if
2448
	 * the new module is a replacement for another that the user
2449
	 * currently has active, even if something at the normal priority
2450
	 * would kibosh everything.
2451
	 *
2452
	 * @since 2.6
2453
	 * @uses jetpack_get_default_modules filter
2454
	 * @param array $modules
2455
	 * @return array
2456
	 */
2457
	function handle_deprecated_modules( $modules ) {
2458
		$deprecated_modules = array(
2459
			'debug'            => null,  // Closed out and moved to the debugger library.
2460
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2461
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2462
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2463
		);
2464
2465
		// Don't activate SSO if they never completed activating WPCC.
2466
		if ( self::is_module_active( 'wpcc' ) ) {
2467
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2468
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2469
				$deprecated_modules['wpcc'] = null;
2470
			}
2471
		}
2472
2473
		foreach ( $deprecated_modules as $module => $replacement ) {
2474
			if ( self::is_module_active( $module ) ) {
2475
				self::deactivate_module( $module );
2476
				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...
2477
					$modules[] = $replacement;
2478
				}
2479
			}
2480
		}
2481
2482
		return array_unique( $modules );
2483
	}
2484
2485
	/**
2486
	 * Checks activated plugins during auto-activation to determine
2487
	 * if any of those plugins are in the list with a corresponding module
2488
	 * that is not compatible with the plugin. The module will not be allowed
2489
	 * to auto-activate.
2490
	 *
2491
	 * @since 2.6
2492
	 * @uses jetpack_get_default_modules filter
2493
	 * @param array $modules
2494
	 * @return array
2495
	 */
2496
	function filter_default_modules( $modules ) {
2497
2498
		$active_plugins = self::get_active_plugins();
2499
2500
		if ( ! empty( $active_plugins ) ) {
2501
2502
			// For each module we'd like to auto-activate...
2503
			foreach ( $modules as $key => $module ) {
2504
				// If there are potential conflicts for it...
2505
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2506
					// For each potential conflict...
2507
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2508
						// If that conflicting plugin is active...
2509
						if ( in_array( $plugin, $active_plugins ) ) {
2510
							// Remove that item from being auto-activated.
2511
							unset( $modules[ $key ] );
2512
						}
2513
					}
2514
				}
2515
			}
2516
		}
2517
2518
		return $modules;
2519
	}
2520
2521
	/**
2522
	 * Extract a module's slug from its full path.
2523
	 */
2524
	public static function get_module_slug( $file ) {
2525
		return str_replace( '.php', '', basename( $file ) );
2526
	}
2527
2528
	/**
2529
	 * Generate a module's path from its slug.
2530
	 */
2531
	public static function get_module_path( $slug ) {
2532
		/**
2533
		 * Filters the path of a modules.
2534
		 *
2535
		 * @since 7.4.0
2536
		 *
2537
		 * @param array $return The absolute path to a module's root php file
2538
		 * @param string $slug The module slug
2539
		 */
2540
		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...
2541
	}
2542
2543
	/**
2544
	 * Load module data from module file. Headers differ from WordPress
2545
	 * plugin headers to avoid them being identified as standalone
2546
	 * plugins on the WordPress plugins page.
2547
	 */
2548
	public static function get_module( $module ) {
2549
		$headers = array(
2550
			'name'                      => 'Module Name',
2551
			'description'               => 'Module Description',
2552
			'sort'                      => 'Sort Order',
2553
			'recommendation_order'      => 'Recommendation Order',
2554
			'introduced'                => 'First Introduced',
2555
			'changed'                   => 'Major Changes In',
2556
			'deactivate'                => 'Deactivate',
2557
			'free'                      => 'Free',
2558
			'requires_connection'       => 'Requires Connection',
2559
			'auto_activate'             => 'Auto Activate',
2560
			'module_tags'               => 'Module Tags',
2561
			'feature'                   => 'Feature',
2562
			'additional_search_queries' => 'Additional Search Queries',
2563
			'plan_classes'              => 'Plans',
2564
		);
2565
2566
		$file = self::get_module_path( self::get_module_slug( $module ) );
2567
2568
		$mod = self::get_file_data( $file, $headers );
2569
		if ( empty( $mod['name'] ) ) {
2570
			return false;
2571
		}
2572
2573
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2574
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2575
		$mod['deactivate']           = empty( $mod['deactivate'] );
2576
		$mod['free']                 = empty( $mod['free'] );
2577
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2578
2579
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2580
			$mod['auto_activate'] = 'No';
2581
		} else {
2582
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2583
		}
2584
2585
		if ( $mod['module_tags'] ) {
2586
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2587
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2588
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2589
		} else {
2590
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2591
		}
2592
2593 View Code Duplication
		if ( $mod['plan_classes'] ) {
2594
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2595
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2596
		} else {
2597
			$mod['plan_classes'] = array( 'free' );
2598
		}
2599
2600 View Code Duplication
		if ( $mod['feature'] ) {
2601
			$mod['feature'] = explode( ',', $mod['feature'] );
2602
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2603
		} else {
2604
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2605
		}
2606
2607
		/**
2608
		 * Filters the feature array on a module.
2609
		 *
2610
		 * This filter allows you to control where each module is filtered: Recommended,
2611
		 * and the default "Other" listing.
2612
		 *
2613
		 * @since 3.5.0
2614
		 *
2615
		 * @param array   $mod['feature'] The areas to feature this module:
2616
		 *     'Recommended' shows on the main Jetpack admin screen.
2617
		 *     'Other' should be the default if no other value is in the array.
2618
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2619
		 * @param array   $mod All the currently assembled module data.
2620
		 */
2621
		$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...
2622
2623
		/**
2624
		 * Filter the returned data about a module.
2625
		 *
2626
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2627
		 * so please be careful.
2628
		 *
2629
		 * @since 3.6.0
2630
		 *
2631
		 * @param array   $mod    The details of the requested module.
2632
		 * @param string  $module The slug of the module, e.g. sharedaddy
2633
		 * @param string  $file   The path to the module source file.
2634
		 */
2635
		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...
2636
	}
2637
2638
	/**
2639
	 * Like core's get_file_data implementation, but caches the result.
2640
	 */
2641
	public static function get_file_data( $file, $headers ) {
2642
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2643
		$file_name = basename( $file );
2644
2645
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2646
2647
		$file_data_option = get_transient( $cache_key );
2648
2649
		if ( ! is_array( $file_data_option ) ) {
2650
			delete_transient( $cache_key );
2651
			$file_data_option = false;
2652
		}
2653
2654
		if ( false === $file_data_option ) {
2655
			$file_data_option = array();
2656
		}
2657
2658
		$key           = md5( $file_name . serialize( $headers ) );
2659
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2660
2661
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2662
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2663
			return $file_data_option[ $key ];
2664
		}
2665
2666
		$data = get_file_data( $file, $headers );
2667
2668
		$file_data_option[ $key ] = $data;
2669
2670
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2671
2672
		return $data;
2673
	}
2674
2675
	/**
2676
	 * Return translated module tag.
2677
	 *
2678
	 * @param string $tag Tag as it appears in each module heading.
2679
	 *
2680
	 * @return mixed
2681
	 */
2682
	public static function translate_module_tag( $tag ) {
2683
		return jetpack_get_module_i18n_tag( $tag );
2684
	}
2685
2686
	/**
2687
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2688
	 *
2689
	 * @since 3.9.2
2690
	 *
2691
	 * @param array $modules
2692
	 *
2693
	 * @return string|void
2694
	 */
2695
	public static function get_translated_modules( $modules ) {
2696
		foreach ( $modules as $index => $module ) {
2697
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2698
			if ( isset( $module['name'] ) ) {
2699
				$modules[ $index ]['name'] = $i18n_module['name'];
2700
			}
2701
			if ( isset( $module['description'] ) ) {
2702
				$modules[ $index ]['description']       = $i18n_module['description'];
2703
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2704
			}
2705
		}
2706
		return $modules;
2707
	}
2708
2709
	/**
2710
	 * Get a list of activated modules as an array of module slugs.
2711
	 */
2712
	public static function get_active_modules() {
2713
		$active = Jetpack_Options::get_option( 'active_modules' );
2714
2715
		if ( ! is_array( $active ) ) {
2716
			$active = array();
2717
		}
2718
2719
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2720
			$active[] = 'vaultpress';
2721
		} else {
2722
			$active = array_diff( $active, array( 'vaultpress' ) );
2723
		}
2724
2725
		// If protect is active on the main site of a multisite, it should be active on all sites.
2726
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2727
			$active[] = 'protect';
2728
		}
2729
2730
		/**
2731
		 * Allow filtering of the active modules.
2732
		 *
2733
		 * Gives theme and plugin developers the power to alter the modules that
2734
		 * are activated on the fly.
2735
		 *
2736
		 * @since 5.8.0
2737
		 *
2738
		 * @param array $active Array of active module slugs.
2739
		 */
2740
		$active = apply_filters( 'jetpack_active_modules', $active );
2741
2742
		return array_unique( $active );
2743
	}
2744
2745
	/**
2746
	 * Check whether or not a Jetpack module is active.
2747
	 *
2748
	 * @param string $module The slug of a Jetpack module.
2749
	 * @return bool
2750
	 *
2751
	 * @static
2752
	 */
2753
	public static function is_module_active( $module ) {
2754
		return in_array( $module, self::get_active_modules() );
2755
	}
2756
2757
	public static function is_module( $module ) {
2758
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2759
	}
2760
2761
	/**
2762
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2763
	 *
2764
	 * @param bool $catch True to start catching, False to stop.
2765
	 *
2766
	 * @static
2767
	 */
2768
	public static function catch_errors( $catch ) {
2769
		static $display_errors, $error_reporting;
2770
2771
		if ( $catch ) {
2772
			$display_errors  = @ini_set( 'display_errors', 1 );
2773
			$error_reporting = @error_reporting( E_ALL );
2774
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2775
		} else {
2776
			@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...
2777
			@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...
2778
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2779
		}
2780
	}
2781
2782
	/**
2783
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2784
	 */
2785
	public static function catch_errors_on_shutdown() {
2786
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2787
	}
2788
2789
	/**
2790
	 * Rewrite any string to make paths easier to read.
2791
	 *
2792
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2793
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2794
	 *
2795
	 * @param $string
2796
	 * @return mixed
2797
	 */
2798
	public static function alias_directories( $string ) {
2799
		// ABSPATH has a trailing slash.
2800
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2801
		// WP_CONTENT_DIR does not have a trailing slash.
2802
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2803
2804
		return $string;
2805
	}
2806
2807
	public static function activate_default_modules(
2808
		$min_version = false,
2809
		$max_version = false,
2810
		$other_modules = array(),
2811
		$redirect = null,
2812
		$send_state_messages = null
2813
	) {
2814
		$jetpack = self::init();
2815
2816
		if ( is_null( $redirect ) ) {
2817
			if (
2818
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2819
			||
2820
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2821
			||
2822
				( defined( 'WP_CLI' ) && WP_CLI )
2823
			||
2824
				( defined( 'DOING_CRON' ) && DOING_CRON )
2825
			||
2826
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2827
			) {
2828
				$redirect = false;
2829
			} elseif ( is_admin() ) {
2830
				$redirect = true;
2831
			} else {
2832
				$redirect = false;
2833
			}
2834
		}
2835
2836
		if ( is_null( $send_state_messages ) ) {
2837
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2838
		}
2839
2840
		$modules = self::get_default_modules( $min_version, $max_version );
2841
		$modules = array_merge( $other_modules, $modules );
2842
2843
		// Look for standalone plugins and disable if active.
2844
2845
		$to_deactivate = array();
2846
		foreach ( $modules as $module ) {
2847
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2848
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2849
			}
2850
		}
2851
2852
		$deactivated = array();
2853
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2854
			list( $probable_file, $probable_title ) = $deactivate_me;
2855
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2856
				$deactivated[] = $module;
2857
			}
2858
		}
2859
2860
		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...
2861
			if ( $send_state_messages ) {
2862
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2863
			}
2864
2865
			if ( $redirect ) {
2866
				$url = add_query_arg(
2867
					array(
2868
						'action'   => 'activate_default_modules',
2869
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2870
					),
2871
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2872
				);
2873
				wp_safe_redirect( $url );
2874
				exit;
2875
			}
2876
		}
2877
2878
		/**
2879
		 * Fires before default modules are activated.
2880
		 *
2881
		 * @since 1.9.0
2882
		 *
2883
		 * @param string $min_version Minimum version number required to use modules.
2884
		 * @param string $max_version Maximum version number required to use modules.
2885
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2886
		 */
2887
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2888
2889
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2890
		if ( $send_state_messages ) {
2891
			self::restate();
2892
			self::catch_errors( true );
2893
		}
2894
2895
		$active = self::get_active_modules();
2896
2897
		foreach ( $modules as $module ) {
2898
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2899
				$active[] = $module;
2900
				self::update_active_modules( $active );
2901
				continue;
2902
			}
2903
2904
			if ( $send_state_messages && in_array( $module, $active ) ) {
2905
				$module_info = self::get_module( $module );
2906 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2907
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2908
					if ( $active_state = self::state( $state ) ) {
2909
						$active_state = explode( ',', $active_state );
2910
					} else {
2911
						$active_state = array();
2912
					}
2913
					$active_state[] = $module;
2914
					self::state( $state, implode( ',', $active_state ) );
2915
				}
2916
				continue;
2917
			}
2918
2919
			$file = self::get_module_path( $module );
2920
			if ( ! file_exists( $file ) ) {
2921
				continue;
2922
			}
2923
2924
			// we'll override this later if the plugin can be included without fatal error
2925
			if ( $redirect ) {
2926
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2927
			}
2928
2929
			if ( $send_state_messages ) {
2930
				self::state( 'error', 'module_activation_failed' );
2931
				self::state( 'module', $module );
2932
			}
2933
2934
			ob_start();
2935
			require_once $file;
2936
2937
			$active[] = $module;
2938
2939 View Code Duplication
			if ( $send_state_messages ) {
2940
2941
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2942
				if ( $active_state = self::state( $state ) ) {
2943
					$active_state = explode( ',', $active_state );
2944
				} else {
2945
					$active_state = array();
2946
				}
2947
				$active_state[] = $module;
2948
				self::state( $state, implode( ',', $active_state ) );
2949
			}
2950
2951
			self::update_active_modules( $active );
2952
2953
			ob_end_clean();
2954
		}
2955
2956
		if ( $send_state_messages ) {
2957
			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...
2958
			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...
2959
		}
2960
2961
		self::catch_errors( false );
2962
		/**
2963
		 * Fires when default modules are activated.
2964
		 *
2965
		 * @since 1.9.0
2966
		 *
2967
		 * @param string $min_version Minimum version number required to use modules.
2968
		 * @param string $max_version Maximum version number required to use modules.
2969
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2970
		 */
2971
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2972
	}
2973
2974
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2975
		/**
2976
		 * Fires before a module is activated.
2977
		 *
2978
		 * @since 2.6.0
2979
		 *
2980
		 * @param string $module Module slug.
2981
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2982
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2983
		 */
2984
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2985
2986
		$jetpack = self::init();
2987
2988
		if ( ! strlen( $module ) ) {
2989
			return false;
2990
		}
2991
2992
		if ( ! self::is_module( $module ) ) {
2993
			return false;
2994
		}
2995
2996
		// If it's already active, then don't do it again
2997
		$active = self::get_active_modules();
2998
		foreach ( $active as $act ) {
2999
			if ( $act == $module ) {
3000
				return true;
3001
			}
3002
		}
3003
3004
		$module_data = self::get_module( $module );
3005
3006
		$is_offline_mode = ( new Status() )->is_offline_mode();
3007
		if ( ! self::is_active() ) {
3008
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3009
				return false;
3010
			}
3011
3012
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3013
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3014
				return false;
3015
			}
3016
		}
3017
3018
		// Check and see if the old plugin is active
3019
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3020
			// Deactivate the old plugin
3021
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3022
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3023
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3024
				self::state( 'deactivated_plugins', $module );
3025
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3026
				exit;
3027
			}
3028
		}
3029
3030
		// Protect won't work with mis-configured IPs
3031
		if ( 'protect' === $module ) {
3032
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3033
			if ( ! jetpack_protect_get_ip() ) {
3034
				self::state( 'message', 'protect_misconfigured_ip' );
3035
				return false;
3036
			}
3037
		}
3038
3039
		if ( ! Jetpack_Plan::supports( $module ) ) {
3040
			return false;
3041
		}
3042
3043
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3044
		self::state( 'module', $module );
3045
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3046
3047
		self::catch_errors( true );
3048
		ob_start();
3049
		require self::get_module_path( $module );
3050
		/** This action is documented in class.jetpack.php */
3051
		do_action( 'jetpack_activate_module', $module );
3052
		$active[] = $module;
3053
		self::update_active_modules( $active );
3054
3055
		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...
3056
		ob_end_clean();
3057
		self::catch_errors( false );
3058
3059
		if ( $redirect ) {
3060
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3061
		}
3062
		if ( $exit ) {
3063
			exit;
3064
		}
3065
		return true;
3066
	}
3067
3068
	function activate_module_actions( $module ) {
3069
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3070
	}
3071
3072
	public static function deactivate_module( $module ) {
3073
		/**
3074
		 * Fires when a module is deactivated.
3075
		 *
3076
		 * @since 1.9.0
3077
		 *
3078
		 * @param string $module Module slug.
3079
		 */
3080
		do_action( 'jetpack_pre_deactivate_module', $module );
3081
3082
		$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...
3083
3084
		$active = self::get_active_modules();
3085
		$new    = array_filter( array_diff( $active, (array) $module ) );
3086
3087
		return self::update_active_modules( $new );
3088
	}
3089
3090
	public static function enable_module_configurable( $module ) {
3091
		$module = self::get_module_slug( $module );
3092
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3093
	}
3094
3095
	/**
3096
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3097
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3098
	 *
3099
	 * @param string $module Module slug
3100
	 * @return string $url module configuration URL
3101
	 */
3102
	public static function module_configuration_url( $module ) {
3103
		$module      = self::get_module_slug( $module );
3104
		$default_url = self::admin_url() . "#/settings?term=$module";
3105
		/**
3106
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3107
		 *
3108
		 * @since 6.9.0
3109
		 *
3110
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3111
		 */
3112
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3113
3114
		return $url;
3115
	}
3116
3117
	/* Installation */
3118
	public static function bail_on_activation( $message, $deactivate = true ) {
3119
		?>
3120
<!doctype html>
3121
<html>
3122
<head>
3123
<meta charset="<?php bloginfo( 'charset' ); ?>">
3124
<style>
3125
* {
3126
	text-align: center;
3127
	margin: 0;
3128
	padding: 0;
3129
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3130
}
3131
p {
3132
	margin-top: 1em;
3133
	font-size: 18px;
3134
}
3135
</style>
3136
<body>
3137
<p><?php echo esc_html( $message ); ?></p>
3138
</body>
3139
</html>
3140
		<?php
3141
		if ( $deactivate ) {
3142
			$plugins = get_option( 'active_plugins' );
3143
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3144
			$update  = false;
3145
			foreach ( $plugins as $i => $plugin ) {
3146
				if ( $plugin === $jetpack ) {
3147
					$plugins[ $i ] = false;
3148
					$update        = true;
3149
				}
3150
			}
3151
3152
			if ( $update ) {
3153
				update_option( 'active_plugins', array_filter( $plugins ) );
3154
			}
3155
		}
3156
		exit;
3157
	}
3158
3159
	/**
3160
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3161
	 *
3162
	 * @static
3163
	 */
3164
	public static function plugin_activation( $network_wide ) {
3165
		Jetpack_Options::update_option( 'activated', 1 );
3166
3167
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3168
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3169
		}
3170
3171
		if ( $network_wide ) {
3172
			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...
3173
		}
3174
3175
		// For firing one-off events (notices) immediately after activation
3176
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3177
3178
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3179
3180
		Health::on_jetpack_activated();
3181
3182
		self::plugin_initialize();
3183
	}
3184
3185
	public static function get_activation_source( $referer_url ) {
3186
3187
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3188
			return array( 'wp-cli', null );
3189
		}
3190
3191
		$referer = wp_parse_url( $referer_url );
3192
3193
		$source_type  = 'unknown';
3194
		$source_query = null;
3195
3196
		if ( ! is_array( $referer ) ) {
3197
			return array( $source_type, $source_query );
3198
		}
3199
3200
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3201
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3202
3203
		if ( isset( $referer['query'] ) ) {
3204
			parse_str( $referer['query'], $query_parts );
3205
		} else {
3206
			$query_parts = array();
3207
		}
3208
3209
		if ( $plugins_path === $referer['path'] ) {
3210
			$source_type = 'list';
3211
		} elseif ( $plugins_install_path === $referer['path'] ) {
3212
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3213
			switch ( $tab ) {
3214
				case 'popular':
3215
					$source_type = 'popular';
3216
					break;
3217
				case 'recommended':
3218
					$source_type = 'recommended';
3219
					break;
3220
				case 'favorites':
3221
					$source_type = 'favorites';
3222
					break;
3223
				case 'search':
3224
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3225
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3226
					break;
3227
				default:
3228
					$source_type = 'featured';
3229
			}
3230
		}
3231
3232
		return array( $source_type, $source_query );
3233
	}
3234
3235
	/**
3236
	 * Runs before bumping version numbers up to a new version
3237
	 *
3238
	 * @param string $version    Version:timestamp.
3239
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3240
	 */
3241
	public static function do_version_bump( $version, $old_version ) {
3242
		if ( $old_version ) { // For existing Jetpack installations.
3243
3244
			// If a front end page is visited after the update, the 'wp' action will fire.
3245
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3246
3247
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3248
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3249
		}
3250
	}
3251
3252
	/**
3253
	 * Sets the display_update_modal state.
3254
	 */
3255
	public static function set_update_modal_display() {
3256
		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...
3257
	}
3258
3259
	/**
3260
	 * Sets the internal version number and activation state.
3261
	 *
3262
	 * @static
3263
	 */
3264
	public static function plugin_initialize() {
3265
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3266
			Jetpack_Options::update_option( 'activated', 2 );
3267
		}
3268
3269 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3270
			$version = $old_version = JETPACK__VERSION . ':' . time();
3271
			/** This action is documented in class.jetpack.php */
3272
			do_action( 'updating_jetpack_version', $version, false );
3273
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3274
		}
3275
3276
		self::load_modules();
3277
3278
		Jetpack_Options::delete_option( 'do_activate' );
3279
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3280
	}
3281
3282
	/**
3283
	 * Removes all connection options
3284
	 *
3285
	 * @static
3286
	 */
3287
	public static function plugin_deactivation() {
3288
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3289
		$tracking = new Tracking();
3290
		$tracking->record_user_event( 'deactivate_plugin', array() );
3291
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3292
			Jetpack_Network::init()->deactivate();
3293
		} else {
3294
			self::disconnect( false );
3295
			// Jetpack_Heartbeat::init()->deactivate();
3296
		}
3297
	}
3298
3299
	/**
3300
	 * Disconnects from the Jetpack servers.
3301
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3302
	 *
3303
	 * @static
3304
	 */
3305
	public static function disconnect( $update_activated_state = true ) {
3306
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3307
3308
		$connection = self::connection();
3309
		$connection->clean_nonces( true );
3310
3311
		// If the site is in an IDC because sync is not allowed,
3312
		// let's make sure to not disconnect the production site.
3313
		if ( ! self::validate_sync_error_idc_option() ) {
3314
			$tracking = new Tracking();
3315
			$tracking->record_user_event( 'disconnect_site', array() );
3316
3317
			$connection->disconnect_site_wpcom( true );
3318
		}
3319
3320
		$connection->delete_all_connection_tokens( true );
3321
		Jetpack_IDC::clear_all_idc_options();
3322
3323
		if ( $update_activated_state ) {
3324
			Jetpack_Options::update_option( 'activated', 4 );
3325
		}
3326
3327
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3328
			// Check then record unique disconnection if site has never been disconnected previously
3329
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3330
				$jetpack_unique_connection['disconnected'] = 1;
3331
			} else {
3332
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3333
					// track unique disconnect
3334
					$jetpack = self::init();
3335
3336
					$jetpack->stat( 'connections', 'unique-disconnect' );
3337
					$jetpack->do_stats( 'server_side' );
3338
				}
3339
				// increment number of times disconnected
3340
				$jetpack_unique_connection['disconnected'] += 1;
3341
			}
3342
3343
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3344
		}
3345
3346
		// Delete all the sync related data. Since it could be taking up space.
3347
		Sender::get_instance()->uninstall();
3348
3349
	}
3350
3351
	/**
3352
	 * Unlinks the current user from the linked WordPress.com user.
3353
	 *
3354
	 * @deprecated since 7.7
3355
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3356
	 *
3357
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
3358
	 * @return Boolean Whether the disconnection of the user was successful.
3359
	 */
3360
	public static function unlink_user( $user_id = null ) {
3361
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3362
		return Connection_Manager::disconnect_user( $user_id );
3363
	}
3364
3365
	/**
3366
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3367
	 */
3368
	public static function try_registration() {
3369
		$terms_of_service = new Terms_Of_Service();
3370
		// The user has agreed to the TOS at some point by now.
3371
		$terms_of_service->agree();
3372
3373
		// Let's get some testing in beta versions and such.
3374
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3375
			// Before attempting to connect, let's make sure that the domains are viable.
3376
			$domains_to_check = array_unique(
3377
				array(
3378
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3379
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3380
				)
3381
			);
3382
			foreach ( $domains_to_check as $domain ) {
3383
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3382 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...
3384
				if ( is_wp_error( $result ) ) {
3385
					return $result;
3386
				}
3387
			}
3388
		}
3389
3390
		$result = self::register();
3391
3392
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3393
		if ( ! $result || is_wp_error( $result ) ) {
3394
			return $result;
3395
		} else {
3396
			return true;
3397
		}
3398
	}
3399
3400
	/**
3401
	 * Tracking an internal event log. Try not to put too much chaff in here.
3402
	 *
3403
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3404
	 */
3405
	public static function log( $code, $data = null ) {
3406
		// only grab the latest 200 entries
3407
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3408
3409
		// Append our event to the log
3410
		$log_entry = array(
3411
			'time'    => time(),
3412
			'user_id' => get_current_user_id(),
3413
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3414
			'code'    => $code,
3415
		);
3416
		// Don't bother storing it unless we've got some.
3417
		if ( ! is_null( $data ) ) {
3418
			$log_entry['data'] = $data;
3419
		}
3420
		$log[] = $log_entry;
3421
3422
		// Try add_option first, to make sure it's not autoloaded.
3423
		// @todo: Add an add_option method to Jetpack_Options
3424
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3425
			Jetpack_Options::update_option( 'log', $log );
3426
		}
3427
3428
		/**
3429
		 * Fires when Jetpack logs an internal event.
3430
		 *
3431
		 * @since 3.0.0
3432
		 *
3433
		 * @param array $log_entry {
3434
		 *  Array of details about the log entry.
3435
		 *
3436
		 *  @param string time Time of the event.
3437
		 *  @param int user_id ID of the user who trigerred the event.
3438
		 *  @param int blog_id Jetpack Blog ID.
3439
		 *  @param string code Unique name for the event.
3440
		 *  @param string data Data about the event.
3441
		 * }
3442
		 */
3443
		do_action( 'jetpack_log_entry', $log_entry );
3444
	}
3445
3446
	/**
3447
	 * Get the internal event log.
3448
	 *
3449
	 * @param $event (string) - only return the specific log events
3450
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3451
	 *
3452
	 * @return array of log events || WP_Error for invalid params
3453
	 */
3454
	public static function get_log( $event = false, $num = false ) {
3455
		if ( $event && ! is_string( $event ) ) {
3456
			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...
3457
		}
3458
3459
		if ( $num && ! is_numeric( $num ) ) {
3460
			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...
3461
		}
3462
3463
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3464
3465
		// If nothing set - act as it did before, otherwise let's start customizing the output
3466
		if ( ! $num && ! $event ) {
3467
			return $entire_log;
3468
		} else {
3469
			$entire_log = array_reverse( $entire_log );
3470
		}
3471
3472
		$custom_log_output = array();
3473
3474
		if ( $event ) {
3475
			foreach ( $entire_log as $log_event ) {
3476
				if ( $event == $log_event['code'] ) {
3477
					$custom_log_output[] = $log_event;
3478
				}
3479
			}
3480
		} else {
3481
			$custom_log_output = $entire_log;
3482
		}
3483
3484
		if ( $num ) {
3485
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3486
		}
3487
3488
		return $custom_log_output;
3489
	}
3490
3491
	/**
3492
	 * Log modification of important settings.
3493
	 */
3494
	public static function log_settings_change( $option, $old_value, $value ) {
3495
		switch ( $option ) {
3496
			case 'jetpack_sync_non_public_post_stati':
3497
				self::log( $option, $value );
3498
				break;
3499
		}
3500
	}
3501
3502
	/**
3503
	 * Return stat data for WPCOM sync
3504
	 */
3505
	public static function get_stat_data( $encode = true, $extended = true ) {
3506
		$data = Jetpack_Heartbeat::generate_stats_array();
3507
3508
		if ( $extended ) {
3509
			$additional_data = self::get_additional_stat_data();
3510
			$data            = array_merge( $data, $additional_data );
3511
		}
3512
3513
		if ( $encode ) {
3514
			return json_encode( $data );
3515
		}
3516
3517
		return $data;
3518
	}
3519
3520
	/**
3521
	 * Get additional stat data to sync to WPCOM
3522
	 */
3523
	public static function get_additional_stat_data( $prefix = '' ) {
3524
		$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...
3525
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3526
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3527
		$return[ "{$prefix}site-count" ]    = 0;
3528
3529
		if ( function_exists( 'get_blog_count' ) ) {
3530
			$return[ "{$prefix}site-count" ] = get_blog_count();
3531
		}
3532
		return $return;
3533
	}
3534
3535
	private static function get_site_user_count() {
3536
		global $wpdb;
3537
3538
		if ( function_exists( 'wp_is_large_network' ) ) {
3539
			if ( wp_is_large_network( 'users' ) ) {
3540
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3541
			}
3542
		}
3543
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3544
			// It wasn't there, so regenerate the data and save the transient
3545
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3546
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3547
		}
3548
		return $user_count;
3549
	}
3550
3551
	/* Admin Pages */
3552
3553
	function admin_init() {
3554
		// If the plugin is not connected, display a connect message.
3555
		if (
3556
			// the plugin was auto-activated and needs its candy
3557
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3558
		||
3559
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3560
			! Jetpack_Options::get_option( 'activated' )
3561
		) {
3562
			self::plugin_initialize();
3563
		}
3564
3565
		$is_offline_mode = ( new Status() )->is_offline_mode();
3566
		if ( ! self::is_active() && ! $is_offline_mode ) {
3567
			Jetpack_Connection_Banner::init();
3568
			/** Already documented in automattic/jetpack-connection::src/class-client.php */
3569
		} elseif ( ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) && ! apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
3570
			// Upgrade: 1.1 -> 1.1.1
3571
			// Check and see if host can verify the Jetpack servers' SSL certificate
3572
			$args = array();
3573
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3574
		}
3575
3576
		Jetpack_Wizard_Banner::init();
3577
3578
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3579
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3580
		}
3581
3582
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3583
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3584
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3585
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3586
3587
		if ( self::is_active() || $is_offline_mode ) {
3588
			// Artificially throw errors in certain specific cases during plugin activation.
3589
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3590
		}
3591
3592
		// Add custom column in wp-admin/users.php to show whether user is linked.
3593
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3594
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3595
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3596
	}
3597
3598
	function admin_body_class( $admin_body_class = '' ) {
3599
		$classes = explode( ' ', trim( $admin_body_class ) );
3600
3601
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3602
3603
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3604
		return " $admin_body_class ";
3605
	}
3606
3607
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3608
		return $admin_body_class . ' jetpack-pagestyles ';
3609
	}
3610
3611
	/**
3612
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3613
	 * This function artificially throws errors for such cases (per a specific list).
3614
	 *
3615
	 * @param string $plugin The activated plugin.
3616
	 */
3617
	function throw_error_on_activate_plugin( $plugin ) {
3618
		$active_modules = self::get_active_modules();
3619
3620
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3621
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3622
			$throw = false;
3623
3624
			// Try and make sure it really was the stats plugin
3625
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3626
				if ( 'stats.php' == basename( $plugin ) ) {
3627
					$throw = true;
3628
				}
3629
			} else {
3630
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3631
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3632
					$throw = true;
3633
				}
3634
			}
3635
3636
			if ( $throw ) {
3637
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3638
			}
3639
		}
3640
	}
3641
3642
	function intercept_plugin_error_scrape_init() {
3643
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3644
	}
3645
3646
	function intercept_plugin_error_scrape( $action, $result ) {
3647
		if ( ! $result ) {
3648
			return;
3649
		}
3650
3651
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3652
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3653
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3654
			}
3655
		}
3656
	}
3657
3658
	/**
3659
	 * Register the remote file upload request handlers, if needed.
3660
	 *
3661
	 * @access public
3662
	 */
3663
	public function add_remote_request_handlers() {
3664
		// Remote file uploads are allowed only via AJAX requests.
3665
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3666
			return;
3667
		}
3668
3669
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3670
		$remote_request_actions = array(
3671
			'jetpack_upload_file',
3672
			'jetpack_update_file',
3673
		);
3674
3675
		// phpcs:ignore WordPress.Security.NonceVerification
3676
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3677
			return;
3678
		}
3679
3680
		// Require Jetpack authentication for the remote file upload AJAX requests.
3681
		if ( ! $this->connection_manager ) {
3682
			$this->connection_manager = new Connection_Manager();
3683
		}
3684
3685
		$this->connection_manager->require_jetpack_authentication();
3686
3687
		// Register the remote file upload AJAX handlers.
3688
		foreach ( $remote_request_actions as $action ) {
3689
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3690
		}
3691
	}
3692
3693
	/**
3694
	 * Handler for Jetpack remote file uploads.
3695
	 *
3696
	 * @access public
3697
	 */
3698
	public function remote_request_handlers() {
3699
		$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...
3700
3701
		switch ( current_filter() ) {
3702
			case 'wp_ajax_nopriv_jetpack_upload_file':
3703
				$response = $this->upload_handler();
3704
				break;
3705
3706
			case 'wp_ajax_nopriv_jetpack_update_file':
3707
				$response = $this->upload_handler( true );
3708
				break;
3709
			default:
3710
				$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...
3711
				break;
3712
		}
3713
3714
		if ( ! $response ) {
3715
			$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...
3716
		}
3717
3718
		if ( is_wp_error( $response ) ) {
3719
			$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...
3720
			$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...
3721
			$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...
3722
3723
			if ( ! is_int( $status_code ) ) {
3724
				$status_code = 400;
3725
			}
3726
3727
			status_header( $status_code );
3728
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3729
		}
3730
3731
		status_header( 200 );
3732
		if ( true === $response ) {
3733
			exit;
3734
		}
3735
3736
		die( json_encode( (object) $response ) );
3737
	}
3738
3739
	/**
3740
	 * Uploads a file gotten from the global $_FILES.
3741
	 * If `$update_media_item` is true and `post_id` is defined
3742
	 * the attachment file of the media item (gotten through of the post_id)
3743
	 * will be updated instead of add a new one.
3744
	 *
3745
	 * @param  boolean $update_media_item - update media attachment
3746
	 * @return array - An array describing the uploadind files process
3747
	 */
3748
	function upload_handler( $update_media_item = false ) {
3749
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3750
			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...
3751
		}
3752
3753
		$user = wp_authenticate( '', '' );
3754
		if ( ! $user || is_wp_error( $user ) ) {
3755
			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...
3756
		}
3757
3758
		wp_set_current_user( $user->ID );
3759
3760
		if ( ! current_user_can( 'upload_files' ) ) {
3761
			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...
3762
		}
3763
3764
		if ( empty( $_FILES ) ) {
3765
			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...
3766
		}
3767
3768
		foreach ( array_keys( $_FILES ) as $files_key ) {
3769
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3770
				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...
3771
			}
3772
		}
3773
3774
		$media_keys = array_keys( $_FILES['media'] );
3775
3776
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

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

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

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

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

Loading history...
4741
	 * @return string Signed user role.
4742
	 */
4743
	public static function sign_role( $role, $user_id = null ) {
4744
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4745
		return self::connection()->sign_role( $role, $user_id );
4746
	}
4747
4748
	/**
4749
	 * Builds a URL to the Jetpack connection auth page
4750
	 *
4751
	 * @since 3.9.5
4752
	 *
4753
	 * @param bool        $raw If true, URL will not be escaped.
4754
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4755
	 *                              If string, will be a custom redirect.
4756
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4757
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4758
	 *
4759
	 * @return string Connect URL
4760
	 */
4761
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4762
		$site_id    = Jetpack_Options::get_option( 'id' );
4763
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

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

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5950
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
5951
		if ( ! $token || empty( $token->secret ) ) {
5952
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5953
		}
5954
5955
		$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' );
5956
5957
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5958
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5959
			/**
5960
			 * Jetpack authorisation request Error.
5961
			 *
5962
			 * @since 7.5.0
5963
			 */
5964
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5965
			$die_error = sprintf(
5966
				/* translators: %s is a URL */
5967
				__( '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' ),
5968
				Redirect::get_url( 'jetpack-support-double-encoding' )
5969
			);
5970
		}
5971
5972
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5973
5974
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5975
			$signature = $jetpack_signature->sign_request(
5976
				$environment['token'],
5977
				$environment['timestamp'],
5978
				$environment['nonce'],
5979
				'',
5980
				'GET',
5981
				$environment['jetpack_json_api_original_query'],
5982
				null,
5983
				true
5984
			);
5985
		} else {
5986
			$signature = $jetpack_signature->sign_current_request(
5987
				array(
5988
					'body'   => null,
5989
					'method' => 'GET',
5990
				)
5991
			);
5992
		}
5993
5994
		if ( ! $signature ) {
5995
			wp_die( $die_error );
5996
		} elseif ( is_wp_error( $signature ) ) {
5997
			wp_die( $die_error );
5998
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5999
			if ( is_ssl() ) {
6000
				// 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
6001
				$signature = $jetpack_signature->sign_current_request(
6002
					array(
6003
						'scheme' => 'http',
6004
						'body'   => null,
6005
						'method' => 'GET',
6006
					)
6007
				);
6008
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6009
					wp_die( $die_error );
6010
				}
6011
			} else {
6012
				wp_die( $die_error );
6013
			}
6014
		}
6015
6016
		$timestamp = (int) $environment['timestamp'];
6017
		$nonce     = stripslashes( (string) $environment['nonce'] );
6018
6019
		if ( ! $this->connection_manager ) {
6020
			$this->connection_manager = new Connection_Manager();
6021
		}
6022
6023
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6024
			// De-nonce the nonce, at least for 5 minutes.
6025
			// 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)
6026
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6027
			if ( $old_nonce_time < time() - 300 ) {
6028
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6029
			}
6030
		}
6031
6032
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6033
		$data_filters = array(
6034
			'state'        => 'opaque',
6035
			'client_id'    => 'int',
6036
			'client_title' => 'string',
6037
			'client_image' => 'url',
6038
		);
6039
6040
		foreach ( $data_filters as $key => $sanitation ) {
6041
			if ( ! isset( $data->$key ) ) {
6042
				wp_die( $die_error );
6043
			}
6044
6045
			switch ( $sanitation ) {
6046
				case 'int':
6047
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6048
					break;
6049
				case 'opaque':
6050
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6051
					break;
6052
				case 'string':
6053
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6054
					break;
6055
				case 'url':
6056
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6057
					break;
6058
			}
6059
		}
6060
6061
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6062
			wp_die( $die_error );
6063
		}
6064
	}
6065
6066
	function login_message_json_api_authorization( $message ) {
6067
		return '<p class="message">' . sprintf(
6068
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6069
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6070
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6071
	}
6072
6073
	/**
6074
	 * Get $content_width, but with a <s>twist</s> filter.
6075
	 */
6076
	public static function get_content_width() {
6077
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6078
			? $GLOBALS['content_width']
6079
			: false;
6080
		/**
6081
		 * Filter the Content Width value.
6082
		 *
6083
		 * @since 2.2.3
6084
		 *
6085
		 * @param string $content_width Content Width value.
6086
		 */
6087
		return apply_filters( 'jetpack_content_width', $content_width );
6088
	}
6089
6090
	/**
6091
	 * Pings the WordPress.com Mirror Site for the specified options.
6092
	 *
6093
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6094
	 *
6095
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6096
	 */
6097
	public function get_cloud_site_options( $option_names ) {
6098
		$option_names = array_filter( (array) $option_names, 'is_string' );
6099
6100
		$xml = new Jetpack_IXR_Client();
6101
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6102
		if ( $xml->isError() ) {
6103
			return array(
6104
				'error_code' => $xml->getErrorCode(),
6105
				'error_msg'  => $xml->getErrorMessage(),
6106
			);
6107
		}
6108
		$cloud_site_options = $xml->getResponse();
6109
6110
		return $cloud_site_options;
6111
	}
6112
6113
	/**
6114
	 * Checks if the site is currently in an identity crisis.
6115
	 *
6116
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6117
	 */
6118
	public static function check_identity_crisis() {
6119
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6120
			return false;
6121
		}
6122
6123
		return Jetpack_Options::get_option( 'sync_error_idc' );
6124
	}
6125
6126
	/**
6127
	 * Checks whether the home and siteurl specifically are allowed.
6128
	 * Written so that we don't have re-check $key and $value params every time
6129
	 * we want to check if this site is allowed, for example in footer.php
6130
	 *
6131
	 * @since  3.8.0
6132
	 * @return bool True = already allowed False = not on the allowed list.
6133
	 */
6134
	public static function is_staging_site() {
6135
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6136
		return ( new Status() )->is_staging_site();
6137
	}
6138
6139
	/**
6140
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6141
	 *
6142
	 * @since 4.4.0
6143
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6144
	 *
6145
	 * @return bool
6146
	 */
6147
	public static function validate_sync_error_idc_option() {
6148
		$is_valid = false;
6149
6150
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6151
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6152
		if ( $sync_error && self::sync_idc_optin() ) {
6153
			$local_options = self::get_sync_error_idc_option();
6154
			// Ensure all values are set.
6155
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6156
6157
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6158
				if (
6159
						isset( $sync_error['wpcom_home'] ) &&
6160
						isset( $sync_error['wpcom_siteurl'] ) &&
6161
						$sync_error['wpcom_home'] === $local_options['home'] &&
6162
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6163
				) {
6164
					$is_valid = false;
6165
					// Enable migrate_for_idc so that sync actions are accepted.
6166
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6167
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6168
					$is_valid = true;
6169
				}
6170
			}
6171
		}
6172
6173
		/**
6174
		 * Filters whether the sync_error_idc option is valid.
6175
		 *
6176
		 * @since 4.4.0
6177
		 *
6178
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6179
		 */
6180
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6181
6182
		if ( ! $is_valid && $sync_error ) {
6183
			// Since the option exists, and did not validate, delete it
6184
			Jetpack_Options::delete_option( 'sync_error_idc' );
6185
		}
6186
6187
		return $is_valid;
6188
	}
6189
6190
	/**
6191
	 * Normalizes a url by doing three things:
6192
	 *  - Strips protocol
6193
	 *  - Strips www
6194
	 *  - Adds a trailing slash
6195
	 *
6196
	 * @since 4.4.0
6197
	 * @param string $url
6198
	 * @return WP_Error|string
6199
	 */
6200
	public static function normalize_url_protocol_agnostic( $url ) {
6201
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6202 View Code Duplication
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsed_url of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

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