Completed
Push — add/unique_registrations_stat ( b6d87d )
by
unknown
515:17 queued 505:25
created

Jetpack::ajax_recheck_ssl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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

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

Loading history...
557
	 */
558
	static function update_active_modules( $modules ) {
559
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
560
		$active_modules       = self::get_active_modules();
561
		$new_active_modules   = array_diff( $modules, $current_modules );
562
		$new_inactive_modules = array_diff( $active_modules, $modules );
563
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
564
		$reindexed_modules    = array_values( $new_current_modules );
565
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
566
567
		foreach ( $new_active_modules as $module ) {
568
			/**
569
			 * Fires when a specific module is activated.
570
			 *
571
			 * @since 1.9.0
572
			 *
573
			 * @param string $module Module slug.
574
			 * @param boolean $success whether the module was activated. @since 4.2
575
			 */
576
			do_action( 'jetpack_activate_module', $module, $success );
577
			/**
578
			 * Fires when a module is activated.
579
			 * The dynamic part of the filter, $module, is the module slug.
580
			 *
581
			 * @since 1.9.0
582
			 *
583
			 * @param string $module Module slug.
584
			 */
585
			do_action( "jetpack_activate_module_$module", $module );
586
		}
587
588
		foreach ( $new_inactive_modules as $module ) {
589
			/**
590
			 * Fired after a module has been deactivated.
591
			 *
592
			 * @since 4.2.0
593
			 *
594
			 * @param string $module Module slug.
595
			 * @param boolean $success whether the module was deactivated.
596
			 */
597
			do_action( 'jetpack_deactivate_module', $module, $success );
598
			/**
599
			 * Fires when a module is deactivated.
600
			 * The dynamic part of the filter, $module, is the module slug.
601
			 *
602
			 * @since 1.9.0
603
			 *
604
			 * @param string $module Module slug.
605
			 */
606
			do_action( "jetpack_deactivate_module_$module", $module );
607
		}
608
609
		return $success;
610
	}
611
612
	static function delete_active_modules() {
613
		self::update_active_modules( array() );
614
	}
615
616
	/**
617
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
618
	 * available.
619
	 */
620
	public function add_configure_hook() {
621
		global $wp_filter;
622
623
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
624
		if ( false !== $current_priority ) {
625
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
626
		}
627
628
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
629
		sort( $taken_priorities );
630
631
		$first_priority = array_shift( $taken_priorities );
632
633
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
634
			$new_priority = - PHP_INT_MAX;
635
		} else {
636
			$new_priority = $first_priority - 1;
637
		}
638
639
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
640
	}
641
642
	/**
643
	 * Constructor.  Initializes WordPress hooks
644
	 */
645
	private function __construct() {
646
		/*
647
		 * Check for and alert any deprecated hooks
648
		 */
649
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
650
651
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
652
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
653
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
654
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
655
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
656
657
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
658
659
		add_filter(
660
			'jetpack_signature_check_token',
661
			array( __CLASS__, 'verify_onboarding_token' ),
662
			10,
663
			3
664
		);
665
666
		/**
667
		 * Prepare Gutenberg Editor functionality
668
		 */
669
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
670
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
671
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
672
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
673
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
674
675
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
676
677
		// Unlink user before deleting the user from WP.com.
678
		add_action( 'deleted_user', array( $this, 'disconnect_user' ), 10, 1 );
679
		add_action( 'remove_user_from_blog', array( $this, 'disconnect_user' ), 10, 1 );
680
681
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
682
683
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
684
		add_action( 'login_init', array( $this, 'login_init' ) );
685
686
		// Set up the REST authentication hooks.
687
		Connection_Rest_Authentication::init();
688
689
		add_action( 'admin_init', array( $this, 'admin_init' ) );
690
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
691
692
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
693
694
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
695
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
696
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
697
698
		// returns HTTPS support status
699
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
700
701
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
702
703
		add_action( 'wp_ajax_jetpack_recommendations_banner', array( 'Jetpack_Recommendations_Banner', 'ajax_callback' ) );
704
705
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
706
707
		/**
708
		 * These actions run checks to load additional files.
709
		 * They check for external files or plugins, so they need to run as late as possible.
710
		 */
711
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
712
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
713
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
714
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
715
716
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
717
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
718
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
719
720
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
721
722
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
723
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
724
725
		// A filter to control all just in time messages
726
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
727
728
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
729
730
		require_once JETPACK__PLUGIN_DIR . 'class-jetpack-pre-connection-jitms.php';
731
		$jetpack_jitm_messages = ( new Jetpack_Pre_Connection_JITMs() );
732
		add_filter( 'jetpack_pre_connection_jitms', array( $jetpack_jitm_messages, 'add_pre_connection_jitms' ) );
733
734
		/*
735
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
736
		 * We should make sure to only do this for front end links.
737
		 */
738
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
739
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
740
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
741
742
			/*
743
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
744
			 * so they point moderation links on emails to Calypso.
745
			 */
746
			jetpack_require_lib( 'functions.wp-notify' );
747
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
748
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
749
		}
750
751
		add_action(
752
			'plugins_loaded',
753
			function () {
754
				if ( User_Agent_Info::is_mobile_app() ) {
755
					add_filter( 'get_edit_post_link', '__return_empty_string' );
756
				}
757
			}
758
		);
759
760
		// Update the site's Jetpack plan and products from API on heartbeats.
761
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
762
763
		/**
764
		 * This is the hack to concatenate all css files into one.
765
		 * For description and reasoning see the implode_frontend_css method.
766
		 *
767
		 * Super late priority so we catch all the registered styles.
768
		 */
769
		if ( ! is_admin() ) {
770
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
771
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
772
		}
773
774
		/**
775
		 * These are sync actions that we need to keep track of for jitms
776
		 */
777
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
778
779
		// Actually push the stats on shutdown.
780
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
781
			add_action( 'shutdown', array( $this, 'push_stats' ) );
782
		}
783
784
		// After a successful connection.
785
		add_action( 'jetpack_site_registered', array( $this, 'activate_default_modules_on_site_register' ) );
786
		add_action( 'jetpack_site_registered', array( $this, 'handle_unique_registrations_stats' ) );
787
788
		// Actions for Manager::authorize().
789
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
790
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
791
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
792
793
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
794
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
795
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
796
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
797
798
		// Filters for the Manager::get_token() urls and request body.
799
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
800
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
801
802
		// Actions for successful reconnect.
803
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
804
805
		// Actions for licensing.
806
		Licensing::instance()->initialize();
807
808
		// Filters for Sync Callables.
809
		add_filter( 'jetpack_sync_callable_whitelist', array( $this, 'filter_sync_callable_whitelist' ), 10, 1 );
810
		add_filter( 'jetpack_sync_multisite_callable_whitelist', array( $this, 'filter_sync_multisite_callable_whitelist' ), 10, 1 );
811
812
		// Make resources use static domain when possible.
813
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
814
	}
815
816
	/**
817
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
818
	 * Config object.
819
	 */
820
	public function configure() {
821
		$config = new Config();
822
823
		foreach (
824
			array(
825
				'sync',
826
			)
827
			as $feature
828
		) {
829
			$config->ensure( $feature );
830
		}
831
832
		$config->ensure(
833
			'connection',
834
			array(
835
				'slug' => 'jetpack',
836
				'name' => 'Jetpack',
837
			)
838
		);
839
840
		if ( is_admin() ) {
841
			$config->ensure( 'jitm' );
842
		}
843
844
		if ( ! $this->connection_manager ) {
845
			$this->connection_manager = new Connection_Manager( 'jetpack' );
846
847
			/**
848
			 * Filter to activate Jetpack Connection UI.
849
			 * INTERNAL USE ONLY.
850
			 *
851
			 * @since 9.5.0
852
			 *
853
			 * @param bool false Whether to activate the Connection UI.
854
			 */
855
			if ( apply_filters( 'jetpack_connection_ui_active', false ) ) {
856
				Automattic\Jetpack\ConnectionUI\Admin::init();
857
			}
858
		}
859
860
		/*
861
		 * Load things that should only be in Network Admin.
862
		 *
863
		 * For now blow away everything else until a more full
864
		 * understanding of what is needed at the network level is
865
		 * available
866
		 */
867
		if ( is_multisite() ) {
868
			$network = Jetpack_Network::init();
869
			$network->set_connection( $this->connection_manager );
870
		}
871
872
		if ( $this->connection_manager->is_active() ) {
873
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
874
875
			Jetpack_Heartbeat::init();
876
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
877
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
878
				Jetpack_Search_Performance_Logger::init();
879
			}
880
		}
881
882
		// Initialize remote file upload request handlers.
883
		$this->add_remote_request_handlers();
884
885
		/*
886
		 * Enable enhanced handling of previewing sites in Calypso
887
		 */
888
		if ( self::is_active() ) {
889
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
890
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
891
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
892
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
893
		}
894
895
		if ( ( new Tracking( $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) ) {
0 ignored issues
show
Documentation introduced by
new \Automattic\Jetpack\Status() is of type object<Automattic\Jetpack\Status>, but the function expects a object<Automattic\Jetpac...omattic\Jetpack\Status>.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
896
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
897
		} else {
898
			/**
899
			 * Initialize tracking right after the user agrees to the terms of service.
900
			 */
901
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
902
		}
903
	}
904
905
	/**
906
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
907
	 * initialization code.
908
	 *
909
	 * @action plugins_loaded
910
	 */
911
	public function late_initialization() {
912
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
913
914
		Partner::init();
915
916
		/**
917
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
918
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
919
		 *
920
		 * @since 8.1.0
921
		 *
922
		 * @param Jetpack $jetpack the main plugin class object.
923
		 */
924
		do_action( 'jetpack_loaded', $this );
925
926
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
927
	}
928
929
	/**
930
	 * Sets up the XMLRPC request handlers.
931
	 *
932
	 * @deprecated since 7.7.0
933
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
934
	 *
935
	 * @param array                 $request_params Incoming request parameters.
936
	 * @param Boolean               $is_active      Whether the connection is currently active.
937
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
938
	 * @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...
939
	 */
940 View Code Duplication
	public function setup_xmlrpc_handlers(
941
		$request_params,
942
		$is_active,
943
		$is_signed,
944
		Jetpack_XMLRPC_Server $xmlrpc_server = null
945
	) {
946
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
947
948
		if ( ! $this->connection_manager ) {
949
			$this->connection_manager = new Connection_Manager();
950
		}
951
952
		return $this->connection_manager->setup_xmlrpc_handlers(
953
			$request_params,
954
			$is_active,
955
			$is_signed,
956
			$xmlrpc_server
957
		);
958
	}
959
960
	/**
961
	 * Initialize REST API registration connector.
962
	 *
963
	 * @deprecated since 7.7.0
964
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
965
	 */
966 View Code Duplication
	public function initialize_rest_api_registration_connector() {
967
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
968
969
		if ( ! $this->connection_manager ) {
970
			$this->connection_manager = new Connection_Manager();
971
		}
972
973
		$this->connection_manager->initialize_rest_api_registration_connector();
974
	}
975
976
	/**
977
	 * This is ported over from the manage module, which has been deprecated and baked in here.
978
	 *
979
	 * @param $domains
980
	 */
981
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
982
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
983
	}
984
985
	/**
986
	 * Return $domains, with 'wordpress.com' appended.
987
	 * This is ported over from the manage module, which has been deprecated and baked in here.
988
	 *
989
	 * @param $domains
990
	 * @return array
991
	 */
992
	function allow_wpcom_domain( $domains ) {
993
		if ( empty( $domains ) ) {
994
			$domains = array();
995
		}
996
		$domains[] = 'wordpress.com';
997
		return array_unique( $domains );
998
	}
999
1000
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
1001
		$post = get_post( $post_id );
1002
1003
		if ( empty( $post ) ) {
1004
			return $default_url;
1005
		}
1006
1007
		$post_type = $post->post_type;
1008
1009
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1010
		// https://en.support.wordpress.com/custom-post-types/
1011
		$allowed_post_types = array(
1012
			'post',
1013
			'page',
1014
			'jetpack-portfolio',
1015
			'jetpack-testimonial',
1016
		);
1017
1018
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1019
			return $default_url;
1020
		}
1021
1022
		return Redirect::get_url(
1023
			'calypso-edit-' . $post_type,
1024
			array(
1025
				'path' => $post_id,
1026
			)
1027
		);
1028
	}
1029
1030
	function point_edit_comment_links_to_calypso( $url ) {
1031
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1032
		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...
1033
1034
		return Redirect::get_url(
1035
			'calypso-edit-comment',
1036
			array(
1037
				'path' => $query_args['amp;c'],
1038
			)
1039
		);
1040
1041
	}
1042
1043
	/**
1044
	 * Extend Sync callables with Jetpack Plugin functions.
1045
	 *
1046
	 * @param array $callables list of callables.
1047
	 *
1048
	 * @return array list of callables.
1049
	 */
1050
	public function filter_sync_callable_whitelist( $callables ) {
1051
1052
		// Jetpack Functions.
1053
		$jetpack_callables = array(
1054
			'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
1055
			'updates'                  => array( 'Jetpack', 'get_updates' ),
1056
			'active_modules'           => array( 'Jetpack', 'get_active_modules' ),
1057
			'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1058
		);
1059
		$callables         = array_merge( $callables, $jetpack_callables );
1060
1061
		// Jetpack_SSO_Helpers.
1062
		if ( include_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' ) {
1063
			$sso_helpers = array(
1064
				'sso_is_two_step_required'      => array( 'Jetpack_SSO_Helpers', 'is_two_step_required' ),
1065
				'sso_should_hide_login_form'    => array( 'Jetpack_SSO_Helpers', 'should_hide_login_form' ),
1066
				'sso_match_by_email'            => array( 'Jetpack_SSO_Helpers', 'match_by_email' ),
1067
				'sso_new_user_override'         => array( 'Jetpack_SSO_Helpers', 'new_user_override' ),
1068
				'sso_bypass_default_login_form' => array( 'Jetpack_SSO_Helpers', 'bypass_login_forward_wpcom' ),
1069
			);
1070
			$callables   = array_merge( $callables, $sso_helpers );
1071
		}
1072
1073
		return $callables;
1074
	}
1075
1076
	/**
1077
	 * Extend Sync multisite callables with Jetpack Plugin functions.
1078
	 *
1079
	 * @param array $callables list of callables.
1080
	 *
1081
	 * @return array list of callables.
1082
	 */
1083
	public function filter_sync_multisite_callable_whitelist( $callables ) {
1084
1085
		// Jetpack Funtions.
1086
		$jetpack_multisite_callables = array(
1087
			'network_name'                        => array( 'Jetpack', 'network_name' ),
1088
			'network_allow_new_registrations'     => array( 'Jetpack', 'network_allow_new_registrations' ),
1089
			'network_add_new_users'               => array( 'Jetpack', 'network_add_new_users' ),
1090
			'network_site_upload_space'           => array( 'Jetpack', 'network_site_upload_space' ),
1091
			'network_upload_file_types'           => array( 'Jetpack', 'network_upload_file_types' ),
1092
			'network_enable_administration_menus' => array( 'Jetpack', 'network_enable_administration_menus' ),
1093
		);
1094
		$callables                   = array_merge( $callables, $jetpack_multisite_callables );
1095
1096
		return $callables;
1097
	}
1098
1099
	function jetpack_track_last_sync_callback( $params ) {
1100
		/**
1101
		 * Filter to turn off jitm caching
1102
		 *
1103
		 * @since 5.4.0
1104
		 *
1105
		 * @param bool false Whether to cache just in time messages
1106
		 */
1107
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1108
			return $params;
1109
		}
1110
1111
		if ( is_array( $params ) && isset( $params[0] ) ) {
1112
			$option = $params[0];
1113
			if ( 'active_plugins' === $option ) {
1114
				// use the cache if we can, but not terribly important if it gets evicted
1115
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1116
			}
1117
		}
1118
1119
		return $params;
1120
	}
1121
1122
	function jetpack_connection_banner_callback() {
1123
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1124
1125
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1126
		if (
1127
			isset( $_REQUEST['dismissBanner'] ) &&
1128
			! Jetpack_Connection_Banner::force_display()
1129
		) {
1130
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1131
			wp_send_json_success();
1132
		}
1133
1134
		wp_die();
1135
	}
1136
1137
	/**
1138
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1139
	 * Only used in our alternate XML-RPC endpoint, where we want to
1140
	 * ensure that Core and other plugins' methods are not exposed.
1141
	 *
1142
	 * @deprecated since 7.7.0
1143
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1144
	 *
1145
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1146
	 * @return array Filtered $methods
1147
	 */
1148 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1149
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1150
1151
		if ( ! $this->connection_manager ) {
1152
			$this->connection_manager = new Connection_Manager();
1153
		}
1154
1155
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1156
	}
1157
1158
	/**
1159
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1160
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1161
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1162
	 * which is accessible via a different URI. Most of the below is copied directly
1163
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1164
	 *
1165
	 * @deprecated since 7.7.0
1166
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1167
	 */
1168 View Code Duplication
	public function alternate_xmlrpc() {
1169
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1170
1171
		if ( ! $this->connection_manager ) {
1172
			$this->connection_manager = new Connection_Manager();
1173
		}
1174
1175
		$this->connection_manager->alternate_xmlrpc();
1176
	}
1177
1178
	/**
1179
	 * The callback for the JITM ajax requests.
1180
	 *
1181
	 * @deprecated since 7.9.0
1182
	 */
1183
	function jetpack_jitm_ajax_callback() {
1184
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1185
	}
1186
1187
	/**
1188
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1189
	 */
1190
	function push_stats() {
1191
		if ( ! empty( $this->stats ) ) {
1192
			$this->do_stats( 'server_side' );
1193
		}
1194
	}
1195
1196
	/**
1197
	 * Sets the Jetpack custom capabilities.
1198
	 *
1199
	 * @param string[] $caps    Array of the user's capabilities.
1200
	 * @param string   $cap     Capability name.
1201
	 * @param int      $user_id The user ID.
1202
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1203
	 */
1204
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1205
		switch ( $cap ) {
1206
			case 'jetpack_manage_modules':
1207
			case 'jetpack_activate_modules':
1208
			case 'jetpack_deactivate_modules':
1209
				$caps = array( 'manage_options' );
1210
				break;
1211
			case 'jetpack_configure_modules':
1212
				$caps = array( 'manage_options' );
1213
				break;
1214
			case 'jetpack_manage_autoupdates':
1215
				$caps = array(
1216
					'manage_options',
1217
					'update_plugins',
1218
				);
1219
				break;
1220
			case 'jetpack_network_admin_page':
1221
			case 'jetpack_network_settings_page':
1222
				$caps = array( 'manage_network_plugins' );
1223
				break;
1224
			case 'jetpack_network_sites_page':
1225
				$caps = array( 'manage_sites' );
1226
				break;
1227 View Code Duplication
			case 'jetpack_admin_page':
1228
				$is_offline_mode = ( new Status() )->is_offline_mode();
1229
				if ( $is_offline_mode ) {
1230
					$caps = array( 'manage_options' );
1231
					break;
1232
				} else {
1233
					$caps = array( 'read' );
1234
				}
1235
				break;
1236
		}
1237
		return $caps;
1238
	}
1239
1240
	/**
1241
	 * Require a Jetpack authentication.
1242
	 *
1243
	 * @deprecated since 7.7.0
1244
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1245
	 */
1246 View Code Duplication
	public function require_jetpack_authentication() {
1247
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1248
1249
		if ( ! $this->connection_manager ) {
1250
			$this->connection_manager = new Connection_Manager();
1251
		}
1252
1253
		$this->connection_manager->require_jetpack_authentication();
1254
	}
1255
1256
	/**
1257
	 * Register assets for use in various modules and the Jetpack admin page.
1258
	 *
1259
	 * @uses wp_script_is, wp_register_script, plugins_url
1260
	 * @action wp_loaded
1261
	 * @return null
1262
	 */
1263
	public function register_assets() {
1264 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1265
			wp_register_script(
1266
				'jetpack-gallery-settings',
1267
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1268
				array( 'media-views' ),
1269
				'20121225'
1270
			);
1271
		}
1272
1273
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1274
			wp_register_script(
1275
				'jetpack-twitter-timeline',
1276
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1277
				array( 'jquery' ),
1278
				'4.0.0',
1279
				true
1280
			);
1281
		}
1282
1283
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1284
			wp_register_script(
1285
				'jetpack-facebook-embed',
1286
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1287
				array(),
1288
				null,
1289
				true
1290
			);
1291
1292
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1293
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1294
			if ( ! is_numeric( $fb_app_id ) ) {
1295
				$fb_app_id = '';
1296
			}
1297
			wp_localize_script(
1298
				'jetpack-facebook-embed',
1299
				'jpfbembed',
1300
				array(
1301
					'appid'  => $fb_app_id,
1302
					'locale' => $this->get_locale(),
1303
				)
1304
			);
1305
		}
1306
1307
		/**
1308
		 * As jetpack_register_genericons is by default fired off a hook,
1309
		 * the hook may have already fired by this point.
1310
		 * So, let's just trigger it manually.
1311
		 */
1312
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1313
		jetpack_register_genericons();
1314
1315
		/**
1316
		 * Register the social logos
1317
		 */
1318
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1319
		jetpack_register_social_logos();
1320
1321
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1322
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1323
		}
1324
	}
1325
1326
	/**
1327
	 * Guess locale from language code.
1328
	 *
1329
	 * @param string $lang Language code.
1330
	 * @return string|bool
1331
	 */
1332 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1333
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1334
			return 'en_US';
1335
		}
1336
1337
		if ( ! class_exists( 'GP_Locales' ) ) {
1338
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1339
				return false;
1340
			}
1341
1342
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1343
		}
1344
1345
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1346
			// WP.com: get_locale() returns 'it'
1347
			$locale = GP_Locales::by_slug( $lang );
1348
		} else {
1349
			// Jetpack: get_locale() returns 'it_IT';
1350
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1351
		}
1352
1353
		if ( ! $locale ) {
1354
			return false;
1355
		}
1356
1357
		if ( empty( $locale->facebook_locale ) ) {
1358
			if ( empty( $locale->wp_locale ) ) {
1359
				return false;
1360
			} else {
1361
				// Facebook SDK is smart enough to fall back to en_US if a
1362
				// locale isn't supported. Since supported Facebook locales
1363
				// can fall out of sync, we'll attempt to use the known
1364
				// wp_locale value and rely on said fallback.
1365
				return $locale->wp_locale;
1366
			}
1367
		}
1368
1369
		return $locale->facebook_locale;
1370
	}
1371
1372
	/**
1373
	 * Get the locale.
1374
	 *
1375
	 * @return string|bool
1376
	 */
1377
	function get_locale() {
1378
		$locale = $this->guess_locale_from_lang( get_locale() );
1379
1380
		if ( ! $locale ) {
1381
			$locale = 'en_US';
1382
		}
1383
1384
		return $locale;
1385
	}
1386
1387
	/**
1388
	 * Return the network_site_url so that .com knows what network this site is a part of.
1389
	 *
1390
	 * @param  bool $option
1391
	 * @return string
1392
	 */
1393
	public function jetpack_main_network_site_option( $option ) {
1394
		return network_site_url();
1395
	}
1396
	/**
1397
	 * Network Name.
1398
	 */
1399
	static function network_name( $option = null ) {
1400
		global $current_site;
1401
		return $current_site->site_name;
1402
	}
1403
	/**
1404
	 * Does the network allow new user and site registrations.
1405
	 *
1406
	 * @return string
1407
	 */
1408
	static function network_allow_new_registrations( $option = null ) {
1409
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1410
	}
1411
	/**
1412
	 * Does the network allow admins to add new users.
1413
	 *
1414
	 * @return boolian
1415
	 */
1416
	static function network_add_new_users( $option = null ) {
1417
		return (bool) get_site_option( 'add_new_users' );
1418
	}
1419
	/**
1420
	 * File upload psace left per site in MB.
1421
	 *  -1 means NO LIMIT.
1422
	 *
1423
	 * @return number
1424
	 */
1425
	static function network_site_upload_space( $option = null ) {
1426
		// value in MB
1427
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1428
	}
1429
1430
	/**
1431
	 * Network allowed file types.
1432
	 *
1433
	 * @return string
1434
	 */
1435
	static function network_upload_file_types( $option = null ) {
1436
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1437
	}
1438
1439
	/**
1440
	 * Maximum file upload size set by the network.
1441
	 *
1442
	 * @return number
1443
	 */
1444
	static function network_max_upload_file_size( $option = null ) {
1445
		// value in KB
1446
		return get_site_option( 'fileupload_maxk', 300 );
1447
	}
1448
1449
	/**
1450
	 * Lets us know if a site allows admins to manage the network.
1451
	 *
1452
	 * @return array
1453
	 */
1454
	static function network_enable_administration_menus( $option = null ) {
1455
		return get_site_option( 'menu_items' );
1456
	}
1457
1458
	/**
1459
	 * If a user has been promoted to or demoted from admin, we need to clear the
1460
	 * jetpack_other_linked_admins transient.
1461
	 *
1462
	 * @since 4.3.2
1463
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1464
	 *
1465
	 * @param int    $user_id   The user ID whose role changed.
1466
	 * @param string $role      The new role.
1467
	 * @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...
1468
	 */
1469
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1470
		if ( 'administrator' == $role
1471
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1472
			|| is_null( $old_roles )
1473
		) {
1474
			delete_transient( 'jetpack_other_linked_admins' );
1475
		}
1476
	}
1477
1478
	/**
1479
	 * Checks to see if there are any other users available to become primary
1480
	 * Users must both:
1481
	 * - Be linked to wpcom
1482
	 * - Be an admin
1483
	 *
1484
	 * @return mixed False if no other users are linked, Int if there are.
1485
	 */
1486
	static function get_other_linked_admins() {
1487
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1488
1489
		if ( false === $other_linked_users ) {
1490
			$admins = get_users( array( 'role' => 'administrator' ) );
1491
			if ( count( $admins ) > 1 ) {
1492
				$available = array();
1493
				foreach ( $admins as $admin ) {
1494
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1495
						$available[] = $admin->ID;
1496
					}
1497
				}
1498
1499
				$count_connected_admins = count( $available );
1500
				if ( count( $available ) > 1 ) {
1501
					$other_linked_users = $count_connected_admins;
1502
				} else {
1503
					$other_linked_users = 0;
1504
				}
1505
			} else {
1506
				$other_linked_users = 0;
1507
			}
1508
1509
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1510
		}
1511
1512
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1513
	}
1514
1515
	/**
1516
	 * Return whether we are dealing with a multi network setup or not.
1517
	 * The reason we are type casting this is because we want to avoid the situation where
1518
	 * the result is false since when is_main_network_option return false it cases
1519
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1520
	 * database which could be set to anything as opposed to what this function returns.
1521
	 *
1522
	 * @param  bool $option
1523
	 *
1524
	 * @return boolean
1525
	 */
1526
	public function is_main_network_option( $option ) {
1527
		// return '1' or ''
1528
		return (string) (bool) self::is_multi_network();
1529
	}
1530
1531
	/**
1532
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1533
	 *
1534
	 * @param  string $option
1535
	 * @return boolean
1536
	 */
1537
	public function is_multisite( $option ) {
1538
		return (string) (bool) is_multisite();
1539
	}
1540
1541
	/**
1542
	 * Implemented since there is no core is multi network function
1543
	 * Right now there is no way to tell if we which network is the dominant network on the system
1544
	 *
1545
	 * @since  3.3
1546
	 * @return boolean
1547
	 */
1548 View Code Duplication
	public static function is_multi_network() {
1549
		global  $wpdb;
1550
1551
		// if we don't have a multi site setup no need to do any more
1552
		if ( ! is_multisite() ) {
1553
			return false;
1554
		}
1555
1556
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1557
		if ( $num_sites > 1 ) {
1558
			return true;
1559
		} else {
1560
			return false;
1561
		}
1562
	}
1563
1564
	/**
1565
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1566
	 *
1567
	 * @return null
1568
	 */
1569
	function update_jetpack_main_network_site_option() {
1570
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1571
	}
1572
	/**
1573
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1574
	 */
1575
	function update_jetpack_network_settings() {
1576
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1577
		// Only sync this info for the main network site.
1578
	}
1579
1580
	/**
1581
	 * Get back if the current site is single user site.
1582
	 *
1583
	 * @return bool
1584
	 */
1585 View Code Duplication
	public static function is_single_user_site() {
1586
		global $wpdb;
1587
1588
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1589
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1590
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1591
		}
1592
		return 1 === (int) $some_users;
1593
	}
1594
1595
	/**
1596
	 * Returns true if the site has file write access false otherwise.
1597
	 *
1598
	 * @return string ( '1' | '0' )
1599
	 **/
1600
	public static function file_system_write_access() {
1601
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1602
			require_once ABSPATH . 'wp-admin/includes/file.php';
1603
		}
1604
1605
		require_once ABSPATH . 'wp-admin/includes/template.php';
1606
1607
		$filesystem_method = get_filesystem_method();
1608
		if ( $filesystem_method === 'direct' ) {
1609
			return 1;
1610
		}
1611
1612
		ob_start();
1613
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1614
		ob_end_clean();
1615
		if ( $filesystem_credentials_are_stored ) {
1616
			return 1;
1617
		}
1618
		return 0;
1619
	}
1620
1621
	/**
1622
	 * Finds out if a site is using a version control system.
1623
	 *
1624
	 * @return string ( '1' | '0' )
1625
	 **/
1626
	public static function is_version_controlled() {
1627
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1628
		return (string) (int) Functions::is_version_controlled();
1629
	}
1630
1631
	/**
1632
	 * Determines whether the current theme supports featured images or not.
1633
	 *
1634
	 * @return string ( '1' | '0' )
1635
	 */
1636
	public static function featured_images_enabled() {
1637
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1638
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1639
	}
1640
1641
	/**
1642
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1643
	 *
1644
	 * @deprecated 4.7 use get_avatar_url instead.
1645
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1646
	 * @param int               $size Size of the avatar image
1647
	 * @param string            $default URL to a default image to use if no avatar is available
1648
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1649
	 *
1650
	 * @return array
1651
	 */
1652
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1653
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1654
		return get_avatar_url(
1655
			$id_or_email,
1656
			array(
1657
				'size'          => $size,
1658
				'default'       => $default,
1659
				'force_default' => $force_display,
1660
			)
1661
		);
1662
	}
1663
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1664
	/**
1665
	 * jetpack_updates is saved in the following schema:
1666
	 *
1667
	 * array (
1668
	 *      'plugins'                       => (int) Number of plugin updates available.
1669
	 *      'themes'                        => (int) Number of theme updates available.
1670
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1671
	 *      'translations'                  => (int) Number of translation updates available.
1672
	 *      'total'                         => (int) Total of all available updates.
1673
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1674
	 * )
1675
	 *
1676
	 * @return array
1677
	 */
1678
	public static function get_updates() {
1679
		$update_data = wp_get_update_data();
1680
1681
		// Stores the individual update counts as well as the total count.
1682
		if ( isset( $update_data['counts'] ) ) {
1683
			$updates = $update_data['counts'];
1684
		}
1685
1686
		// If we need to update WordPress core, let's find the latest version number.
1687 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1688
			$cur = get_preferred_from_update_core();
1689
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1690
				$updates['wp_update_version'] = $cur->current;
1691
			}
1692
		}
1693
		return isset( $updates ) ? $updates : array();
1694
	}
1695
	// phpcs:enable
1696
1697
	public static function get_update_details() {
1698
		$update_details = array(
1699
			'update_core'    => get_site_transient( 'update_core' ),
1700
			'update_plugins' => get_site_transient( 'update_plugins' ),
1701
			'update_themes'  => get_site_transient( 'update_themes' ),
1702
		);
1703
		return $update_details;
1704
	}
1705
1706
	public static function refresh_update_data() {
1707
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1708
1709
	}
1710
1711
	public static function refresh_theme_data() {
1712
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1713
	}
1714
1715
	/**
1716
	 * Is Jetpack active?
1717
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1718
	 *
1719
	 * @return bool
1720
	 */
1721
	public static function is_active() {
1722
		return self::connection()->is_active();
1723
	}
1724
1725
	/**
1726
	 * Make an API call to WordPress.com for plan status
1727
	 *
1728
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1729
	 *
1730
	 * @return bool True if plan is updated, false if no update
1731
	 */
1732
	public static function refresh_active_plan_from_wpcom() {
1733
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1734
		return Jetpack_Plan::refresh_from_wpcom();
1735
	}
1736
1737
	/**
1738
	 * Get the plan that this Jetpack site is currently using
1739
	 *
1740
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1741
	 * @return array Active Jetpack plan details.
1742
	 */
1743
	public static function get_active_plan() {
1744
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1745
		return Jetpack_Plan::get();
1746
	}
1747
1748
	/**
1749
	 * Determine whether the active plan supports a particular feature
1750
	 *
1751
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1752
	 * @return bool True if plan supports feature, false if not.
1753
	 */
1754
	public static function active_plan_supports( $feature ) {
1755
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1756
		return Jetpack_Plan::supports( $feature );
1757
	}
1758
1759
	/**
1760
	 * Deprecated: Is Jetpack in development (offline) mode?
1761
	 *
1762
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1763
	 * and themes still use it, and we do not want to flood them with notices.
1764
	 *
1765
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1766
	 *
1767
	 * @deprecated since 8.0.
1768
	 */
1769
	public static function is_development_mode() {
1770
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1771
		return ( new Status() )->is_offline_mode();
1772
	}
1773
1774
	/**
1775
	 * Whether the site is currently onboarding or not.
1776
	 * A site is considered as being onboarded if it currently has an onboarding token.
1777
	 *
1778
	 * @since 5.8
1779
	 *
1780
	 * @access public
1781
	 * @static
1782
	 *
1783
	 * @return bool True if the site is currently onboarding, false otherwise
1784
	 */
1785
	public static function is_onboarding() {
1786
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1787
	}
1788
1789
	/**
1790
	 * Determines reason for Jetpack offline mode.
1791
	 */
1792
	public static function development_mode_trigger_text() {
1793
		$status = new Status();
1794
1795
		if ( ! $status->is_offline_mode() ) {
1796
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1797
		}
1798
1799
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1800
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1801
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1802
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1803
		} elseif ( $status->is_local_site() ) {
1804
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1805
			/** This filter is documented in packages/status/src/class-status.php */
1806
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1807
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1808
		} else {
1809
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1810
		}
1811
1812
		return $notice;
1813
1814
	}
1815
	/**
1816
	 * Get Jetpack offline mode notice text and notice class.
1817
	 *
1818
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1819
	 */
1820
	public static function show_development_mode_notice() {
1821 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1822
			$notice = sprintf(
1823
				/* translators: %s is a URL */
1824
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1825
				Redirect::get_url( 'jetpack-support-development-mode' )
1826
			);
1827
1828
			$notice .= ' ' . self::development_mode_trigger_text();
1829
1830
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1831
		}
1832
1833
		// Throw up a notice if using a development version and as for feedback.
1834
		if ( self::is_development_version() ) {
1835
			/* translators: %s is a URL */
1836
			$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' ) );
1837
1838
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1839
		}
1840
		// Throw up a notice if using staging mode
1841 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1842
			/* translators: %s is a URL */
1843
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1844
1845
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1846
		}
1847
	}
1848
1849
	/**
1850
	 * Whether Jetpack's version maps to a public release, or a development version.
1851
	 */
1852
	public static function is_development_version() {
1853
		/**
1854
		 * Allows filtering whether this is a development version of Jetpack.
1855
		 *
1856
		 * This filter is especially useful for tests.
1857
		 *
1858
		 * @since 4.3.0
1859
		 *
1860
		 * @param bool $development_version Is this a develoment version of Jetpack?
1861
		 */
1862
		return (bool) apply_filters(
1863
			'jetpack_development_version',
1864
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1865
		);
1866
	}
1867
1868
	/**
1869
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1870
	 */
1871
	public static function is_user_connected( $user_id = false ) {
1872
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1873
		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...
1874
	}
1875
1876
	/**
1877
	 * Get the wpcom user data of the current|specified connected user.
1878
	 */
1879
	public static function get_connected_user_data( $user_id = null ) {
1880
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1881
		return self::connection()->get_connected_user_data( $user_id );
1882
	}
1883
1884
	/**
1885
	 * Get the wpcom email of the current|specified connected user.
1886
	 */
1887
	public static function get_connected_user_email( $user_id = null ) {
1888
		if ( ! $user_id ) {
1889
			$user_id = get_current_user_id();
1890
		}
1891
1892
		$xml = new Jetpack_IXR_Client(
1893
			array(
1894
				'user_id' => $user_id,
1895
			)
1896
		);
1897
		$xml->query( 'wpcom.getUserEmail' );
1898
		if ( ! $xml->isError() ) {
1899
			return $xml->getResponse();
1900
		}
1901
		return false;
1902
	}
1903
1904
	/**
1905
	 * Get the wpcom email of the master user.
1906
	 */
1907
	public static function get_master_user_email() {
1908
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1909
		if ( $master_user_id ) {
1910
			return self::get_connected_user_email( $master_user_id );
1911
		}
1912
		return '';
1913
	}
1914
1915
	/**
1916
	 * Whether the current user is the connection owner.
1917
	 *
1918
	 * @deprecated since 7.7
1919
	 *
1920
	 * @return bool Whether the current user is the connection owner.
1921
	 */
1922
	public function current_user_is_connection_owner() {
1923
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1924
		return self::connection()->is_connection_owner();
1925
	}
1926
1927
	/**
1928
	 * Gets current user IP address.
1929
	 *
1930
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1931
	 *
1932
	 * @return string                  Current user IP address.
1933
	 */
1934
	public static function current_user_ip( $check_all_headers = false ) {
1935
		if ( $check_all_headers ) {
1936
			foreach ( array(
1937
				'HTTP_CF_CONNECTING_IP',
1938
				'HTTP_CLIENT_IP',
1939
				'HTTP_X_FORWARDED_FOR',
1940
				'HTTP_X_FORWARDED',
1941
				'HTTP_X_CLUSTER_CLIENT_IP',
1942
				'HTTP_FORWARDED_FOR',
1943
				'HTTP_FORWARDED',
1944
				'HTTP_VIA',
1945
			) as $key ) {
1946
				if ( ! empty( $_SERVER[ $key ] ) ) {
1947
					return $_SERVER[ $key ];
1948
				}
1949
			}
1950
		}
1951
1952
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1953
	}
1954
1955
	/**
1956
	 * Synchronize connected user role changes
1957
	 */
1958
	function user_role_change( $user_id ) {
1959
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1960
		Users::user_role_change( $user_id );
1961
	}
1962
1963
	/**
1964
	 * Loads the currently active modules.
1965
	 */
1966
	public static function load_modules() {
1967
		$is_offline_mode = ( new Status() )->is_offline_mode();
1968
		if (
1969
			! self::is_active()
1970
			&& ! $is_offline_mode
1971
			&& ! self::is_onboarding()
1972
			&& (
1973
				! is_multisite()
1974
				|| ! get_site_option( 'jetpack_protect_active' )
1975
			)
1976
		) {
1977
			return;
1978
		}
1979
1980
		$version = Jetpack_Options::get_option( 'version' );
1981 View Code Duplication
		if ( ! $version ) {
1982
			$version = $old_version = JETPACK__VERSION . ':' . time();
1983
			/** This action is documented in class.jetpack.php */
1984
			do_action( 'updating_jetpack_version', $version, false );
1985
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1986
		}
1987
		list( $version ) = explode( ':', $version );
1988
1989
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1990
1991
		$modules_data = array();
1992
1993
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1994
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1995
			$updated_modules = array();
1996
			foreach ( $modules as $module ) {
1997
				$modules_data[ $module ] = self::get_module( $module );
1998
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1999
					continue;
2000
				}
2001
2002
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2003
					continue;
2004
				}
2005
2006
				$updated_modules[] = $module;
2007
			}
2008
2009
			$modules = array_diff( $modules, $updated_modules );
2010
		}
2011
2012
		foreach ( $modules as $index => $module ) {
2013
			// If we're in offline mode, disable modules requiring a connection.
2014
			if ( $is_offline_mode ) {
2015
				// Prime the pump if we need to
2016
				if ( empty( $modules_data[ $module ] ) ) {
2017
					$modules_data[ $module ] = self::get_module( $module );
2018
				}
2019
				// If the module requires a connection, but we're in local mode, don't include it.
2020
				if ( $modules_data[ $module ]['requires_connection'] ) {
2021
					continue;
2022
				}
2023
			}
2024
2025
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2026
				continue;
2027
			}
2028
2029
			if ( ! include_once self::get_module_path( $module ) ) {
2030
				unset( $modules[ $index ] );
2031
				self::update_active_modules( array_values( $modules ) );
2032
				continue;
2033
			}
2034
2035
			/**
2036
			 * Fires when a specific module is loaded.
2037
			 * The dynamic part of the hook, $module, is the module slug.
2038
			 *
2039
			 * @since 1.1.0
2040
			 */
2041
			do_action( 'jetpack_module_loaded_' . $module );
2042
		}
2043
2044
		/**
2045
		 * Fires when all the modules are loaded.
2046
		 *
2047
		 * @since 1.1.0
2048
		 */
2049
		do_action( 'jetpack_modules_loaded' );
2050
2051
		// 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.
2052
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2053
	}
2054
2055
	/**
2056
	 * Check if Jetpack's REST API compat file should be included
2057
	 *
2058
	 * @action plugins_loaded
2059
	 * @return null
2060
	 */
2061
	public function check_rest_api_compat() {
2062
		/**
2063
		 * Filters the list of REST API compat files to be included.
2064
		 *
2065
		 * @since 2.2.5
2066
		 *
2067
		 * @param array $args Array of REST API compat files to include.
2068
		 */
2069
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2070
2071
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2072
			require_once $_jetpack_rest_api_compat_include;
2073
		}
2074
	}
2075
2076
	/**
2077
	 * Gets all plugins currently active in values, regardless of whether they're
2078
	 * traditionally activated or network activated.
2079
	 *
2080
	 * @todo Store the result in core's object cache maybe?
2081
	 */
2082
	public static function get_active_plugins() {
2083
		$active_plugins = (array) get_option( 'active_plugins', array() );
2084
2085
		if ( is_multisite() ) {
2086
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2087
			// whereas active_plugins stores them in the values.
2088
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2089
			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...
2090
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2091
			}
2092
		}
2093
2094
		sort( $active_plugins );
2095
2096
		return array_unique( $active_plugins );
2097
	}
2098
2099
	/**
2100
	 * Gets and parses additional plugin data to send with the heartbeat data
2101
	 *
2102
	 * @since 3.8.1
2103
	 *
2104
	 * @return array Array of plugin data
2105
	 */
2106
	public static function get_parsed_plugin_data() {
2107
		if ( ! function_exists( 'get_plugins' ) ) {
2108
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2109
		}
2110
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2111
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2112
		$active_plugins = self::get_active_plugins();
2113
2114
		$plugins = array();
2115
		foreach ( $all_plugins as $path => $plugin_data ) {
2116
			$plugins[ $path ] = array(
2117
				'is_active' => in_array( $path, $active_plugins ),
2118
				'file'      => $path,
2119
				'name'      => $plugin_data['Name'],
2120
				'version'   => $plugin_data['Version'],
2121
				'author'    => $plugin_data['Author'],
2122
			);
2123
		}
2124
2125
		return $plugins;
2126
	}
2127
2128
	/**
2129
	 * Gets and parses theme data to send with the heartbeat data
2130
	 *
2131
	 * @since 3.8.1
2132
	 *
2133
	 * @return array Array of theme data
2134
	 */
2135
	public static function get_parsed_theme_data() {
2136
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2137
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2138
2139
		$themes = array();
2140
		foreach ( $all_themes as $slug => $theme_data ) {
2141
			$theme_headers = array();
2142
			foreach ( $header_keys as $header_key ) {
2143
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2144
			}
2145
2146
			$themes[ $slug ] = array(
2147
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2148
				'slug'            => $slug,
2149
				'theme_root'      => $theme_data->get_theme_root_uri(),
2150
				'parent'          => $theme_data->parent(),
2151
				'headers'         => $theme_headers,
2152
			);
2153
		}
2154
2155
		return $themes;
2156
	}
2157
2158
	/**
2159
	 * Checks whether a specific plugin is active.
2160
	 *
2161
	 * We don't want to store these in a static variable, in case
2162
	 * there are switch_to_blog() calls involved.
2163
	 */
2164
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2165
		return in_array( $plugin, self::get_active_plugins() );
2166
	}
2167
2168
	/**
2169
	 * Check if Jetpack's Open Graph tags should be used.
2170
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2171
	 *
2172
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2173
	 * @action plugins_loaded
2174
	 * @return null
2175
	 */
2176
	public function check_open_graph() {
2177
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2178
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2179
		}
2180
2181
		$active_plugins = self::get_active_plugins();
2182
2183
		if ( ! empty( $active_plugins ) ) {
2184
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2185
				if ( in_array( $plugin, $active_plugins ) ) {
2186
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2187
					break;
2188
				}
2189
			}
2190
		}
2191
2192
		/**
2193
		 * Allow the addition of Open Graph Meta Tags to all pages.
2194
		 *
2195
		 * @since 2.0.3
2196
		 *
2197
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2198
		 */
2199
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2200
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2201
		}
2202
	}
2203
2204
	/**
2205
	 * Check if Jetpack's Twitter tags should be used.
2206
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2207
	 *
2208
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2209
	 * @action plugins_loaded
2210
	 * @return null
2211
	 */
2212
	public function check_twitter_tags() {
2213
2214
		$active_plugins = self::get_active_plugins();
2215
2216
		if ( ! empty( $active_plugins ) ) {
2217
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2218
				if ( in_array( $plugin, $active_plugins ) ) {
2219
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2220
					break;
2221
				}
2222
			}
2223
		}
2224
2225
		/**
2226
		 * Allow Twitter Card Meta tags to be disabled.
2227
		 *
2228
		 * @since 2.6.0
2229
		 *
2230
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2231
		 */
2232
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2233
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2234
		}
2235
	}
2236
2237
	/**
2238
	 * Allows plugins to submit security reports.
2239
	 *
2240
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2241
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2242
	 * @param array  $args         See definitions above
2243
	 */
2244
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2245
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2246
	}
2247
2248
	/* Jetpack Options API */
2249
2250
	public static function get_option_names( $type = 'compact' ) {
2251
		return Jetpack_Options::get_option_names( $type );
2252
	}
2253
2254
	/**
2255
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2256
	 *
2257
	 * @param string $name    Option name
2258
	 * @param mixed  $default (optional)
2259
	 */
2260
	public static function get_option( $name, $default = false ) {
2261
		return Jetpack_Options::get_option( $name, $default );
2262
	}
2263
2264
	/**
2265
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2266
	 *
2267
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2268
	 * @param string $name  Option name
2269
	 * @param mixed  $value Option value
2270
	 */
2271
	public static function update_option( $name, $value ) {
2272
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2273
		return Jetpack_Options::update_option( $name, $value );
2274
	}
2275
2276
	/**
2277
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2278
	 *
2279
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2280
	 * @param array $array array( option name => option value, ... )
2281
	 */
2282
	public static function update_options( $array ) {
2283
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2284
		return Jetpack_Options::update_options( $array );
2285
	}
2286
2287
	/**
2288
	 * Deletes the given option.  May be passed multiple option names as an array.
2289
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2290
	 *
2291
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2292
	 * @param string|array $names
2293
	 */
2294
	public static function delete_option( $names ) {
2295
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2296
		return Jetpack_Options::delete_option( $names );
2297
	}
2298
2299
	/**
2300
	 * Enters a user token into the user_tokens option
2301
	 *
2302
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2303
	 *
2304
	 * @param int    $user_id The user id.
2305
	 * @param string $token The user token.
2306
	 * @param bool   $is_master_user Whether the user is the master user.
2307
	 * @return bool
2308
	 */
2309
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2310
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2311
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2312
	}
2313
2314
	/**
2315
	 * Returns an array of all PHP files in the specified absolute path.
2316
	 * Equivalent to glob( "$absolute_path/*.php" ).
2317
	 *
2318
	 * @param string $absolute_path The absolute path of the directory to search.
2319
	 * @return array Array of absolute paths to the PHP files.
2320
	 */
2321
	public static function glob_php( $absolute_path ) {
2322
		if ( function_exists( 'glob' ) ) {
2323
			return glob( "$absolute_path/*.php" );
2324
		}
2325
2326
		$absolute_path = untrailingslashit( $absolute_path );
2327
		$files         = array();
2328
		if ( ! $dir = @opendir( $absolute_path ) ) {
2329
			return $files;
2330
		}
2331
2332
		while ( false !== $file = readdir( $dir ) ) {
2333
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2334
				continue;
2335
			}
2336
2337
			$file = "$absolute_path/$file";
2338
2339
			if ( ! is_file( $file ) ) {
2340
				continue;
2341
			}
2342
2343
			$files[] = $file;
2344
		}
2345
2346
		closedir( $dir );
2347
2348
		return $files;
2349
	}
2350
2351
	public static function activate_new_modules( $redirect = false ) {
2352
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2353
			return;
2354
		}
2355
2356
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2357 View Code Duplication
		if ( ! $jetpack_old_version ) {
2358
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2359
			/** This action is documented in class.jetpack.php */
2360
			do_action( 'updating_jetpack_version', $version, false );
2361
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2362
		}
2363
2364
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2365
2366
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2367
			return;
2368
		}
2369
2370
		$active_modules     = self::get_active_modules();
2371
		$reactivate_modules = array();
2372
		foreach ( $active_modules as $active_module ) {
2373
			$module = self::get_module( $active_module );
2374
			if ( ! isset( $module['changed'] ) ) {
2375
				continue;
2376
			}
2377
2378
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2379
				continue;
2380
			}
2381
2382
			$reactivate_modules[] = $active_module;
2383
			self::deactivate_module( $active_module );
2384
		}
2385
2386
		$new_version = JETPACK__VERSION . ':' . time();
2387
		/** This action is documented in class.jetpack.php */
2388
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2389
		Jetpack_Options::update_options(
2390
			array(
2391
				'version'     => $new_version,
2392
				'old_version' => $jetpack_old_version,
2393
			)
2394
		);
2395
2396
		self::state( 'message', 'modules_activated' );
2397
2398
		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...
2399
2400
		if ( $redirect ) {
2401
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2402
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2403
				$page = $_GET['page'];
2404
			}
2405
2406
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2407
			exit;
2408
		}
2409
	}
2410
2411
	/**
2412
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2413
	 * Make sure to tuck away module "library" files in a sub-directory.
2414
	 *
2415
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2416
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2417
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2418
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2419
	 *
2420
	 * @return array $modules Array of module slugs
2421
	 */
2422
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2423
		static $modules = null;
2424
2425
		if ( ! isset( $modules ) ) {
2426
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2427
			// Use the cache if we're on the front-end and it's available...
2428
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2429
				$modules = $available_modules_option[ JETPACK__VERSION ];
2430
			} else {
2431
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2432
2433
				$modules = array();
2434
2435
				foreach ( $files as $file ) {
2436
					if ( ! $headers = self::get_module( $file ) ) {
2437
						continue;
2438
					}
2439
2440
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2441
				}
2442
2443
				Jetpack_Options::update_option(
2444
					'available_modules',
2445
					array(
2446
						JETPACK__VERSION => $modules,
2447
					)
2448
				);
2449
			}
2450
		}
2451
2452
		/**
2453
		 * Filters the array of modules available to be activated.
2454
		 *
2455
		 * @since 2.4.0
2456
		 *
2457
		 * @param array $modules Array of available modules.
2458
		 * @param string $min_version Minimum version number required to use modules.
2459
		 * @param string $max_version Maximum version number required to use modules.
2460
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2461
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2462
		 */
2463
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version, $requires_connection, $requires_user_connection );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2464
2465
		if ( ! $min_version && ! $max_version && is_null( $requires_connection ) && is_null( $requires_user_connection ) ) {
2466
			return array_keys( $mods );
2467
		}
2468
2469
		$r = array();
2470
		foreach ( $mods as $slug => $introduced ) {
2471
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2472
				continue;
2473
			}
2474
2475
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2476
				continue;
2477
			}
2478
2479
			$mod_details = self::get_module( $slug );
2480
2481
			if ( null !== $requires_connection && (bool) $requires_connection !== $mod_details['requires_connection'] ) {
2482
				continue;
2483
			}
2484
2485
			if ( null !== $requires_user_connection && (bool) $requires_user_connection !== $mod_details['requires_user_connection'] ) {
2486
				continue;
2487
			}
2488
2489
			$r[] = $slug;
2490
		}
2491
2492
		return $r;
2493
	}
2494
2495
	/**
2496
	 * Get default modules loaded on activation.
2497
	 *
2498
	 * @param bool|string $min_version Onlu return modules introduced in this version or later. Default is false, do not filter.
2499
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2500
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2501
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2502
	 *
2503
	 * @return array $modules Array of module slugs
2504
	 */
2505
	public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2506
		$return = array();
2507
2508
		foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2509
			$module_data = self::get_module( $module );
2510
2511
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2512
				case 'yes':
2513
					$return[] = $module;
2514
					break;
2515
				case 'public':
2516
					if ( Jetpack_Options::get_option( 'public' ) ) {
2517
						$return[] = $module;
2518
					}
2519
					break;
2520
				case 'no':
2521
				default:
2522
					break;
2523
			}
2524
		}
2525
		/**
2526
		 * Filters the array of default modules.
2527
		 *
2528
		 * @since 2.5.0
2529
		 *
2530
		 * @param array $return Array of default modules.
2531
		 * @param string $min_version Minimum version number required to use modules.
2532
		 * @param string $max_version Maximum version number required to use modules.
2533
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2534
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2535
		 */
2536
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version, $requires_connection, $requires_user_connection );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2537
	}
2538
2539
	/**
2540
	 * Checks activated modules during auto-activation to determine
2541
	 * if any of those modules are being deprecated.  If so, close
2542
	 * them out, and add any replacement modules.
2543
	 *
2544
	 * Runs at priority 99 by default.
2545
	 *
2546
	 * This is run late, so that it can still activate a module if
2547
	 * the new module is a replacement for another that the user
2548
	 * currently has active, even if something at the normal priority
2549
	 * would kibosh everything.
2550
	 *
2551
	 * @since 2.6
2552
	 * @uses jetpack_get_default_modules filter
2553
	 * @param array $modules
2554
	 * @return array
2555
	 */
2556
	function handle_deprecated_modules( $modules ) {
2557
		$deprecated_modules = array(
2558
			'debug'            => null,  // Closed out and moved to the debugger library.
2559
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2560
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2561
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2562
		);
2563
2564
		// Don't activate SSO if they never completed activating WPCC.
2565
		if ( self::is_module_active( 'wpcc' ) ) {
2566
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2567
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2568
				$deprecated_modules['wpcc'] = null;
2569
			}
2570
		}
2571
2572
		foreach ( $deprecated_modules as $module => $replacement ) {
2573
			if ( self::is_module_active( $module ) ) {
2574
				self::deactivate_module( $module );
2575
				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...
2576
					$modules[] = $replacement;
2577
				}
2578
			}
2579
		}
2580
2581
		return array_unique( $modules );
2582
	}
2583
2584
	/**
2585
	 * Checks activated plugins during auto-activation to determine
2586
	 * if any of those plugins are in the list with a corresponding module
2587
	 * that is not compatible with the plugin. The module will not be allowed
2588
	 * to auto-activate.
2589
	 *
2590
	 * @since 2.6
2591
	 * @uses jetpack_get_default_modules filter
2592
	 * @param array $modules
2593
	 * @return array
2594
	 */
2595
	function filter_default_modules( $modules ) {
2596
2597
		$active_plugins = self::get_active_plugins();
2598
2599
		if ( ! empty( $active_plugins ) ) {
2600
2601
			// For each module we'd like to auto-activate...
2602
			foreach ( $modules as $key => $module ) {
2603
				// If there are potential conflicts for it...
2604
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2605
					// For each potential conflict...
2606
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2607
						// If that conflicting plugin is active...
2608
						if ( in_array( $plugin, $active_plugins ) ) {
2609
							// Remove that item from being auto-activated.
2610
							unset( $modules[ $key ] );
2611
						}
2612
					}
2613
				}
2614
			}
2615
		}
2616
2617
		return $modules;
2618
	}
2619
2620
	/**
2621
	 * Extract a module's slug from its full path.
2622
	 */
2623
	public static function get_module_slug( $file ) {
2624
		return str_replace( '.php', '', basename( $file ) );
2625
	}
2626
2627
	/**
2628
	 * Generate a module's path from its slug.
2629
	 */
2630
	public static function get_module_path( $slug ) {
2631
		/**
2632
		 * Filters the path of a modules.
2633
		 *
2634
		 * @since 7.4.0
2635
		 *
2636
		 * @param array $return The absolute path to a module's root php file
2637
		 * @param string $slug The module slug
2638
		 */
2639
		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...
2640
	}
2641
2642
	/**
2643
	 * Load module data from module file. Headers differ from WordPress
2644
	 * plugin headers to avoid them being identified as standalone
2645
	 * plugins on the WordPress plugins page.
2646
	 */
2647
	public static function get_module( $module ) {
2648
		$headers = array(
2649
			'name'                      => 'Module Name',
2650
			'description'               => 'Module Description',
2651
			'sort'                      => 'Sort Order',
2652
			'recommendation_order'      => 'Recommendation Order',
2653
			'introduced'                => 'First Introduced',
2654
			'changed'                   => 'Major Changes In',
2655
			'deactivate'                => 'Deactivate',
2656
			'free'                      => 'Free',
2657
			'requires_connection'       => 'Requires Connection',
2658
			'requires_user_connection'  => 'Requires User Connection',
2659
			'auto_activate'             => 'Auto Activate',
2660
			'module_tags'               => 'Module Tags',
2661
			'feature'                   => 'Feature',
2662
			'additional_search_queries' => 'Additional Search Queries',
2663
			'plan_classes'              => 'Plans',
2664
		);
2665
2666
		static $modules_details;
2667
		$file = self::get_module_path( self::get_module_slug( $module ) );
2668
2669
		if ( isset( $modules_details[ $module ] ) ) {
2670
			$mod = $modules_details[ $module ];
2671
		} else {
2672
2673
			$mod = self::get_file_data( $file, $headers );
2674
			if ( empty( $mod['name'] ) ) {
2675
				return false;
2676
			}
2677
2678
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2679
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2680
			$mod['deactivate']               = empty( $mod['deactivate'] );
2681
			$mod['free']                     = empty( $mod['free'] );
2682
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2683
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2684
2685
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2686
				$mod['auto_activate'] = 'No';
2687
			} else {
2688
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2689
			}
2690
2691
			if ( $mod['module_tags'] ) {
2692
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2693
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2694
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2695
			} else {
2696
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2697
			}
2698
2699 View Code Duplication
			if ( $mod['plan_classes'] ) {
2700
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2701
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2702
			} else {
2703
				$mod['plan_classes'] = array( 'free' );
2704
			}
2705
2706 View Code Duplication
			if ( $mod['feature'] ) {
2707
				$mod['feature'] = explode( ',', $mod['feature'] );
2708
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2709
			} else {
2710
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2711
			}
2712
2713
			$modules_details[ $module ] = $mod;
2714
2715
		}
2716
2717
		/**
2718
		 * Filters the feature array on a module.
2719
		 *
2720
		 * This filter allows you to control where each module is filtered: Recommended,
2721
		 * and the default "Other" listing.
2722
		 *
2723
		 * @since 3.5.0
2724
		 *
2725
		 * @param array   $mod['feature'] The areas to feature this module:
2726
		 *     'Recommended' shows on the main Jetpack admin screen.
2727
		 *     'Other' should be the default if no other value is in the array.
2728
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2729
		 * @param array   $mod All the currently assembled module data.
2730
		 */
2731
		$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...
2732
2733
		/**
2734
		 * Filter the returned data about a module.
2735
		 *
2736
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2737
		 * so please be careful.
2738
		 *
2739
		 * @since 3.6.0
2740
		 *
2741
		 * @param array   $mod    The details of the requested module.
2742
		 * @param string  $module The slug of the module, e.g. sharedaddy
2743
		 * @param string  $file   The path to the module source file.
2744
		 */
2745
		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...
2746
	}
2747
2748
	/**
2749
	 * Like core's get_file_data implementation, but caches the result.
2750
	 */
2751
	public static function get_file_data( $file, $headers ) {
2752
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2753
		$file_name = basename( $file );
2754
2755
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2756
2757
		$file_data_option = get_transient( $cache_key );
2758
2759
		if ( ! is_array( $file_data_option ) ) {
2760
			delete_transient( $cache_key );
2761
			$file_data_option = false;
2762
		}
2763
2764
		if ( false === $file_data_option ) {
2765
			$file_data_option = array();
2766
		}
2767
2768
		$key           = md5( $file_name . serialize( $headers ) );
2769
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2770
2771
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2772
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2773
			return $file_data_option[ $key ];
2774
		}
2775
2776
		$data = get_file_data( $file, $headers );
2777
2778
		$file_data_option[ $key ] = $data;
2779
2780
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2781
2782
		return $data;
2783
	}
2784
2785
	/**
2786
	 * Return translated module tag.
2787
	 *
2788
	 * @param string $tag Tag as it appears in each module heading.
2789
	 *
2790
	 * @return mixed
2791
	 */
2792
	public static function translate_module_tag( $tag ) {
2793
		return jetpack_get_module_i18n_tag( $tag );
2794
	}
2795
2796
	/**
2797
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2798
	 *
2799
	 * @since 3.9.2
2800
	 *
2801
	 * @param array $modules
2802
	 *
2803
	 * @return string|void
2804
	 */
2805
	public static function get_translated_modules( $modules ) {
2806
		foreach ( $modules as $index => $module ) {
2807
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2808
			if ( isset( $module['name'] ) ) {
2809
				$modules[ $index ]['name'] = $i18n_module['name'];
2810
			}
2811
			if ( isset( $module['description'] ) ) {
2812
				$modules[ $index ]['description']       = $i18n_module['description'];
2813
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2814
			}
2815
		}
2816
		return $modules;
2817
	}
2818
2819
	/**
2820
	 * Get a list of activated modules as an array of module slugs.
2821
	 */
2822
	public static function get_active_modules() {
2823
		$active = Jetpack_Options::get_option( 'active_modules' );
2824
2825
		if ( ! is_array( $active ) ) {
2826
			$active = array();
2827
		}
2828
2829
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2830
			$active[] = 'vaultpress';
2831
		} else {
2832
			$active = array_diff( $active, array( 'vaultpress' ) );
2833
		}
2834
2835
		// If protect is active on the main site of a multisite, it should be active on all sites.
2836
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2837
			$active[] = 'protect';
2838
		}
2839
2840
		/**
2841
		 * Allow filtering of the active modules.
2842
		 *
2843
		 * Gives theme and plugin developers the power to alter the modules that
2844
		 * are activated on the fly.
2845
		 *
2846
		 * @since 5.8.0
2847
		 *
2848
		 * @param array $active Array of active module slugs.
2849
		 */
2850
		$active = apply_filters( 'jetpack_active_modules', $active );
2851
2852
		return array_unique( $active );
2853
	}
2854
2855
	/**
2856
	 * Check whether or not a Jetpack module is active.
2857
	 *
2858
	 * @param string $module The slug of a Jetpack module.
2859
	 * @return bool
2860
	 *
2861
	 * @static
2862
	 */
2863
	public static function is_module_active( $module ) {
2864
		return in_array( $module, self::get_active_modules() );
2865
	}
2866
2867
	public static function is_module( $module ) {
2868
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2869
	}
2870
2871
	/**
2872
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2873
	 *
2874
	 * @param bool $catch True to start catching, False to stop.
2875
	 *
2876
	 * @static
2877
	 */
2878
	public static function catch_errors( $catch ) {
2879
		static $display_errors, $error_reporting;
2880
2881
		if ( $catch ) {
2882
			$display_errors  = @ini_set( 'display_errors', 1 );
2883
			$error_reporting = @error_reporting( E_ALL );
2884
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2885
		} else {
2886
			@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...
2887
			@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...
2888
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2889
		}
2890
	}
2891
2892
	/**
2893
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2894
	 */
2895
	public static function catch_errors_on_shutdown() {
2896
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2897
	}
2898
2899
	/**
2900
	 * Rewrite any string to make paths easier to read.
2901
	 *
2902
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2903
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2904
	 *
2905
	 * @param $string
2906
	 * @return mixed
2907
	 */
2908
	public static function alias_directories( $string ) {
2909
		// ABSPATH has a trailing slash.
2910
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2911
		// WP_CONTENT_DIR does not have a trailing slash.
2912
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2913
2914
		return $string;
2915
	}
2916
2917
	public static function activate_default_modules(
2918
		$min_version = false,
2919
		$max_version = false,
2920
		$other_modules = array(),
2921
		$redirect = null,
2922
		$send_state_messages = null,
2923
		$requires_connection = null,
2924
		$requires_user_connection = null
2925
	) {
2926
		$jetpack = self::init();
2927
2928
		if ( is_null( $redirect ) ) {
2929
			if (
2930
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2931
			||
2932
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2933
			||
2934
				( defined( 'WP_CLI' ) && WP_CLI )
2935
			||
2936
				( defined( 'DOING_CRON' ) && DOING_CRON )
2937
			||
2938
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2939
			) {
2940
				$redirect = false;
2941
			} elseif ( is_admin() ) {
2942
				$redirect = true;
2943
			} else {
2944
				$redirect = false;
2945
			}
2946
		}
2947
2948
		if ( is_null( $send_state_messages ) ) {
2949
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2950
		}
2951
2952
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2953
		$modules = array_merge( $other_modules, $modules );
2954
2955
		// Look for standalone plugins and disable if active.
2956
2957
		$to_deactivate = array();
2958
		foreach ( $modules as $module ) {
2959
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2960
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2961
			}
2962
		}
2963
2964
		$deactivated = array();
2965
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2966
			list( $probable_file, $probable_title ) = $deactivate_me;
2967
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2968
				$deactivated[] = $module;
2969
			}
2970
		}
2971
2972
		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...
2973
			if ( $send_state_messages ) {
2974
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2975
			}
2976
2977
			if ( $redirect ) {
2978
				$url = add_query_arg(
2979
					array(
2980
						'action'   => 'activate_default_modules',
2981
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2982
					),
2983
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2984
				);
2985
				wp_safe_redirect( $url );
2986
				exit;
2987
			}
2988
		}
2989
2990
		/**
2991
		 * Fires before default modules are activated.
2992
		 *
2993
		 * @since 1.9.0
2994
		 *
2995
		 * @param string    $min_version Minimum version number required to use modules.
2996
		 * @param string    $max_version Maximum version number required to use modules.
2997
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
2998
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2999
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3000
		 */
3001
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3002
3003
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3004
		if ( $send_state_messages ) {
3005
			self::restate();
3006
			self::catch_errors( true );
3007
		}
3008
3009
		$active = self::get_active_modules();
3010
3011
		foreach ( $modules as $module ) {
3012
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3013
				$active[] = $module;
3014
				self::update_active_modules( $active );
3015
				continue;
3016
			}
3017
3018
			if ( $send_state_messages && in_array( $module, $active ) ) {
3019
				$module_info = self::get_module( $module );
3020 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3021
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3022
					if ( $active_state = self::state( $state ) ) {
3023
						$active_state = explode( ',', $active_state );
3024
					} else {
3025
						$active_state = array();
3026
					}
3027
					$active_state[] = $module;
3028
					self::state( $state, implode( ',', $active_state ) );
3029
				}
3030
				continue;
3031
			}
3032
3033
			$file = self::get_module_path( $module );
3034
			if ( ! file_exists( $file ) ) {
3035
				continue;
3036
			}
3037
3038
			// we'll override this later if the plugin can be included without fatal error
3039
			if ( $redirect ) {
3040
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3041
			}
3042
3043
			if ( $send_state_messages ) {
3044
				self::state( 'error', 'module_activation_failed' );
3045
				self::state( 'module', $module );
3046
			}
3047
3048
			ob_start();
3049
			require_once $file;
3050
3051
			$active[] = $module;
3052
3053 View Code Duplication
			if ( $send_state_messages ) {
3054
3055
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3056
				if ( $active_state = self::state( $state ) ) {
3057
					$active_state = explode( ',', $active_state );
3058
				} else {
3059
					$active_state = array();
3060
				}
3061
				$active_state[] = $module;
3062
				self::state( $state, implode( ',', $active_state ) );
3063
			}
3064
3065
			self::update_active_modules( $active );
3066
3067
			ob_end_clean();
3068
		}
3069
3070
		if ( $send_state_messages ) {
3071
			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...
3072
			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...
3073
		}
3074
3075
		self::catch_errors( false );
3076
		/**
3077
		 * Fires when default modules are activated.
3078
		 *
3079
		 * @since 1.9.0
3080
		 *
3081
		 * @param string    $min_version Minimum version number required to use modules.
3082
		 * @param string    $max_version Maximum version number required to use modules.
3083
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3084
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3085
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3086
		 */
3087
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3088
	}
3089
3090
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3091
		/**
3092
		 * Fires before a module is activated.
3093
		 *
3094
		 * @since 2.6.0
3095
		 *
3096
		 * @param string $module Module slug.
3097
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3098
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3099
		 */
3100
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3101
3102
		$jetpack = self::init();
3103
3104
		if ( ! strlen( $module ) ) {
3105
			return false;
3106
		}
3107
3108
		if ( ! self::is_module( $module ) ) {
3109
			return false;
3110
		}
3111
3112
		// If it's already active, then don't do it again
3113
		$active = self::get_active_modules();
3114
		foreach ( $active as $act ) {
3115
			if ( $act == $module ) {
3116
				return true;
3117
			}
3118
		}
3119
3120
		$module_data = self::get_module( $module );
3121
3122
		$is_offline_mode = ( new Status() )->is_offline_mode();
3123
		if ( ! self::is_active() ) {
3124
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3125
				return false;
3126
			}
3127
3128
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3129
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3130
				return false;
3131
			}
3132
		}
3133
3134
		// Check and see if the old plugin is active
3135
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3136
			// Deactivate the old plugin
3137
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3138
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3139
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3140
				self::state( 'deactivated_plugins', $module );
3141
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3142
				exit;
3143
			}
3144
		}
3145
3146
		// Protect won't work with mis-configured IPs
3147
		if ( 'protect' === $module ) {
3148
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3149
			if ( ! jetpack_protect_get_ip() ) {
3150
				self::state( 'message', 'protect_misconfigured_ip' );
3151
				return false;
3152
			}
3153
		}
3154
3155
		if ( ! Jetpack_Plan::supports( $module ) ) {
3156
			return false;
3157
		}
3158
3159
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3160
		self::state( 'module', $module );
3161
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3162
3163
		self::catch_errors( true );
3164
		ob_start();
3165
		require self::get_module_path( $module );
3166
		/** This action is documented in class.jetpack.php */
3167
		do_action( 'jetpack_activate_module', $module );
3168
		$active[] = $module;
3169
		self::update_active_modules( $active );
3170
3171
		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...
3172
		ob_end_clean();
3173
		self::catch_errors( false );
3174
3175
		if ( $redirect ) {
3176
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3177
		}
3178
		if ( $exit ) {
3179
			exit;
3180
		}
3181
		return true;
3182
	}
3183
3184
	function activate_module_actions( $module ) {
3185
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3186
	}
3187
3188
	public static function deactivate_module( $module ) {
3189
		/**
3190
		 * Fires when a module is deactivated.
3191
		 *
3192
		 * @since 1.9.0
3193
		 *
3194
		 * @param string $module Module slug.
3195
		 */
3196
		do_action( 'jetpack_pre_deactivate_module', $module );
3197
3198
		$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...
3199
3200
		$active = self::get_active_modules();
3201
		$new    = array_filter( array_diff( $active, (array) $module ) );
3202
3203
		return self::update_active_modules( $new );
3204
	}
3205
3206
	public static function enable_module_configurable( $module ) {
3207
		$module = self::get_module_slug( $module );
3208
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3209
	}
3210
3211
	/**
3212
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3213
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3214
	 *
3215
	 * @param string $module Module slug
3216
	 * @return string $url module configuration URL
3217
	 */
3218
	public static function module_configuration_url( $module ) {
3219
		$module      = self::get_module_slug( $module );
3220
		$default_url = self::admin_url() . "#/settings?term=$module";
3221
		/**
3222
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3223
		 *
3224
		 * @since 6.9.0
3225
		 *
3226
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3227
		 */
3228
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3229
3230
		return $url;
3231
	}
3232
3233
	/* Installation */
3234
	public static function bail_on_activation( $message, $deactivate = true ) {
3235
		?>
3236
<!doctype html>
3237
<html>
3238
<head>
3239
<meta charset="<?php bloginfo( 'charset' ); ?>">
3240
<style>
3241
* {
3242
	text-align: center;
3243
	margin: 0;
3244
	padding: 0;
3245
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3246
}
3247
p {
3248
	margin-top: 1em;
3249
	font-size: 18px;
3250
}
3251
</style>
3252
<body>
3253
<p><?php echo esc_html( $message ); ?></p>
3254
</body>
3255
</html>
3256
		<?php
3257
		if ( $deactivate ) {
3258
			$plugins = get_option( 'active_plugins' );
3259
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3260
			$update  = false;
3261
			foreach ( $plugins as $i => $plugin ) {
3262
				if ( $plugin === $jetpack ) {
3263
					$plugins[ $i ] = false;
3264
					$update        = true;
3265
				}
3266
			}
3267
3268
			if ( $update ) {
3269
				update_option( 'active_plugins', array_filter( $plugins ) );
3270
			}
3271
		}
3272
		exit;
3273
	}
3274
3275
	/**
3276
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3277
	 *
3278
	 * @static
3279
	 */
3280
	public static function plugin_activation( $network_wide ) {
3281
		Jetpack_Options::update_option( 'activated', 1 );
3282
3283
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3284
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3285
		}
3286
3287
		if ( $network_wide ) {
3288
			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...
3289
		}
3290
3291
		// For firing one-off events (notices) immediately after activation
3292
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3293
3294
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3295
3296
		Health::on_jetpack_activated();
3297
3298
		self::plugin_initialize();
3299
	}
3300
3301
	public static function get_activation_source( $referer_url ) {
3302
3303
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3304
			return array( 'wp-cli', null );
3305
		}
3306
3307
		$referer = wp_parse_url( $referer_url );
3308
3309
		$source_type  = 'unknown';
3310
		$source_query = null;
3311
3312
		if ( ! is_array( $referer ) ) {
3313
			return array( $source_type, $source_query );
3314
		}
3315
3316
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3317
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3318
3319
		if ( isset( $referer['query'] ) ) {
3320
			parse_str( $referer['query'], $query_parts );
3321
		} else {
3322
			$query_parts = array();
3323
		}
3324
3325
		if ( $plugins_path === $referer['path'] ) {
3326
			$source_type = 'list';
3327
		} elseif ( $plugins_install_path === $referer['path'] ) {
3328
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3329
			switch ( $tab ) {
3330
				case 'popular':
3331
					$source_type = 'popular';
3332
					break;
3333
				case 'recommended':
3334
					$source_type = 'recommended';
3335
					break;
3336
				case 'favorites':
3337
					$source_type = 'favorites';
3338
					break;
3339
				case 'search':
3340
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3341
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3342
					break;
3343
				default:
3344
					$source_type = 'featured';
3345
			}
3346
		}
3347
3348
		return array( $source_type, $source_query );
3349
	}
3350
3351
	/**
3352
	 * Runs before bumping version numbers up to a new version
3353
	 *
3354
	 * @param string $version    Version:timestamp.
3355
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3356
	 */
3357
	public static function do_version_bump( $version, $old_version ) {
3358
		if ( $old_version ) { // For existing Jetpack installations.
3359
3360
			// If a front end page is visited after the update, the 'wp' action will fire.
3361
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3362
3363
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3364
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3365
		}
3366
	}
3367
3368
	/**
3369
	 * Sets the display_update_modal state.
3370
	 */
3371
	public static function set_update_modal_display() {
3372
		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...
3373
	}
3374
3375
	/**
3376
	 * Sets the internal version number and activation state.
3377
	 *
3378
	 * @static
3379
	 */
3380
	public static function plugin_initialize() {
3381
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3382
			Jetpack_Options::update_option( 'activated', 2 );
3383
		}
3384
3385 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3386
			$version = $old_version = JETPACK__VERSION . ':' . time();
3387
			/** This action is documented in class.jetpack.php */
3388
			do_action( 'updating_jetpack_version', $version, false );
3389
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3390
		}
3391
3392
		self::load_modules();
3393
3394
		Jetpack_Options::delete_option( 'do_activate' );
3395
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3396
	}
3397
3398
	/**
3399
	 * Removes all connection options
3400
	 *
3401
	 * @static
3402
	 */
3403
	public static function plugin_deactivation() {
3404
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3405
		$tracking = new Tracking();
3406
		$tracking->record_user_event( 'deactivate_plugin', array() );
3407
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3408
			Jetpack_Network::init()->deactivate();
3409
		} else {
3410
			self::disconnect( false );
3411
			// Jetpack_Heartbeat::init()->deactivate();
3412
		}
3413
	}
3414
3415
	/**
3416
	 * Disconnects from the Jetpack servers.
3417
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3418
	 *
3419
	 * @static
3420
	 */
3421
	public static function disconnect( $update_activated_state = true ) {
3422
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3423
3424
		$connection = self::connection();
3425
3426
		( new Nonce_Handler() )->clean_all();
3427
3428
		// If the site is in an IDC because sync is not allowed,
3429
		// let's make sure to not disconnect the production site.
3430
		if ( ! self::validate_sync_error_idc_option() ) {
3431
			$tracking = new Tracking();
3432
			$tracking->record_user_event( 'disconnect_site', array() );
3433
3434
			$connection->disconnect_site_wpcom( true );
3435
		}
3436
3437
		$connection->delete_all_connection_tokens( true );
3438
		Jetpack_IDC::clear_all_idc_options();
3439
3440
		if ( $update_activated_state ) {
3441
			Jetpack_Options::update_option( 'activated', 4 );
3442
		}
3443
3444
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3445
			// Check then record unique disconnection if site has never been disconnected previously
3446
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3447
				$jetpack_unique_connection['disconnected'] = 1;
3448
			} else {
3449
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3450
					// track unique disconnect
3451
					$jetpack = self::init();
3452
3453
					$jetpack->stat( 'connections', 'unique-disconnect' );
3454
					$jetpack->do_stats( 'server_side' );
3455
				}
3456
				// increment number of times disconnected
3457
				$jetpack_unique_connection['disconnected'] += 1;
3458
			}
3459
3460
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3461
		}
3462
3463
		// Delete all the sync related data. Since it could be taking up space.
3464
		Sender::get_instance()->uninstall();
3465
3466
	}
3467
3468
	/**
3469
	 * Disconnects the user
3470
	 *
3471
	 * @param int $user_id The user ID to disconnect.
3472
	 */
3473
	public function disconnect_user( $user_id ) {
3474
		$this->connection_manager->disconnect_user( $user_id );
3475
	}
3476
3477
	/**
3478
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3479
	 */
3480
	public static function try_registration() {
3481
		$terms_of_service = new Terms_Of_Service();
3482
		// The user has agreed to the TOS at some point by now.
3483
		$terms_of_service->agree();
3484
3485
		// Let's get some testing in beta versions and such.
3486
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3487
			// Before attempting to connect, let's make sure that the domains are viable.
3488
			$domains_to_check = array_unique(
3489
				array(
3490
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3491
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3492
				)
3493
			);
3494
			foreach ( $domains_to_check as $domain ) {
3495
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3494 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...
3496
				if ( is_wp_error( $result ) ) {
3497
					return $result;
3498
				}
3499
			}
3500
		}
3501
3502
		$result = self::register();
3503
3504
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3505
		if ( ! $result || is_wp_error( $result ) ) {
3506
			return $result;
3507
		} else {
3508
			return true;
3509
		}
3510
	}
3511
3512
	/**
3513
	 * Tracking an internal event log. Try not to put too much chaff in here.
3514
	 *
3515
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3516
	 */
3517
	public static function log( $code, $data = null ) {
3518
		// only grab the latest 200 entries
3519
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3520
3521
		// Append our event to the log
3522
		$log_entry = array(
3523
			'time'    => time(),
3524
			'user_id' => get_current_user_id(),
3525
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3526
			'code'    => $code,
3527
		);
3528
		// Don't bother storing it unless we've got some.
3529
		if ( ! is_null( $data ) ) {
3530
			$log_entry['data'] = $data;
3531
		}
3532
		$log[] = $log_entry;
3533
3534
		// Try add_option first, to make sure it's not autoloaded.
3535
		// @todo: Add an add_option method to Jetpack_Options
3536
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3537
			Jetpack_Options::update_option( 'log', $log );
3538
		}
3539
3540
		/**
3541
		 * Fires when Jetpack logs an internal event.
3542
		 *
3543
		 * @since 3.0.0
3544
		 *
3545
		 * @param array $log_entry {
3546
		 *  Array of details about the log entry.
3547
		 *
3548
		 *  @param string time Time of the event.
3549
		 *  @param int user_id ID of the user who trigerred the event.
3550
		 *  @param int blog_id Jetpack Blog ID.
3551
		 *  @param string code Unique name for the event.
3552
		 *  @param string data Data about the event.
3553
		 * }
3554
		 */
3555
		do_action( 'jetpack_log_entry', $log_entry );
3556
	}
3557
3558
	/**
3559
	 * Get the internal event log.
3560
	 *
3561
	 * @param $event (string) - only return the specific log events
3562
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3563
	 *
3564
	 * @return array of log events || WP_Error for invalid params
3565
	 */
3566
	public static function get_log( $event = false, $num = false ) {
3567
		if ( $event && ! is_string( $event ) ) {
3568
			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...
3569
		}
3570
3571
		if ( $num && ! is_numeric( $num ) ) {
3572
			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...
3573
		}
3574
3575
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3576
3577
		// If nothing set - act as it did before, otherwise let's start customizing the output
3578
		if ( ! $num && ! $event ) {
3579
			return $entire_log;
3580
		} else {
3581
			$entire_log = array_reverse( $entire_log );
3582
		}
3583
3584
		$custom_log_output = array();
3585
3586
		if ( $event ) {
3587
			foreach ( $entire_log as $log_event ) {
3588
				if ( $event == $log_event['code'] ) {
3589
					$custom_log_output[] = $log_event;
3590
				}
3591
			}
3592
		} else {
3593
			$custom_log_output = $entire_log;
3594
		}
3595
3596
		if ( $num ) {
3597
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3598
		}
3599
3600
		return $custom_log_output;
3601
	}
3602
3603
	/**
3604
	 * Log modification of important settings.
3605
	 */
3606
	public static function log_settings_change( $option, $old_value, $value ) {
3607
		switch ( $option ) {
3608
			case 'jetpack_sync_non_public_post_stati':
3609
				self::log( $option, $value );
3610
				break;
3611
		}
3612
	}
3613
3614
	/**
3615
	 * Return stat data for WPCOM sync
3616
	 */
3617
	public static function get_stat_data( $encode = true, $extended = true ) {
3618
		$data = Jetpack_Heartbeat::generate_stats_array();
3619
3620
		if ( $extended ) {
3621
			$additional_data = self::get_additional_stat_data();
3622
			$data            = array_merge( $data, $additional_data );
3623
		}
3624
3625
		if ( $encode ) {
3626
			return json_encode( $data );
3627
		}
3628
3629
		return $data;
3630
	}
3631
3632
	/**
3633
	 * Get additional stat data to sync to WPCOM
3634
	 */
3635
	public static function get_additional_stat_data( $prefix = '' ) {
3636
		$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...
3637
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3638
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3639
		$return[ "{$prefix}site-count" ]    = 0;
3640
3641
		if ( function_exists( 'get_blog_count' ) ) {
3642
			$return[ "{$prefix}site-count" ] = get_blog_count();
3643
		}
3644
		return $return;
3645
	}
3646
3647
	private static function get_site_user_count() {
3648
		global $wpdb;
3649
3650
		if ( function_exists( 'wp_is_large_network' ) ) {
3651
			if ( wp_is_large_network( 'users' ) ) {
3652
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3653
			}
3654
		}
3655
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3656
			// It wasn't there, so regenerate the data and save the transient
3657
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3658
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3659
		}
3660
		return $user_count;
3661
	}
3662
3663
	/* Admin Pages */
3664
3665
	function admin_init() {
3666
		// If the plugin is not connected, display a connect message.
3667
		if (
3668
			// the plugin was auto-activated and needs its candy
3669
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3670
		||
3671
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3672
			! Jetpack_Options::get_option( 'activated' )
3673
		) {
3674
			self::plugin_initialize();
3675
		}
3676
3677
		$is_offline_mode = ( new Status() )->is_offline_mode();
3678
		if ( ! self::is_active() && ! $is_offline_mode ) {
3679
			Jetpack_Connection_Banner::init();
3680
			/** Already documented in automattic/jetpack-connection::src/class-client.php */
3681
		} elseif ( ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) && ! apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
3682
			// Upgrade: 1.1 -> 1.1.1
3683
			// Check and see if host can verify the Jetpack servers' SSL certificate
3684
			$args = array();
3685
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3686
		}
3687
3688
		Jetpack_Recommendations_Banner::init();
3689
3690
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3691
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3692
		}
3693
3694
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3695
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3696
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3697
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3698
3699
		if ( self::is_active() || $is_offline_mode ) {
3700
			// Artificially throw errors in certain specific cases during plugin activation.
3701
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3702
		}
3703
3704
		// Add custom column in wp-admin/users.php to show whether user is linked.
3705
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3706
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3707
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3708
	}
3709
3710
	function admin_body_class( $admin_body_class = '' ) {
3711
		$classes = explode( ' ', trim( $admin_body_class ) );
3712
3713
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3714
3715
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3716
		return " $admin_body_class ";
3717
	}
3718
3719
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3720
		return $admin_body_class . ' jetpack-pagestyles ';
3721
	}
3722
3723
	/**
3724
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3725
	 * This function artificially throws errors for such cases (per a specific list).
3726
	 *
3727
	 * @param string $plugin The activated plugin.
3728
	 */
3729
	function throw_error_on_activate_plugin( $plugin ) {
3730
		$active_modules = self::get_active_modules();
3731
3732
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3733
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3734
			$throw = false;
3735
3736
			// Try and make sure it really was the stats plugin
3737
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3738
				if ( 'stats.php' == basename( $plugin ) ) {
3739
					$throw = true;
3740
				}
3741
			} else {
3742
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3743
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3744
					$throw = true;
3745
				}
3746
			}
3747
3748
			if ( $throw ) {
3749
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3750
			}
3751
		}
3752
	}
3753
3754
	function intercept_plugin_error_scrape_init() {
3755
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3756
	}
3757
3758
	function intercept_plugin_error_scrape( $action, $result ) {
3759
		if ( ! $result ) {
3760
			return;
3761
		}
3762
3763
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3764
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3765
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3766
			}
3767
		}
3768
	}
3769
3770
	/**
3771
	 * Register the remote file upload request handlers, if needed.
3772
	 *
3773
	 * @access public
3774
	 */
3775
	public function add_remote_request_handlers() {
3776
		// Remote file uploads are allowed only via AJAX requests.
3777
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3778
			return;
3779
		}
3780
3781
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3782
		$remote_request_actions = array(
3783
			'jetpack_upload_file',
3784
			'jetpack_update_file',
3785
		);
3786
3787
		// phpcs:ignore WordPress.Security.NonceVerification
3788
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3789
			return;
3790
		}
3791
3792
		// Require Jetpack authentication for the remote file upload AJAX requests.
3793
		if ( ! $this->connection_manager ) {
3794
			$this->connection_manager = new Connection_Manager();
3795
		}
3796
3797
		$this->connection_manager->require_jetpack_authentication();
3798
3799
		// Register the remote file upload AJAX handlers.
3800
		foreach ( $remote_request_actions as $action ) {
3801
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3802
		}
3803
	}
3804
3805
	/**
3806
	 * Handler for Jetpack remote file uploads.
3807
	 *
3808
	 * @access public
3809
	 */
3810
	public function remote_request_handlers() {
3811
		$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...
3812
3813
		switch ( current_filter() ) {
3814
			case 'wp_ajax_nopriv_jetpack_upload_file':
3815
				$response = $this->upload_handler();
3816
				break;
3817
3818
			case 'wp_ajax_nopriv_jetpack_update_file':
3819
				$response = $this->upload_handler( true );
3820
				break;
3821
			default:
3822
				$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...
3823
				break;
3824
		}
3825
3826
		if ( ! $response ) {
3827
			$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...
3828
		}
3829
3830
		if ( is_wp_error( $response ) ) {
3831
			$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...
3832
			$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...
3833
			$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...
3834
3835
			if ( ! is_int( $status_code ) ) {
3836
				$status_code = 400;
3837
			}
3838
3839
			status_header( $status_code );
3840
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3841
		}
3842
3843
		status_header( 200 );
3844
		if ( true === $response ) {
3845
			exit;
3846
		}
3847
3848
		die( json_encode( (object) $response ) );
3849
	}
3850
3851
	/**
3852
	 * Uploads a file gotten from the global $_FILES.
3853
	 * If `$update_media_item` is true and `post_id` is defined
3854
	 * the attachment file of the media item (gotten through of the post_id)
3855
	 * will be updated instead of add a new one.
3856
	 *
3857
	 * @param  boolean $update_media_item - update media attachment
3858
	 * @return array - An array describing the uploadind files process
3859
	 */
3860
	function upload_handler( $update_media_item = false ) {
3861
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3862
			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...
3863
		}
3864
3865
		$user = wp_authenticate( '', '' );
3866
		if ( ! $user || is_wp_error( $user ) ) {
3867
			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...
3868
		}
3869
3870
		wp_set_current_user( $user->ID );
3871
3872
		if ( ! current_user_can( 'upload_files' ) ) {
3873
			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...
3874
		}
3875
3876
		if ( empty( $_FILES ) ) {
3877
			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...
3878
		}
3879
3880
		foreach ( array_keys( $_FILES ) as $files_key ) {
3881
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3882
				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...
3883
			}
3884
		}
3885
3886
		$media_keys = array_keys( $_FILES['media'] );
3887
3888
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3889
		if ( ! $token || is_wp_error( $token ) ) {
3890
			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...
3891
		}
3892
3893
		$uploaded_files = array();
3894
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3895
		unset( $GLOBALS['post'] );
3896
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3897
			$file = array();
3898
			foreach ( $media_keys as $media_key ) {
3899
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3900
			}
3901
3902
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3903
3904
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3905
			if ( $hmac_provided !== $hmac_file ) {
3906
				$uploaded_files[ $index ] = (object) array(
3907
					'error'             => 'invalid_hmac',
3908
					'error_description' => 'The corresponding HMAC for this file does not match',
3909
				);
3910
				continue;
3911
			}
3912
3913
			$_FILES['.jetpack.upload.'] = $file;
3914
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3915
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3916
				$post_id = 0;
3917
			}
3918
3919
			if ( $update_media_item ) {
3920
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3921
					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...
3922
				}
3923
3924
				$media_array = $_FILES['media'];
3925
3926
				$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...
3927
				$file_array['type']     = $media_array['type'][0];
3928
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3929
				$file_array['error']    = $media_array['error'][0];
3930
				$file_array['size']     = $media_array['size'][0];
3931
3932
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3933
3934
				if ( is_wp_error( $edited_media_item ) ) {
3935
					return $edited_media_item;
3936
				}
3937
3938
				$response = (object) array(
3939
					'id'   => (string) $post_id,
3940
					'file' => (string) $edited_media_item->post_title,
3941
					'url'  => (string) wp_get_attachment_url( $post_id ),
3942
					'type' => (string) $edited_media_item->post_mime_type,
3943
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3944
				);
3945
3946
				return (array) array( $response );
3947
			}
3948
3949
			$attachment_id = media_handle_upload(
3950
				'.jetpack.upload.',
3951
				$post_id,
3952
				array(),
3953
				array(
3954
					'action' => 'jetpack_upload_file',
3955
				)
3956
			);
3957
3958
			if ( ! $attachment_id ) {
3959
				$uploaded_files[ $index ] = (object) array(
3960
					'error'             => 'unknown',
3961
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3962
				);
3963
			} elseif ( is_wp_error( $attachment_id ) ) {
3964
				$uploaded_files[ $index ] = (object) array(
3965
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3966
					'error_description' => $attachment_id->get_error_message(),
3967
				);
3968
			} else {
3969
				$attachment               = get_post( $attachment_id );
3970
				$uploaded_files[ $index ] = (object) array(
3971
					'id'   => (string) $attachment_id,
3972
					'file' => $attachment->post_title,
3973
					'url'  => wp_get_attachment_url( $attachment_id ),
3974
					'type' => $attachment->post_mime_type,
3975
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3976
				);
3977
				// Zip files uploads are not supported unless they are done for installation purposed
3978
				// lets delete them in case something goes wrong in this whole process
3979
				if ( 'application/zip' === $attachment->post_mime_type ) {
3980
					// Schedule a cleanup for 2 hours from now in case of failed install.
3981
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3982
				}
3983
			}
3984
		}
3985
		if ( ! is_null( $global_post ) ) {
3986
			$GLOBALS['post'] = $global_post;
3987
		}
3988
3989
		return $uploaded_files;
3990
	}
3991
3992
	/**
3993
	 * Add help to the Jetpack page
3994
	 *
3995
	 * @since Jetpack (1.2.3)
3996
	 * @return false if not the Jetpack page
3997
	 */
3998
	function admin_help() {
3999
		$current_screen = get_current_screen();
4000
4001
		// Overview
4002
		$current_screen->add_help_tab(
4003
			array(
4004
				'id'      => 'home',
4005
				'title'   => __( 'Home', 'jetpack' ),
4006
				'content' =>
4007
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4008
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4009
					'<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>',
4010
			)
4011
		);
4012
4013
		// Screen Content
4014
		if ( current_user_can( 'manage_options' ) ) {
4015
			$current_screen->add_help_tab(
4016
				array(
4017
					'id'      => 'settings',
4018
					'title'   => __( 'Settings', 'jetpack' ),
4019
					'content' =>
4020
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4021
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4022
						'<ol>' .
4023
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4024
							'<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>' .
4025
						'</ol>' .
4026
						'<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>',
4027
				)
4028
			);
4029
		}
4030
4031
		// Help Sidebar
4032
		$support_url = Redirect::get_url( 'jetpack-support' );
4033
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4034
		$current_screen->set_help_sidebar(
4035
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4036
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4037
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4038
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4039
		);
4040
	}
4041
4042
	function admin_menu_css() {
4043
		wp_enqueue_style( 'jetpack-icons' );
4044
	}
4045
4046
	function admin_menu_order() {
4047
		return true;
4048
	}
4049
4050
	function jetpack_menu_order( $menu_order ) {
4051
		$jp_menu_order = array();
4052
4053
		foreach ( $menu_order as $index => $item ) {
4054
			if ( $item != 'jetpack' ) {
4055
				$jp_menu_order[] = $item;
4056
			}
4057
4058
			if ( $index == 0 ) {
4059
				$jp_menu_order[] = 'jetpack';
4060
			}
4061
		}
4062
4063
		return $jp_menu_order;
4064
	}
4065
4066
	function admin_banner_styles() {
4067
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4068
4069
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4070
			wp_register_style(
4071
				'jetpack-dops-style',
4072
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4073
				array(),
4074
				JETPACK__VERSION
4075
			);
4076
		}
4077
4078
		wp_enqueue_style(
4079
			'jetpack',
4080
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4081
			array( 'jetpack-dops-style' ),
4082
			JETPACK__VERSION . '-20121016'
4083
		);
4084
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4085
		wp_style_add_data( 'jetpack', 'suffix', $min );
4086
	}
4087
4088
	function plugin_action_links( $actions ) {
4089
4090
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4091
4092
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
4093
			return array_merge(
4094
				$jetpack_home,
4095
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4096
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4097
				$actions
4098
			);
4099
		}
4100
4101
		return array_merge( $jetpack_home, $actions );
4102
	}
4103
4104
	/**
4105
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4106
	 *
4107
	 * @param string $hook The current admin page.
4108
	 *
4109
	 * @return void
4110
	 */
4111
	public function deactivate_dialog( $hook ) {
4112
		if (
4113
			'plugins.php' === $hook
4114
			&& self::is_active()
4115
		) {
4116
4117
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4118
4119
			if ( count( $active_plugins_using_connection ) > 1 ) {
4120
4121
				add_thickbox();
4122
4123
				wp_register_script(
4124
					'jp-tracks',
4125
					'//stats.wp.com/w.js',
4126
					array(),
4127
					gmdate( 'YW' ),
4128
					true
4129
				);
4130
4131
				wp_register_script(
4132
					'jp-tracks-functions',
4133
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4134
					array( 'jp-tracks' ),
4135
					JETPACK__VERSION,
4136
					false
4137
				);
4138
4139
				wp_enqueue_script(
4140
					'jetpack-deactivate-dialog-js',
4141
					Assets::get_file_url_for_environment(
4142
						'_inc/build/jetpack-deactivate-dialog.min.js',
4143
						'_inc/jetpack-deactivate-dialog.js'
4144
					),
4145
					array( 'jquery', 'jp-tracks-functions' ),
4146
					JETPACK__VERSION,
4147
					true
4148
				);
4149
4150
				wp_localize_script(
4151
					'jetpack-deactivate-dialog-js',
4152
					'deactivate_dialog',
4153
					array(
4154
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4155
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4156
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4157
					)
4158
				);
4159
4160
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4161
4162
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4163
			}
4164
		}
4165
	}
4166
4167
	/**
4168
	 * Outputs the content of the deactivation modal
4169
	 *
4170
	 * @return void
4171
	 */
4172
	public function deactivate_dialog_content() {
4173
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4174
		unset( $active_plugins_using_connection['jetpack'] );
4175
		$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 4173 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...
4176
	}
4177
4178
	/**
4179
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4180
	 *
4181
	 * @param string $login_url The wp-login URL.
4182
	 * @param string $redirect  URL to redirect users after logging in.
4183
	 * @since Jetpack 8.4
4184
	 * @return string
4185
	 */
4186
	public function login_url( $login_url, $redirect ) {
4187
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4188
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4189
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4190
		}
4191
		return $login_url;
4192
	}
4193
4194
	/**
4195
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4196
	 *
4197
	 * @since Jetpack 8.4
4198
	 */
4199
	public function login_init() {
4200
		// phpcs:ignore WordPress.Security.NonceVerification
4201
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4202
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4203
			wp_safe_redirect(
4204
				add_query_arg(
4205
					array(
4206
						'forceInstall' => 1,
4207
						'url'          => rawurlencode( get_site_url() ),
4208
					),
4209
					// @todo provide way to go to specific calypso env.
4210
					self::get_calypso_host() . 'jetpack/connect'
4211
				)
4212
			);
4213
			exit;
4214
		}
4215
	}
4216
4217
	/*
4218
	 * Registration flow:
4219
	 * 1 - ::admin_page_load() action=register
4220
	 * 2 - ::try_registration()
4221
	 * 3 - ::register()
4222
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4223
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4224
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4225
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4226
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4227
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4228
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4229
	 *       jetpack_id, jetpack_secret, jetpack_public
4230
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4231
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4232
	 * 5 - user logs in with WP.com account
4233
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4234
	 *		- Manager::authorize()
4235
	 *		- Manager::get_token()
4236
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4237
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4238
	 *			- which responds with access_token, token_type, scope
4239
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4240
	 *		- Jetpack::activate_default_modules()
4241
	 *     		- Deactivates deprecated plugins
4242
	 *     		- Activates all default modules
4243
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4244
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4245
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4246
	 *     Done!
4247
	 */
4248
4249
	/**
4250
	 * Handles the page load events for the Jetpack admin page
4251
	 */
4252
	function admin_page_load() {
4253
		$error = false;
4254
4255
		// Make sure we have the right body class to hook stylings for subpages off of.
4256
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4257
4258
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4259
			// Should only be used in intermediate redirects to preserve state across redirects
4260
			self::restate();
4261
		}
4262
4263
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4264
			// @todo: Add validation against a known allowed list.
4265
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4266
			// User clicked in the iframe to link their accounts
4267
			if ( ! self::connection()->is_user_connected() ) {
4268
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4269
4270
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4271
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4272
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4273
4274
				if ( isset( $_GET['notes_iframe'] ) ) {
4275
					$connect_url .= '&notes_iframe';
4276
				}
4277
				wp_redirect( $connect_url );
4278
				exit;
4279
			} else {
4280
				if ( ! isset( $_GET['calypso_env'] ) ) {
4281
					self::state( 'message', 'already_authorized' );
4282
					wp_safe_redirect( self::admin_url() );
4283
					exit;
4284
				} else {
4285
					$connect_url  = $this->build_connect_url( true, false, $from );
4286
					$connect_url .= '&already_authorized=true';
4287
					wp_redirect( $connect_url );
4288
					exit;
4289
				}
4290
			}
4291
		}
4292
4293
		if ( isset( $_GET['action'] ) ) {
4294
			switch ( $_GET['action'] ) {
4295
				case 'authorize_redirect':
4296
					self::log( 'authorize_redirect' );
4297
4298
					add_filter(
4299
						'allowed_redirect_hosts',
4300
						function ( $domains ) {
4301
							$domains[] = 'jetpack.com';
4302
							$domains[] = 'jetpack.wordpress.com';
4303
							$domains[] = 'wordpress.com';
4304
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4305
							return array_unique( $domains );
4306
						}
4307
					);
4308
4309
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4310
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4311
4312
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4313
						// The destination URL is missing or invalid, nothing to do here.
4314
						exit;
4315
					}
4316
4317
					if ( static::is_active() && static::connection()->is_user_connected() ) {
4318
						// The user is either already connected, or finished the connection process.
4319
						wp_safe_redirect( $dest_url );
4320
						exit;
4321
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4322
						// The user decided not to proceed with setting up the connection.
4323
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4324
						exit;
4325
					}
4326
4327
					$redirect_url = self::admin_url(
4328
						array(
4329
							'page'     => 'jetpack',
4330
							'action'   => 'authorize_redirect',
4331
							'dest_url' => rawurlencode( $dest_url ),
4332
							'done'     => '1',
4333
						)
4334
					);
4335
4336
					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...
4337
					exit;
4338
				case 'authorize':
4339
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4340
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4341
					exit;
4342
				case 'register':
4343
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4344
						$error = 'cheatin';
4345
						break;
4346
					}
4347
					check_admin_referer( 'jetpack-register' );
4348
					self::log( 'register' );
4349
					self::maybe_set_version_option();
4350
					$registered = self::try_registration();
4351
					if ( is_wp_error( $registered ) ) {
4352
						$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...
4353
						self::state( 'error', $error );
4354
						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...
4355
4356
						/**
4357
						 * Jetpack registration Error.
4358
						 *
4359
						 * @since 7.5.0
4360
						 *
4361
						 * @param string|int $error The error code.
4362
						 * @param \WP_Error $registered The error object.
4363
						 */
4364
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4365
						break;
4366
					}
4367
4368
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4369
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4370
4371
					/**
4372
					 * Jetpack registration Success.
4373
					 *
4374
					 * @since 7.5.0
4375
					 *
4376
					 * @param string $from 'from' GET parameter;
4377
					 */
4378
					do_action( 'jetpack_connection_register_success', $from );
4379
4380
					$url = $this->build_connect_url( true, $redirect, $from );
4381
4382
					if ( ! empty( $_GET['onboarding'] ) ) {
4383
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4384
					}
4385
4386
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4387
						$url = add_query_arg( 'auth_approved', 'true', $url );
4388
					}
4389
4390
					wp_redirect( $url );
4391
					exit;
4392
				case 'activate':
4393
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4394
						$error = 'cheatin';
4395
						break;
4396
					}
4397
4398
					$module = stripslashes( $_GET['module'] );
4399
					check_admin_referer( "jetpack_activate-$module" );
4400
					self::log( 'activate', $module );
4401
					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...
4402
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4403
					}
4404
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4405
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4406
					exit;
4407
				case 'activate_default_modules':
4408
					check_admin_referer( 'activate_default_modules' );
4409
					self::log( 'activate_default_modules' );
4410
					self::restate();
4411
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4412
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4413
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4414
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4415
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4416
					exit;
4417 View Code Duplication
				case 'disconnect':
4418
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4419
						$error = 'cheatin';
4420
						break;
4421
					}
4422
4423
					check_admin_referer( 'jetpack-disconnect' );
4424
					self::log( 'disconnect' );
4425
					self::disconnect();
4426
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4427
					exit;
4428 View Code Duplication
				case 'reconnect':
4429
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4430
						$error = 'cheatin';
4431
						break;
4432
					}
4433
4434
					check_admin_referer( 'jetpack-reconnect' );
4435
					self::log( 'reconnect' );
4436
					self::disconnect();
4437
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4438
					exit;
4439 View Code Duplication
				case 'deactivate':
4440
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4441
						$error = 'cheatin';
4442
						break;
4443
					}
4444
4445
					$modules = stripslashes( $_GET['module'] );
4446
					check_admin_referer( "jetpack_deactivate-$modules" );
4447
					foreach ( explode( ',', $modules ) as $module ) {
4448
						self::log( 'deactivate', $module );
4449
						self::deactivate_module( $module );
4450
						self::state( 'message', 'module_deactivated' );
4451
					}
4452
					self::state( 'module', $modules );
4453
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4454
					exit;
4455
				case 'unlink':
4456
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4457
					check_admin_referer( 'jetpack-unlink' );
4458
					self::log( 'unlink' );
4459
					$this->connection_manager->disconnect_user();
4460
					self::state( 'message', 'unlinked' );
4461
					if ( 'sub-unlink' == $redirect ) {
4462
						wp_safe_redirect( admin_url() );
4463
					} else {
4464
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4465
					}
4466
					exit;
4467
				case 'onboard':
4468
					if ( ! current_user_can( 'manage_options' ) ) {
4469
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4470
					} else {
4471
						self::create_onboarding_token();
4472
						$url = $this->build_connect_url( true );
4473
4474
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4475
							$url = add_query_arg( 'onboarding', $token, $url );
4476
						}
4477
4478
						$calypso_env = $this->get_calypso_env();
4479
						if ( ! empty( $calypso_env ) ) {
4480
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4481
						}
4482
4483
						wp_redirect( $url );
4484
						exit;
4485
					}
4486
					exit;
4487
				default:
4488
					/**
4489
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4490
					 *
4491
					 * @since 2.6.0
4492
					 *
4493
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4494
					 */
4495
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4496
			}
4497
		}
4498
4499
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4500
			self::activate_new_modules( true );
4501
		}
4502
4503
		$message_code = self::state( 'message' );
4504
		if ( self::state( 'optin-manage' ) ) {
4505
			$activated_manage = $message_code;
4506
			$message_code     = 'jetpack-manage';
4507
		}
4508
4509
		switch ( $message_code ) {
4510
			case 'jetpack-manage':
4511
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4512
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4513
				$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>';
4514
				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...
4515
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4516
				}
4517
				break;
4518
4519
		}
4520
4521
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4522
4523
		if ( ! empty( $deactivated_plugins ) ) {
4524
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4525
			$deactivated_titles  = array();
4526
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4527
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4528
					continue;
4529
				}
4530
4531
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4532
			}
4533
4534
			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...
4535
				if ( $this->message ) {
4536
					$this->message .= "<br /><br />\n";
4537
				}
4538
4539
				$this->message .= wp_sprintf(
4540
					_n(
4541
						'Jetpack contains the most recent version of the old %l plugin.',
4542
						'Jetpack contains the most recent versions of the old %l plugins.',
4543
						count( $deactivated_titles ),
4544
						'jetpack'
4545
					),
4546
					$deactivated_titles
4547
				);
4548
4549
				$this->message .= "<br />\n";
4550
4551
				$this->message .= _n(
4552
					'The old version has been deactivated and can be removed from your site.',
4553
					'The old versions have been deactivated and can be removed from your site.',
4554
					count( $deactivated_titles ),
4555
					'jetpack'
4556
				);
4557
			}
4558
		}
4559
4560
		$this->privacy_checks = self::state( 'privacy_checks' );
4561
4562
		if ( $this->message || $this->error || $this->privacy_checks ) {
4563
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4564
		}
4565
4566
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4567
	}
4568
4569
	function admin_notices() {
4570
4571
		if ( $this->error ) {
4572
			?>
4573
<div id="message" class="jetpack-message jetpack-err">
4574
	<div class="squeezer">
4575
		<h2>
4576
			<?php
4577
			echo wp_kses(
4578
				$this->error,
4579
				array(
4580
					'a'      => array( 'href' => array() ),
4581
					'small'  => true,
4582
					'code'   => true,
4583
					'strong' => true,
4584
					'br'     => true,
4585
					'b'      => true,
4586
				)
4587
			);
4588
			?>
4589
			</h2>
4590
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4591
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4592
<?php	endif; ?>
4593
	</div>
4594
</div>
4595
			<?php
4596
		}
4597
4598
		if ( $this->message ) {
4599
			?>
4600
<div id="message" class="jetpack-message">
4601
	<div class="squeezer">
4602
		<h2>
4603
			<?php
4604
			echo wp_kses(
4605
				$this->message,
4606
				array(
4607
					'strong' => array(),
4608
					'a'      => array( 'href' => true ),
4609
					'br'     => true,
4610
				)
4611
			);
4612
			?>
4613
			</h2>
4614
	</div>
4615
</div>
4616
			<?php
4617
		}
4618
4619
		if ( $this->privacy_checks ) :
4620
			$module_names = $module_slugs = array();
4621
4622
			$privacy_checks = explode( ',', $this->privacy_checks );
4623
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4624
			foreach ( $privacy_checks as $module_slug ) {
4625
				$module = self::get_module( $module_slug );
4626
				if ( ! $module ) {
4627
					continue;
4628
				}
4629
4630
				$module_slugs[] = $module_slug;
4631
				$module_names[] = "<strong>{$module['name']}</strong>";
4632
			}
4633
4634
			$module_slugs = join( ',', $module_slugs );
4635
			?>
4636
<div id="message" class="jetpack-message jetpack-err">
4637
	<div class="squeezer">
4638
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4639
		<p>
4640
			<?php
4641
			echo wp_kses(
4642
				wptexturize(
4643
					wp_sprintf(
4644
						_nx(
4645
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4646
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4647
							count( $privacy_checks ),
4648
							'%l = list of Jetpack module/feature names',
4649
							'jetpack'
4650
						),
4651
						$module_names
4652
					)
4653
				),
4654
				array( 'strong' => true )
4655
			);
4656
4657
			echo "\n<br />\n";
4658
4659
			echo wp_kses(
4660
				sprintf(
4661
					_nx(
4662
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4663
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4664
						count( $privacy_checks ),
4665
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4666
						'jetpack'
4667
					),
4668
					wp_nonce_url(
4669
						self::admin_url(
4670
							array(
4671
								'page'   => 'jetpack',
4672
								'action' => 'deactivate',
4673
								'module' => urlencode( $module_slugs ),
4674
							)
4675
						),
4676
						"jetpack_deactivate-$module_slugs"
4677
					),
4678
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4679
				),
4680
				array(
4681
					'a' => array(
4682
						'href'  => true,
4683
						'title' => true,
4684
					),
4685
				)
4686
			);
4687
			?>
4688
		</p>
4689
	</div>
4690
</div>
4691
			<?php
4692
endif;
4693
	}
4694
4695
	/**
4696
	 * We can't always respond to a signed XML-RPC request with a
4697
	 * helpful error message. In some circumstances, doing so could
4698
	 * leak information.
4699
	 *
4700
	 * Instead, track that the error occurred via a Jetpack_Option,
4701
	 * and send that data back in the heartbeat.
4702
	 * All this does is increment a number, but it's enough to find
4703
	 * trends.
4704
	 *
4705
	 * @param WP_Error $xmlrpc_error The error produced during
4706
	 *                               signature validation.
4707
	 */
4708
	function track_xmlrpc_error( $xmlrpc_error ) {
4709
		$code = is_wp_error( $xmlrpc_error )
4710
			? $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...
4711
			: 'should-not-happen';
4712
4713
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4714
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4715
			// No need to update the option if we already have
4716
			// this code stored.
4717
			return;
4718
		}
4719
		$xmlrpc_errors[ $code ] = true;
4720
4721
		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...
4722
	}
4723
4724
	/**
4725
	 * Initialize the jetpack stats instance only when needed
4726
	 *
4727
	 * @return void
4728
	 */
4729
	private function initialize_stats() {
4730
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4731
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4732
		}
4733
	}
4734
4735
	/**
4736
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4737
	 */
4738
	function stat( $group, $detail ) {
4739
		$this->initialize_stats();
4740
		$this->a8c_mc_stats_instance->add( $group, $detail );
4741
4742
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4743
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4744
	}
4745
4746
	/**
4747
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4748
	 */
4749
	function do_stats( $method = '' ) {
4750
		$this->initialize_stats();
4751
		if ( 'server_side' === $method ) {
4752
			$this->a8c_mc_stats_instance->do_server_side_stats();
4753
		} else {
4754
			$this->a8c_mc_stats_instance->do_stats();
4755
		}
4756
4757
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4758
		$this->stats = array();
4759
	}
4760
4761
	/**
4762
	 * Runs stats code for a one-off, server-side.
4763
	 *
4764
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4765
	 *
4766
	 * @return bool If it worked.
4767
	 */
4768
	static function do_server_side_stat( $args ) {
4769
		$url                   = self::build_stats_url( $args );
4770
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4771
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4772
	}
4773
4774
	/**
4775
	 * Builds the stats url.
4776
	 *
4777
	 * @param $args array|string The arguments to append to the URL.
4778
	 *
4779
	 * @return string The URL to be pinged.
4780
	 */
4781
	static function build_stats_url( $args ) {
4782
4783
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4784
		return $a8c_mc_stats_instance->build_stats_url( $args );
4785
4786
	}
4787
4788
	/**
4789
	 * Builds a URL to the Jetpack connection auth page
4790
	 *
4791
	 * @since 3.9.5
4792
	 *
4793
	 * @param bool        $raw If true, URL will not be escaped.
4794
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4795
	 *                              If string, will be a custom redirect.
4796
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4797
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4798
	 *
4799
	 * @return string Connect URL
4800
	 */
4801
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4802
		$site_id    = Jetpack_Options::get_option( 'id' );
4803
		$blog_token = ( new Tokens() )->get_access_token();
4804
4805
		if ( $register || ! $blog_token || ! $site_id ) {
4806
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4807
4808
			if ( ! empty( $redirect ) ) {
4809
				$url = add_query_arg(
4810
					'redirect',
4811
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4812
					$url
4813
				);
4814
			}
4815
4816
			if ( is_network_admin() ) {
4817
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4818
			}
4819
4820
			$calypso_env = self::get_calypso_env();
4821
4822
			if ( ! empty( $calypso_env ) ) {
4823
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4824
			}
4825
		} else {
4826
4827
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4828
			// because otherwise this logic can get us in to a loop.
4829
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4830
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4831
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4832
4833
				$response = Client::wpcom_json_api_request_as_blog(
4834
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4835
					'1.1'
4836
				);
4837
4838
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4839
4840
					// Generating a register URL instead to refresh the existing token
4841
					return $this->build_connect_url( $raw, $redirect, $from, true );
4842
				}
4843
			}
4844
4845
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4801 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...
4846
		}
4847
4848
		if ( $from ) {
4849
			$url = add_query_arg( 'from', $from, $url );
4850
		}
4851
4852
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4853
		/**
4854
		 * Filter the URL used when connecting a user to a WordPress.com account.
4855
		 *
4856
		 * @since 8.1.0
4857
		 *
4858
		 * @param string $url Connection URL.
4859
		 * @param bool   $raw If true, URL will not be escaped.
4860
		 */
4861
		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...
4862
	}
4863
4864
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4865
4866
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4867
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4868
4869
		if ( $iframe ) {
4870
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4871
		}
4872
4873
		$c8n = self::connection();
4874
		$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...
4875
4876
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4877
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4878
4879
		if ( $iframe ) {
4880
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4881
		}
4882
4883
		/**
4884
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4885
		 *
4886
		 * @since 8.9.0
4887
		 *
4888
		 * @param string $url Connection URL.
4889
		 */
4890
		return apply_filters( 'jetpack_build_authorize_url', $url );
4891
	}
4892
4893
	/**
4894
	 * Filters the connection URL parameter array.
4895
	 *
4896
	 * @param array $args default URL parameters used by the package.
4897
	 * @return array the modified URL arguments array.
4898
	 */
4899
	public static function filter_connect_request_body( $args ) {
4900
		if (
4901
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4902
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4903
		) {
4904
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4905
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4906
				? $gp_locale->slug
4907
				: '';
4908
		}
4909
4910
		$tracking        = new Tracking();
4911
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4912
4913
		$args = array_merge(
4914
			$args,
4915
			array(
4916
				'_ui' => $tracks_identity['_ui'],
4917
				'_ut' => $tracks_identity['_ut'],
4918
			)
4919
		);
4920
4921
		$calypso_env = self::get_calypso_env();
4922
4923
		if ( ! empty( $calypso_env ) ) {
4924
			$args['calypso_env'] = $calypso_env;
4925
		}
4926
4927
		return $args;
4928
	}
4929
4930
	/**
4931
	 * Filters the URL that will process the connection data. It can be different from the URL
4932
	 * that we send the user to after everything is done.
4933
	 *
4934
	 * @param String $processing_url the default redirect URL used by the package.
4935
	 * @return String the modified URL.
4936
	 *
4937
	 * @deprecated since Jetpack 9.5.0
4938
	 */
4939
	public static function filter_connect_processing_url( $processing_url ) {
4940
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4941
4942
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4943
		return $processing_url;
4944
	}
4945
4946
	/**
4947
	 * Filters the redirection URL that is used for connect requests. The redirect
4948
	 * URL should return the user back to the Jetpack console.
4949
	 *
4950
	 * @param String $redirect the default redirect URL used by the package.
4951
	 * @return String the modified URL.
4952
	 */
4953
	public static function filter_connect_redirect_url( $redirect ) {
4954
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4955
		$redirect           = $redirect
4956
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4957
			: $jetpack_admin_page;
4958
4959
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4960
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4961
		}
4962
4963
		return $redirect;
4964
	}
4965
4966
	/**
4967
	 * This action fires at the beginning of the Manager::authorize method.
4968
	 */
4969
	public static function authorize_starting() {
4970
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4971
		// Checking if site has been active/connected previously before recording unique connection.
4972
		if ( ! $jetpack_unique_connection ) {
4973
			// jetpack_unique_connection option has never been set.
4974
			$jetpack_unique_connection = array(
4975
				'connected'    => 0,
4976
				'disconnected' => 0,
4977
				'version'      => '3.6.1',
4978
			);
4979
4980
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4981
4982
			// Track unique connection.
4983
			$jetpack = self::init();
4984
4985
			$jetpack->stat( 'connections', 'unique-connection' );
4986
			$jetpack->do_stats( 'server_side' );
4987
		}
4988
4989
		// Increment number of times connected.
4990
		$jetpack_unique_connection['connected'] += 1;
4991
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4992
	}
4993
4994
	/**
4995
	 * This action fires when the site is registered (connected at a site level).
4996
	 */
4997
	public function handle_unique_registrations_stats() {
4998
		$jetpack_unique_registrations = Jetpack_Options::get_option( 'unique_registrations' );
4999
		// Checking if site has been registered previously before recording unique connection.
5000
		if ( ! $jetpack_unique_registrations ) {
5001
5002
			$jetpack_unique_registrations = 0;
5003
5004
			$this->stat( 'connections', 'unique-registrations' );
5005
			$this->do_stats( 'server_side' );
5006
		}
5007
5008
		// Increment number of times connected.
5009
		$jetpack_unique_registrations ++;
5010
		Jetpack_Options::update_option( 'unique_registrations', $jetpack_unique_registrations );
5011
	}
5012
5013
	/**
5014
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5015
	 * linked.
5016
	 */
5017
	public static function authorize_ending_linked() {
5018
		// Don't activate anything since we are just connecting a user.
5019
		self::state( 'message', 'linked' );
5020
	}
5021
5022
	/**
5023
	 * This action fires at the end of the Manager::authorize method when the master user is
5024
	 * authorized.
5025
	 *
5026
	 * @param array $data The request data.
5027
	 */
5028
	public static function authorize_ending_authorized( $data ) {
5029
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5030
		self::invalidate_onboarding_token();
5031
5032
		// If redirect_uri is SSO, ensure SSO module is enabled.
5033
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5034
5035
		/** This filter is documented in class.jetpack-cli.php */
5036
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5037
5038
		$activate_sso = (
5039
			isset( $redirect_options['action'] ) &&
5040
			'jetpack-sso' === $redirect_options['action'] &&
5041
			$jetpack_start_enable_sso
5042
		);
5043
5044
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5045
5046
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5047
	}
5048
5049
	/**
5050
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5051
	 */
5052
	public static function activate_default_modules_on_site_register() {
5053
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5054
		if ( $active_modules ) {
5055
			self::delete_active_modules();
5056
5057
			// If there was previously activated modules (a reconnection), re-activate them all including those that require a user, and do not re-activate those that have been deactivated.
5058
			self::activate_default_modules( 999, 1, $active_modules, false );
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...
5059
		} else {
5060
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5061
			self::activate_default_modules( false, false, array(), false, null, null, false );
5062
		}
5063
5064
		// Since this is a fresh connection, be sure to clear out IDC options.
5065
		Jetpack_IDC::clear_all_idc_options();
5066
	}
5067
5068
	/**
5069
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5070
	 * reconnect process is completed.
5071
	 * Note that this currently only happens when we don't need the user to re-authorize
5072
	 * their WP.com account, eg in cases where we are restoring a connection with
5073
	 * unhealthy blog token.
5074
	 */
5075
	public static function reconnection_completed() {
5076
		self::state( 'message', 'reconnection_completed' );
5077
	}
5078
5079
	/**
5080
	 * Get our assumed site creation date.
5081
	 * Calculated based on the earlier date of either:
5082
	 * - Earliest admin user registration date.
5083
	 * - Earliest date of post of any post type.
5084
	 *
5085
	 * @since 7.2.0
5086
	 * @deprecated since 7.8.0
5087
	 *
5088
	 * @return string Assumed site creation date and time.
5089
	 */
5090
	public static function get_assumed_site_creation_date() {
5091
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5092
		return self::connection()->get_assumed_site_creation_date();
5093
	}
5094
5095 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5096
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5097
5098
		if ( $activation_source_name ) {
5099
			$args['_as'] = urlencode( $activation_source_name );
5100
		}
5101
5102
		if ( $activation_source_keyword ) {
5103
			$args['_ak'] = urlencode( $activation_source_keyword );
5104
		}
5105
	}
5106
5107
	function build_reconnect_url( $raw = false ) {
5108
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5109
		return $raw ? $url : esc_url( $url );
5110
	}
5111
5112
	public static function admin_url( $args = null ) {
5113
		$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...
5114
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5115
		return $url;
5116
	}
5117
5118
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5119
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5120
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5121
	}
5122
5123
	function dismiss_jetpack_notice() {
5124
5125
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5126
			return;
5127
		}
5128
5129
		switch ( $_GET['jetpack-notice'] ) {
5130
			case 'dismiss':
5131
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5132
5133
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5134
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5135
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5136
				}
5137
				break;
5138
		}
5139
	}
5140
5141
	public static function sort_modules( $a, $b ) {
5142
		if ( $a['sort'] == $b['sort'] ) {
5143
			return 0;
5144
		}
5145
5146
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5147
	}
5148
5149
	function ajax_recheck_ssl() {
5150
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5151
		$result = self::permit_ssl( true );
5152
		wp_send_json(
5153
			array(
5154
				'enabled' => $result,
5155
				'message' => get_transient( 'jetpack_https_test_message' ),
5156
			)
5157
		);
5158
	}
5159
5160
	/* Client API */
5161
5162
	/**
5163
	 * Returns the requested Jetpack API URL
5164
	 *
5165
	 * @deprecated since 7.7
5166
	 * @return string
5167
	 */
5168
	public static function api_url( $relative_url ) {
5169
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5170
		$connection = self::connection();
5171
		return $connection->api_url( $relative_url );
5172
	}
5173
5174
	/**
5175
	 * @deprecated 8.0
5176
	 *
5177
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5178
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5179
	 */
5180
	public static function fix_url_for_bad_hosts( $url ) {
5181
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5182
		return $url;
5183
	}
5184
5185
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5186
		// Default to a blog token.
5187
		$token_type = 'blog';
5188
5189
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5190
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5191
			if ( ! empty( $_GET['onboarding'] ) ) {
5192
				$jpo = $_GET;
5193
			} else {
5194
				$jpo = json_decode( $request_data, true );
5195
			}
5196
5197
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5198
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5199
5200
			if (
5201
				isset( $jpo_user )
5202
				&& isset( $jpo_token )
5203
				&& is_email( $jpo_user )
5204
				&& ctype_alnum( $jpo_token )
5205
				&& isset( $_GET['rest_route'] )
5206
				&& self::validate_onboarding_token_action(
5207
					$jpo_token,
5208
					$_GET['rest_route']
5209
				)
5210
			) {
5211
				$jp_user = get_user_by( 'email', $jpo_user );
5212
				if ( is_a( $jp_user, 'WP_User' ) ) {
5213
					wp_set_current_user( $jp_user->ID );
5214
					$user_can = is_multisite()
5215
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5216
						: current_user_can( 'manage_options' );
5217
					if ( $user_can ) {
5218
						$token_type              = 'user';
5219
						$token->external_user_id = $jp_user->ID;
5220
					}
5221
				}
5222
			}
5223
5224
			$token_data['type']    = $token_type;
5225
			$token_data['user_id'] = $token->external_user_id;
5226
		}
5227
5228
		return $token_data;
5229
	}
5230
5231
	/**
5232
	 * Create a random secret for validating onboarding payload
5233
	 *
5234
	 * @return string Secret token
5235
	 */
5236
	public static function create_onboarding_token() {
5237
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5238
			$token = wp_generate_password( 32, false );
5239
			Jetpack_Options::update_option( 'onboarding', $token );
5240
		}
5241
5242
		return $token;
5243
	}
5244
5245
	/**
5246
	 * Remove the onboarding token
5247
	 *
5248
	 * @return bool True on success, false on failure
5249
	 */
5250
	public static function invalidate_onboarding_token() {
5251
		return Jetpack_Options::delete_option( 'onboarding' );
5252
	}
5253
5254
	/**
5255
	 * Validate an onboarding token for a specific action
5256
	 *
5257
	 * @return boolean True if token/action pair is accepted, false if not
5258
	 */
5259
	public static function validate_onboarding_token_action( $token, $action ) {
5260
		// Compare tokens, bail if tokens do not match
5261
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5262
			return false;
5263
		}
5264
5265
		// List of valid actions we can take
5266
		$valid_actions = array(
5267
			'/jetpack/v4/settings',
5268
		);
5269
5270
		// Only allow valid actions.
5271
		if ( ! in_array( $action, $valid_actions ) ) {
5272
			return false;
5273
		}
5274
5275
		return true;
5276
	}
5277
5278
	/**
5279
	 * Checks to see if the URL is using SSL to connect with Jetpack
5280
	 *
5281
	 * @since 2.3.3
5282
	 * @return boolean
5283
	 */
5284
	public static function permit_ssl( $force_recheck = false ) {
5285
		// Do some fancy tests to see if ssl is being supported
5286
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5287
			$message = '';
5288
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5289
				$ssl = 0;
5290
			} else {
5291
				$ssl = 1;
5292
5293
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5294
					$ssl     = 0;
5295
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5296
				} else {
5297
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5298
					if ( is_wp_error( $response ) ) {
5299
						$ssl     = 0;
5300
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5301
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5302
						$ssl     = 0;
5303
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5304
					}
5305
				}
5306
			}
5307
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5308
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5309
		}
5310
5311
		return (bool) $ssl;
5312
	}
5313
5314
	/*
5315
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5316
	 */
5317
	public function alert_auto_ssl_fail() {
5318
		if ( ! current_user_can( 'manage_options' ) ) {
5319
			return;
5320
		}
5321
5322
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5323
		?>
5324
5325
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5326
			<div class="jp-banner__content">
5327
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5328
				<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>
5329
				<p>
5330
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5331
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5332
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5333
				</p>
5334
				<p>
5335
					<?php
5336
					printf(
5337
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5338
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5339
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5340
					);
5341
					?>
5342
				</p>
5343
			</div>
5344
		</div>
5345
		<style>
5346
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5347
		</style>
5348
		<script type="text/javascript">
5349
			jQuery( document ).ready( function( $ ) {
5350
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5351
					var $this = $( this );
5352
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5353
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5354
					e.preventDefault();
5355
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5356
					$.post( ajaxurl, data )
5357
					  .done( function( response ) {
5358
						  if ( response.enabled ) {
5359
							  $( '#jetpack-ssl-warning' ).hide();
5360
						  } else {
5361
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5362
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5363
						  }
5364
					  }.bind( $this ) );
5365
				} );
5366
			} );
5367
		</script>
5368
5369
		<?php
5370
	}
5371
5372
	/**
5373
	 * Returns the Jetpack XML-RPC API
5374
	 *
5375
	 * @deprecated 8.0 Use Connection_Manager instead.
5376
	 * @return string
5377
	 */
5378
	public static function xmlrpc_api_url() {
5379
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5380
		return self::connection()->xmlrpc_api_url();
5381
	}
5382
5383
	/**
5384
	 * Returns the connection manager object.
5385
	 *
5386
	 * @return Automattic\Jetpack\Connection\Manager
5387
	 */
5388
	public static function connection() {
5389
		$jetpack = static::init();
5390
5391
		// If the connection manager hasn't been instantiated, do that now.
5392
		if ( ! $jetpack->connection_manager ) {
5393
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5394
		}
5395
5396
		return $jetpack->connection_manager;
5397
	}
5398
5399
	/**
5400
	 * Creates two secret tokens and the end of life timestamp for them.
5401
	 *
5402
	 * Note these tokens are unique per call, NOT static per site for connecting.
5403
	 *
5404
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5405
	 *
5406
	 * @since 2.6
5407
	 * @param String  $action  The action name.
5408
	 * @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...
5409
	 * @param Integer $exp     Expiration time in seconds.
5410
	 * @return array
5411
	 */
5412
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5413
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5414
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5415
	}
5416
5417
	public static function get_secrets( $action, $user_id ) {
5418
		$secrets = ( new Secrets() )->get( $action, $user_id );
5419
5420
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5421
			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...
5422
		}
5423
5424
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5425
			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...
5426
		}
5427
5428
		return $secrets;
5429
	}
5430
5431
	/**
5432
	 * Builds the timeout limit for queries talking with the wpcom servers.
5433
	 *
5434
	 * Based on local php max_execution_time in php.ini
5435
	 *
5436
	 * @since 2.6
5437
	 * @return int
5438
	 * @deprecated
5439
	 **/
5440
	public function get_remote_query_timeout_limit() {
5441
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5442
		return self::get_max_execution_time();
5443
	}
5444
5445
	/**
5446
	 * Builds the timeout limit for queries talking with the wpcom servers.
5447
	 *
5448
	 * Based on local php max_execution_time in php.ini
5449
	 *
5450
	 * @since 5.4
5451
	 * @return int
5452
	 **/
5453
	public static function get_max_execution_time() {
5454
		$timeout = (int) ini_get( 'max_execution_time' );
5455
5456
		// Ensure exec time set in php.ini
5457
		if ( ! $timeout ) {
5458
			$timeout = 30;
5459
		}
5460
		return $timeout;
5461
	}
5462
5463
	/**
5464
	 * Sets a minimum request timeout, and returns the current timeout
5465
	 *
5466
	 * @since 5.4
5467
	 **/
5468 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5469
		$timeout = self::get_max_execution_time();
5470
		if ( $timeout < $min_timeout ) {
5471
			$timeout = $min_timeout;
5472
			set_time_limit( $timeout );
5473
		}
5474
		return $timeout;
5475
	}
5476
5477
	/**
5478
	 * Takes the response from the Jetpack register new site endpoint and
5479
	 * verifies it worked properly.
5480
	 *
5481
	 * @since 2.6
5482
	 * @deprecated since 7.7.0
5483
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5484
	 **/
5485
	public function validate_remote_register_response() {
5486
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5487
	}
5488
5489
	/**
5490
	 * @return bool|WP_Error
5491
	 */
5492
	public static function register() {
5493
		$tracking = new Tracking();
5494
		$tracking->record_user_event( 'jpc_register_begin' );
5495
5496
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5497
5498
		$connection   = self::connection();
5499
		$registration = $connection->register();
5500
5501
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5502
5503
		if ( ! $registration || is_wp_error( $registration ) ) {
5504
			return $registration;
5505
		}
5506
5507
		return true;
5508
	}
5509
5510
	/**
5511
	 * Filters the registration request body to include tracking properties.
5512
	 *
5513
	 * @param array $properties
5514
	 * @return array amended properties.
5515
	 */
5516 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5517
		$tracking        = new Tracking();
5518
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5519
5520
		return array_merge(
5521
			$properties,
5522
			array(
5523
				'_ui' => $tracks_identity['_ui'],
5524
				'_ut' => $tracks_identity['_ut'],
5525
			)
5526
		);
5527
	}
5528
5529
	/**
5530
	 * Filters the token request body to include tracking properties.
5531
	 *
5532
	 * @param array $properties
5533
	 * @return array amended properties.
5534
	 */
5535 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5536
		$tracking        = new Tracking();
5537
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5538
5539
		return array_merge(
5540
			$properties,
5541
			array(
5542
				'_ui' => $tracks_identity['_ui'],
5543
				'_ut' => $tracks_identity['_ut'],
5544
			)
5545
		);
5546
	}
5547
5548
	/**
5549
	 * If the db version is showing something other that what we've got now, bump it to current.
5550
	 *
5551
	 * @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...
5552
	 */
5553
	public static function maybe_set_version_option() {
5554
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5555
		if ( JETPACK__VERSION != $version ) {
5556
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5557
5558
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5559
				/** This action is documented in class.jetpack.php */
5560
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5561
			}
5562
5563
			return true;
5564
		}
5565
		return false;
5566
	}
5567
5568
	/* Client Server API */
5569
5570
	/**
5571
	 * Loads the Jetpack XML-RPC client.
5572
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5573
	 *
5574
	 * @deprecated since 7.7.0
5575
	 */
5576
	public static function load_xml_rpc_client() {
5577
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5578
	}
5579
5580
	/**
5581
	 * Resets the saved authentication state in between testing requests.
5582
	 *
5583
	 * @deprecated since 8.9.0
5584
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5585
	 */
5586
	public function reset_saved_auth_state() {
5587
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5588
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5589
	}
5590
5591
	/**
5592
	 * Verifies the signature of the current request.
5593
	 *
5594
	 * @deprecated since 7.7.0
5595
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5596
	 *
5597
	 * @return false|array
5598
	 */
5599
	public function verify_xml_rpc_signature() {
5600
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5601
		return self::connection()->verify_xml_rpc_signature();
5602
	}
5603
5604
	/**
5605
	 * Verifies the signature of the current request.
5606
	 *
5607
	 * This function has side effects and should not be used. Instead,
5608
	 * use the memoized version `->verify_xml_rpc_signature()`.
5609
	 *
5610
	 * @deprecated since 7.7.0
5611
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5612
	 * @internal
5613
	 */
5614
	private function internal_verify_xml_rpc_signature() {
5615
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5616
	}
5617
5618
	/**
5619
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5620
	 *
5621
	 * @deprecated since 7.7.0
5622
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5623
	 *
5624
	 * @param \WP_User|mixed $user     User object if authenticated.
5625
	 * @param string         $username Username.
5626
	 * @param string         $password Password string.
5627
	 * @return \WP_User|mixed Authenticated user or error.
5628
	 */
5629 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5630
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5631
5632
		if ( ! $this->connection_manager ) {
5633
			$this->connection_manager = new Connection_Manager();
5634
		}
5635
5636
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5637
	}
5638
5639
	/**
5640
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5641
	 * Uses the existing XMLRPC request signing implementation.
5642
	 *
5643
	 * @deprecated since 8.9.0
5644
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5645
	 */
5646
	function wp_rest_authenticate( $user ) {
5647
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5648
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5649
	}
5650
5651
	/**
5652
	 * Report authentication status to the WP REST API.
5653
	 *
5654
	 * @deprecated since 8.9.0
5655
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5656
	 *
5657
	 * @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...
5658
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5659
	 */
5660
	public function wp_rest_authentication_errors( $value ) {
5661
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5662
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5663
	}
5664
5665
	/**
5666
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5667
	 * Capture it here so we can verify the signature later.
5668
	 *
5669
	 * @deprecated since 7.7.0
5670
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5671
	 *
5672
	 * @param array $methods XMLRPC methods.
5673
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5674
	 */
5675 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5676
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5677
5678
		if ( ! $this->connection_manager ) {
5679
			$this->connection_manager = new Connection_Manager();
5680
		}
5681
5682
		return $this->connection_manager->xmlrpc_methods( $methods );
5683
	}
5684
5685
	/**
5686
	 * Register additional public XMLRPC methods.
5687
	 *
5688
	 * @deprecated since 7.7.0
5689
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5690
	 *
5691
	 * @param array $methods Public XMLRPC methods.
5692
	 * @return array Public XMLRPC methods, with the getOptions one.
5693
	 */
5694 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5695
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5696
5697
		if ( ! $this->connection_manager ) {
5698
			$this->connection_manager = new Connection_Manager();
5699
		}
5700
5701
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5702
	}
5703
5704
	/**
5705
	 * Handles a getOptions XMLRPC method call.
5706
	 *
5707
	 * @deprecated since 7.7.0
5708
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5709
	 *
5710
	 * @param array $args method call arguments.
5711
	 * @return array an amended XMLRPC server options array.
5712
	 */
5713 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5714
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5715
5716
		if ( ! $this->connection_manager ) {
5717
			$this->connection_manager = new Connection_Manager();
5718
		}
5719
5720
		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...
5721
	}
5722
5723
	/**
5724
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5725
	 *
5726
	 * @deprecated since 7.7.0
5727
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5728
	 *
5729
	 * @param array $options Standard Core options.
5730
	 * @return array Amended options.
5731
	 */
5732 View Code Duplication
	public function xmlrpc_options( $options ) {
5733
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5734
5735
		if ( ! $this->connection_manager ) {
5736
			$this->connection_manager = new Connection_Manager();
5737
		}
5738
5739
		return $this->connection_manager->xmlrpc_options( $options );
5740
	}
5741
5742
	/**
5743
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5744
	 * SET: state( $key, $value );
5745
	 * GET: $value = state( $key );
5746
	 *
5747
	 * @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...
5748
	 * @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...
5749
	 * @param bool   $restate private
5750
	 */
5751
	public static function state( $key = null, $value = null, $restate = false ) {
5752
		static $state = array();
5753
		static $path, $domain;
5754
		if ( ! isset( $path ) ) {
5755
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5756
			$admin_url = self::admin_url();
5757
			$bits      = wp_parse_url( $admin_url );
5758
5759
			if ( is_array( $bits ) ) {
5760
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5761
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5762
			} else {
5763
				$path = $domain = null;
5764
			}
5765
		}
5766
5767
		// Extract state from cookies and delete cookies
5768
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5769
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5770
			unset( $_COOKIE['jetpackState'] );
5771
			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...
5772
				if ( strlen( $v ) ) {
5773
					$state[ $k ] = $v;
5774
				}
5775
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5776
			}
5777
		}
5778
5779
		if ( $restate ) {
5780
			foreach ( $state as $k => $v ) {
5781
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5782
			}
5783
			return;
5784
		}
5785
5786
		// Get a state variable.
5787
		if ( isset( $key ) && ! isset( $value ) ) {
5788
			if ( array_key_exists( $key, $state ) ) {
5789
				return $state[ $key ];
5790
			}
5791
			return null;
5792
		}
5793
5794
		// Set a state variable.
5795
		if ( isset( $key ) && isset( $value ) ) {
5796
			if ( is_array( $value ) && isset( $value[0] ) ) {
5797
				$value = $value[0];
5798
			}
5799
			$state[ $key ] = $value;
5800
			if ( ! headers_sent() ) {
5801
				if ( self::should_set_cookie( $key ) ) {
5802
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5803
				}
5804
			}
5805
		}
5806
	}
5807
5808
	public static function restate() {
5809
		self::state( null, null, true );
5810
	}
5811
5812
	/**
5813
	 * Determines whether the jetpackState[$key] value should be added to the
5814
	 * cookie.
5815
	 *
5816
	 * @param string $key The state key.
5817
	 *
5818
	 * @return boolean Whether the value should be added to the cookie.
5819
	 */
5820
	public static function should_set_cookie( $key ) {
5821
		global $current_screen;
5822
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5823
5824
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5825
			return false;
5826
		}
5827
5828
		return true;
5829
	}
5830
5831
	public static function check_privacy( $file ) {
5832
		static $is_site_publicly_accessible = null;
5833
5834
		if ( is_null( $is_site_publicly_accessible ) ) {
5835
			$is_site_publicly_accessible = false;
5836
5837
			$rpc = new Jetpack_IXR_Client();
5838
5839
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5840
			if ( $success ) {
5841
				$response = $rpc->getResponse();
5842
				if ( $response ) {
5843
					$is_site_publicly_accessible = true;
5844
				}
5845
			}
5846
5847
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5848
		}
5849
5850
		if ( $is_site_publicly_accessible ) {
5851
			return;
5852
		}
5853
5854
		$module_slug = self::get_module_slug( $file );
5855
5856
		$privacy_checks = self::state( 'privacy_checks' );
5857
		if ( ! $privacy_checks ) {
5858
			$privacy_checks = $module_slug;
5859
		} else {
5860
			$privacy_checks .= ",$module_slug";
5861
		}
5862
5863
		self::state( 'privacy_checks', $privacy_checks );
5864
	}
5865
5866
	/**
5867
	 * Helper method for multicall XMLRPC.
5868
	 *
5869
	 * @deprecated since 8.9.0
5870
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5871
	 *
5872
	 * @param ...$args Args for the async_call.
5873
	 */
5874
	public static function xmlrpc_async_call( ...$args ) {
5875
5876
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5877
5878
		global $blog_id;
5879
		static $clients = array();
5880
5881
		$client_blog_id = is_multisite() ? $blog_id : 0;
5882
5883
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5884
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5885
			if ( function_exists( 'ignore_user_abort' ) ) {
5886
				ignore_user_abort( true );
5887
			}
5888
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5889
		}
5890
5891
		if ( ! empty( $args[0] ) ) {
5892
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5893
		} elseif ( is_multisite() ) {
5894
			foreach ( $clients as $client_blog_id => $client ) {
5895
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5896
					continue;
5897
				}
5898
5899
				$switch_success = switch_to_blog( $client_blog_id, true );
5900
				if ( ! $switch_success ) {
5901
					continue;
5902
				}
5903
5904
				flush();
5905
				$client->query();
5906
5907
				restore_current_blog();
5908
			}
5909
		} else {
5910
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5911
				flush();
5912
				$clients[0]->query();
5913
			}
5914
		}
5915
	}
5916
5917
	/**
5918
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5919
	 *
5920
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5921
	 *
5922
	 * @param string $url WordPress.com static resource URL.
5923
	 */
5924
	public static function staticize_subdomain( $url ) {
5925
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5926
		return Assets::staticize_subdomain( $url );
5927
	}
5928
5929
	/* JSON API Authorization */
5930
5931
	/**
5932
	 * Handles the login action for Authorizing the JSON API
5933
	 */
5934
	function login_form_json_api_authorization() {
5935
		$this->verify_json_api_authorization_request();
5936
5937
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5938
5939
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5940
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5941
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5942
	}
5943
5944
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5945
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5946
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5947
			return $url;
5948
		}
5949
5950
		$parsed_url = wp_parse_url( $url );
5951
		$url        = strtok( $url, '?' );
5952
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5953
		if ( ! empty( $parsed_url['query'] ) ) {
5954
			$url .= "&{$parsed_url['query']}";
5955
		}
5956
5957
		return $url;
5958
	}
5959
5960
	// Make sure the POSTed request is handled by the same action
5961
	function preserve_action_in_login_form_for_json_api_authorization() {
5962
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5963
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5964
	}
5965
5966
	// If someone logs in to approve API access, store the Access Code in usermeta
5967
	function store_json_api_authorization_token( $user_login, $user ) {
5968
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5969
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5970
		$token = wp_generate_password( 32, false );
5971
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5972
	}
5973
5974
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5975
	function allow_wpcom_public_api_domain( $domains ) {
5976
		$domains[] = 'public-api.wordpress.com';
5977
		return $domains;
5978
	}
5979
5980
	static function is_redirect_encoded( $redirect_url ) {
5981
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5982
	}
5983
5984
	// Add all wordpress.com environments to the safe redirect allowed list.
5985
	function allow_wpcom_environments( $domains ) {
5986
		$domains[] = 'wordpress.com';
5987
		$domains[] = 'wpcalypso.wordpress.com';
5988
		$domains[] = 'horizon.wordpress.com';
5989
		$domains[] = 'calypso.localhost';
5990
		return $domains;
5991
	}
5992
5993
	// Add the Access Code details to the public-api.wordpress.com redirect
5994
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5995
		return add_query_arg(
5996
			urlencode_deep(
5997
				array(
5998
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5999
					'jetpack-user-id' => (int) $user->ID,
6000
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6001
				)
6002
			),
6003
			$redirect_to
6004
		);
6005
	}
6006
6007
	/**
6008
	 * Verifies the request by checking the signature
6009
	 *
6010
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6011
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6012
	 *
6013
	 * @param null|array $environment
6014
	 */
6015
	function verify_json_api_authorization_request( $environment = null ) {
6016
		$environment = is_null( $environment )
6017
			? $_REQUEST
6018
			: $environment;
6019
6020
		//phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
6021
		list( $env_token, $env_version, $env_user_id ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $env_version is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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