Completed
Push — add/nonce-removal ( 55b081...734151 )
by
unknown
36:14 queued 27:38
created

class.jetpack.php (83 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
use Automattic\Jetpack\Assets;
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Config;
5
use Automattic\Jetpack\Connection\Client;
6
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7
use Automattic\Jetpack\Connection\Nonce_Handler;
8
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
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\Constants;
12
use Automattic\Jetpack\Partner;
13
use Automattic\Jetpack\Roles;
14
use Automattic\Jetpack\Status;
15
use Automattic\Jetpack\Sync\Functions;
16
use Automattic\Jetpack\Sync\Health;
17
use Automattic\Jetpack\Sync\Sender;
18
use Automattic\Jetpack\Sync\Users;
19
use Automattic\Jetpack\Terms_Of_Service;
20
use Automattic\Jetpack\Tracking;
21
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
22
use Automattic\Jetpack\Redirect;
23
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
24
25
/*
26
Options:
27
jetpack_options (array)
28
	An array of options.
29
	@see Jetpack_Options::get_option_names()
30
31
jetpack_register (string)
32
	Temporary verification secrets.
33
34
jetpack_activated (int)
35
	1: the plugin was activated normally
36
	2: the plugin was activated on this site because of a network-wide activation
37
	3: the plugin was auto-installed
38
	4: the plugin was manually disconnected (but is still installed)
39
40
jetpack_active_modules (array)
41
	Array of active module slugs.
42
43
jetpack_do_activate (bool)
44
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
45
*/
46
47
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
48
49
class Jetpack {
50
	public $xmlrpc_server = null;
51
52
	/**
53
	 * @var array The handles of styles that are concatenated into jetpack.css.
54
	 *
55
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
56
	 */
57
	public $concatenated_style_handles = array(
58
		'jetpack-carousel',
59
		'grunion.css',
60
		'the-neverending-homepage',
61
		'jetpack_likes',
62
		'jetpack_related-posts',
63
		'sharedaddy',
64
		'jetpack-slideshow',
65
		'presentations',
66
		'quiz',
67
		'jetpack-subscriptions',
68
		'jetpack-responsive-videos-style',
69
		'jetpack-social-menu',
70
		'tiled-gallery',
71
		'jetpack_display_posts_widget',
72
		'gravatar-profile-widget',
73
		'goodreads-widget',
74
		'jetpack_social_media_icons_widget',
75
		'jetpack-top-posts-widget',
76
		'jetpack_image_widget',
77
		'jetpack-my-community-widget',
78
		'jetpack-authors-widget',
79
		'wordads',
80
		'eu-cookie-law-style',
81
		'flickr-widget-style',
82
		'jetpack-search-widget',
83
		'jetpack-simple-payments-widget-style',
84
		'jetpack-widget-social-icons-styles',
85
		'wpcom_instagram_widget',
86
	);
87
88
	/**
89
	 * Contains all assets that have had their URL rewritten to minified versions.
90
	 *
91
	 * @var array
92
	 */
93
	static $min_assets = array();
94
95
	public $plugins_to_deactivate = array(
96
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
97
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
98
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
99
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
100
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
101
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
102
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
103
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
104
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
105
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
106
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
107
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
108
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
109
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
110
	);
111
112
	/**
113
	 * Map of roles we care about, and their corresponding minimum capabilities.
114
	 *
115
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
116
	 *
117
	 * @access public
118
	 * @static
119
	 *
120
	 * @var array
121
	 */
122
	public static $capability_translations = array(
123
		'administrator' => 'manage_options',
124
		'editor'        => 'edit_others_posts',
125
		'author'        => 'publish_posts',
126
		'contributor'   => 'edit_posts',
127
		'subscriber'    => 'read',
128
	);
129
130
	/**
131
	 * Map of modules that have conflicts with plugins and should not be auto-activated
132
	 * if the plugins are active.  Used by filter_default_modules
133
	 *
134
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
135
	 * change `module-slug` and add this to your plugin:
136
	 *
137
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
138
	 * function my_jetpack_get_default_modules( $modules ) {
139
	 *     return array_diff( $modules, array( 'module-slug' ) );
140
	 * }
141
	 *
142
	 * @var array
143
	 */
144
	private $conflicting_plugins = array(
145
		'comments'           => array(
146
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
147
			'Disqus'                         => 'disqus-comment-system/disqus.php',
148
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
149
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
150
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
151
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
152
		),
153
		'comment-likes'      => array(
154
			'Epoch' => 'epoch/plugincore.php',
155
		),
156
		'contact-form'       => array(
157
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
158
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
159
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
160
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
161
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
162
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
163
		),
164
		'latex'              => array(
165
			'LaTeX for WordPress'     => 'latex/latex.php',
166
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
167
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
168
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
169
			'Enable Latex'            => 'enable-latex/enable-latex.php',
170
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
171
		),
172
		'protect'            => array(
173
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
174
			'Captcha'                           => 'captcha/captcha.php',
175
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
176
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
177
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
178
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
179
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
180
			'Security-protection'               => 'security-protection/security-protection.php',
181
			'Login Security'                    => 'login-security/login-security.php',
182
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
183
			'Wordfence Security'                => 'wordfence/wordfence.php',
184
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
185
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
186
		),
187
		'random-redirect'    => array(
188
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
189
		),
190
		'related-posts'      => array(
191
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
192
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
193
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
194
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
195
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
196
			'outbrain'                    => 'outbrain/outbrain.php',
197
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
198
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
199
		),
200
		'sharedaddy'         => array(
201
			'AddThis'     => 'addthis/addthis_social_widget.php',
202
			'Add To Any'  => 'add-to-any/add-to-any.php',
203
			'ShareThis'   => 'share-this/sharethis.php',
204
			'Shareaholic' => 'shareaholic/shareaholic.php',
205
		),
206
		'seo-tools'          => array(
207
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
208
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
209
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
210
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
211
			'The SEO Framework'              => 'autodescription/autodescription.php',
212
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
213
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
214
		),
215
		'verification-tools' => array(
216
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
217
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
218
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
219
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
220
			'The SEO Framework'              => 'autodescription/autodescription.php',
221
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
222
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
223
		),
224
		'widget-visibility'  => array(
225
			'Widget Logic'    => 'widget-logic/widget_logic.php',
226
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
227
		),
228
		'sitemaps'           => array(
229
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
230
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
231
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
232
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
233
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
234
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
235
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
236
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
237
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
238
			'The SEO Framework'                    => 'autodescription/autodescription.php',
239
			'Sitemap'                              => 'sitemap/sitemap.php',
240
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
241
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
242
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
243
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
244
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
245
			'Slim SEO'                             => 'slim-seo/slim-seo.php',
246
		),
247
		'lazy-images'        => array(
248
			'Lazy Load'              => 'lazy-load/lazy-load.php',
249
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
250
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
251
		),
252
	);
253
254
	/**
255
	 * Plugins for which we turn off our Facebook OG Tags implementation.
256
	 *
257
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
258
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
259
	 *
260
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
261
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
262
	 */
263
	private $open_graph_conflicting_plugins = array(
264
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
265
		// 2 Click Social Media Buttons
266
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
267
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
268
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
269
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
270
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
271
		// Open Graph Meta Tags by Heateor
272
		'facebook/facebook.php',                                 // Facebook (official plugin)
273
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
274
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
275
		// Facebook Featured Image & OG Meta Tags
276
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
277
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
278
		// Facebook Open Graph Meta Tags for WordPress
279
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
280
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
281
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
282
		// Fedmich's Facebook Open Graph Meta
283
		'network-publisher/networkpub.php',                      // Network Publisher
284
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
285
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
286
		// NextScripts SNAP
287
		'og-tags/og-tags.php',                                   // OG Tags
288
		'opengraph/opengraph.php',                               // Open Graph
289
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
290
		// Open Graph Protocol Framework
291
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
292
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
293
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
294
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
295
		'sharepress/sharepress.php',                             // SharePress
296
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
297
		'social-discussions/social-discussions.php',             // Social Discussions
298
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
299
		'socialize/socialize.php',                               // Socialize
300
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
301
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
302
		// Tweet, Like, Google +1 and Share
303
		'wordbooker/wordbooker.php',                             // Wordbooker
304
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
305
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
306
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
307
		// WP Facebook Like Send & Open Graph Meta
308
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
309
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
310
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
311
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
312
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
313
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
314
		'slim-seo/slim-seo.php',                                 // Slim SEO
315
	);
316
317
	/**
318
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
319
	 */
320
	private $twitter_cards_conflicting_plugins = array(
321
		// 'twitter/twitter.php',                       // The official one handles this on its own.
322
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
323
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
324
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
325
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
326
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
327
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
328
		'twitter-cards/twitter-cards.php',           // Twitter Cards
329
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
330
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
331
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
332
		'seo-by-rank-math/rank-math.php',            // Rank Math.
333
		'slim-seo/slim-seo.php',                     // Slim SEO
334
	);
335
336
	/**
337
	 * Message to display in admin_notice
338
	 *
339
	 * @var string
340
	 */
341
	public $message = '';
342
343
	/**
344
	 * Error to display in admin_notice
345
	 *
346
	 * @var string
347
	 */
348
	public $error = '';
349
350
	/**
351
	 * Modules that need more privacy description.
352
	 *
353
	 * @var string
354
	 */
355
	public $privacy_checks = '';
356
357
	/**
358
	 * Stats to record once the page loads
359
	 *
360
	 * @var array
361
	 */
362
	public $stats = array();
363
364
	/**
365
	 * Jetpack_Sync object
366
	 */
367
	public $sync;
368
369
	/**
370
	 * Verified data for JSON authorization request
371
	 */
372
	public $json_api_authorization_request = array();
373
374
	/**
375
	 * @var Automattic\Jetpack\Connection\Manager
376
	 */
377
	protected $connection_manager;
378
379
	/**
380
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
381
	 */
382
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
383
384
	/**
385
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
386
	 *
387
	 * @var Automattic\Jetpack\A8c_Mc_Stats
388
	 */
389
	public $a8c_mc_stats_instance;
390
391
	/**
392
	 * Constant for login redirect key.
393
	 *
394
	 * @var string
395
	 * @since 8.4.0
396
	 */
397
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
398
399
	/**
400
	 * Holds the singleton instance of this class
401
	 *
402
	 * @since 2.3.3
403
	 * @var Jetpack
404
	 */
405
	static $instance = false;
406
407
	/**
408
	 * Singleton
409
	 *
410
	 * @static
411
	 */
412
	public static function init() {
413
		if ( ! self::$instance ) {
414
			self::$instance = new Jetpack();
415
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
416
		}
417
418
		return self::$instance;
419
	}
420
421
	/**
422
	 * Must never be called statically
423
	 */
424
	function plugin_upgrade() {
425
		if ( self::is_active() ) {
426
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
427
			if ( JETPACK__VERSION != $version ) {
428
				// Prevent multiple upgrades at once - only a single process should trigger
429
				// an upgrade to avoid stampedes
430
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
431
					return;
432
				}
433
434
				// Set a short lock to prevent multiple instances of the upgrade
435
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
436
437
				// check which active modules actually exist and remove others from active_modules list
438
				$unfiltered_modules = self::get_active_modules();
439
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
440
				if ( array_diff( $unfiltered_modules, $modules ) ) {
441
					self::update_active_modules( $modules );
442
				}
443
444
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
445
446
				// Upgrade to 4.3.0
447
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
448
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
449
				}
450
451
				// Make sure Markdown for posts gets turned back on
452
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
453
					update_option( 'wpcom_publish_posts_with_markdown', true );
454
				}
455
456
				/*
457
				 * Minileven deprecation. 8.3.0.
458
				 * Only delete options if not using
459
				 * the replacement standalone Minileven plugin.
460
				 */
461
				if (
462
					! self::is_plugin_active( 'minileven-master/minileven.php' )
463
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
464
				) {
465
					if ( get_option( 'wp_mobile_custom_css' ) ) {
466
						delete_option( 'wp_mobile_custom_css' );
467
					}
468
					if ( get_option( 'wp_mobile_excerpt' ) ) {
469
						delete_option( 'wp_mobile_excerpt' );
470
					}
471
					if ( get_option( 'wp_mobile_featured_images' ) ) {
472
						delete_option( 'wp_mobile_featured_images' );
473
					}
474
					if ( get_option( 'wp_mobile_app_promos' ) ) {
475
						delete_option( 'wp_mobile_app_promos' );
476
					}
477
				}
478
479
				// Upgrade to 8.4.0.
480
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
481
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
482
				}
483
484
				// Update to 8.8.x (WordPress 5.5 Compatibility).
485
				if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
486
					$updated = update_site_option(
487
						'auto_update_plugins',
488
						array_unique(
489
							array_merge(
490
								(array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
491
								(array) get_site_option( 'auto_update_plugins', array() )
492
							)
493
						)
494
					);
495
496
					if ( $updated ) {
497
						Jetpack_Options::delete_option( 'autoupdate_plugins' );
498
					} // Should we have some type of fallback if something fails here?
499
				}
500
501
				if ( did_action( 'wp_loaded' ) ) {
502
					self::upgrade_on_load();
503
				} else {
504
					add_action(
505
						'wp_loaded',
506
						array( __CLASS__, 'upgrade_on_load' )
507
					);
508
				}
509
510
				// Upgrade to Jetpack 9.0.0, cleaning up nonces during runtime.
511
				wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
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
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( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
679
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', '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_wizard_banner', array( 'Jetpack_Wizard_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( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
713
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
714
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
715
716
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
717
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
718
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
719
720
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
721
722
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
723
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
724
725
		// A filter to control all just in time messages
726
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
727
728
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
729
730
		/*
731
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
732
		 * We should make sure to only do this for front end links.
733
		 */
734
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
735
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
736
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
737
738
			/*
739
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
740
			 * so they point moderation links on emails to Calypso.
741
			 */
742
			jetpack_require_lib( 'functions.wp-notify' );
743
		}
744
745
		add_action(
746
			'plugins_loaded',
747
			function() {
748
				if ( User_Agent_Info::is_mobile_app() ) {
749
					add_filter( 'get_edit_post_link', '__return_empty_string' );
750
				}
751
			}
752
		);
753
754
		// Update the site's Jetpack plan and products from API on heartbeats.
755
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
756
757
		/**
758
		 * This is the hack to concatenate all css files into one.
759
		 * For description and reasoning see the implode_frontend_css method.
760
		 *
761
		 * Super late priority so we catch all the registered styles.
762
		 */
763
		if ( ! is_admin() ) {
764
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
765
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
766
		}
767
768
		/**
769
		 * These are sync actions that we need to keep track of for jitms
770
		 */
771
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
772
773
		// Actually push the stats on shutdown.
774
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
775
			add_action( 'shutdown', array( $this, 'push_stats' ) );
776
		}
777
778
		// Actions for Manager::authorize().
779
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
780
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
781
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
782
783
		// Filters for the Manager::get_token() urls and request body.
784
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
785
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
786
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
787
788
		// Actions for successful reconnect.
789
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
790
	}
791
792
	/**
793
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
794
	 * Config object.
795
	 */
796
	public function configure() {
797
		$config = new Config();
798
799
		foreach (
800
			array(
801
				'sync',
802
			)
803
			as $feature
804
		) {
805
			$config->ensure( $feature );
806
		}
807
808
		$config->ensure(
809
			'connection',
810
			array(
811
				'slug' => 'jetpack',
812
				'name' => 'Jetpack',
813
			)
814
		);
815
816
		if ( is_admin() ) {
817
			$config->ensure( 'jitm' );
818
		}
819
820
		if ( ! $this->connection_manager ) {
821
			$this->connection_manager = new Connection_Manager( 'jetpack' );
822
		}
823
824
		/*
825
		 * Load things that should only be in Network Admin.
826
		 *
827
		 * For now blow away everything else until a more full
828
		 * understanding of what is needed at the network level is
829
		 * available
830
		 */
831
		if ( is_multisite() ) {
832
			$network = Jetpack_Network::init();
833
			$network->set_connection( $this->connection_manager );
834
		}
835
836
		if ( $this->connection_manager->is_active() ) {
837
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
838
839
			Jetpack_Heartbeat::init();
840
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
841
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
842
				Jetpack_Search_Performance_Logger::init();
843
			}
844
		}
845
846
		// Initialize remote file upload request handlers.
847
		$this->add_remote_request_handlers();
848
849
		/*
850
		 * Enable enhanced handling of previewing sites in Calypso
851
		 */
852
		if ( self::is_active() ) {
853
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
854
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
855
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
856
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
857
		}
858
859
		if ( ( new Tracking( $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) ) {
0 ignored issues
show
$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...
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...
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...
860
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
861
		} else {
862
			/**
863
			 * Initialize tracking right after the user agrees to the terms of service.
864
			 */
865
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
866
		}
867
	}
868
869
	/**
870
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
871
	 * initialization code.
872
	 *
873
	 * @action plugins_loaded
874
	 */
875
	public function late_initialization() {
876
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
877
878
		Partner::init();
879
880
		/**
881
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
882
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
883
		 *
884
		 * @since 8.1.0
885
		 *
886
		 * @param Jetpack $jetpack the main plugin class object.
887
		 */
888
		do_action( 'jetpack_loaded', $this );
889
890
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
891
	}
892
893
	/**
894
	 * Sets up the XMLRPC request handlers.
895
	 *
896
	 * @deprecated since 7.7.0
897
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
898
	 *
899
	 * @param array                 $request_params Incoming request parameters.
900
	 * @param Boolean               $is_active      Whether the connection is currently active.
901
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
902
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
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...
903
	 */
904 View Code Duplication
	public function setup_xmlrpc_handlers(
905
		$request_params,
906
		$is_active,
907
		$is_signed,
908
		Jetpack_XMLRPC_Server $xmlrpc_server = null
909
	) {
910
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
911
912
		if ( ! $this->connection_manager ) {
913
			$this->connection_manager = new Connection_Manager();
914
		}
915
916
		return $this->connection_manager->setup_xmlrpc_handlers(
917
			$request_params,
918
			$is_active,
919
			$is_signed,
920
			$xmlrpc_server
921
		);
922
	}
923
924
	/**
925
	 * Initialize REST API registration connector.
926
	 *
927
	 * @deprecated since 7.7.0
928
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
929
	 */
930 View Code Duplication
	public function initialize_rest_api_registration_connector() {
931
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
932
933
		if ( ! $this->connection_manager ) {
934
			$this->connection_manager = new Connection_Manager();
935
		}
936
937
		$this->connection_manager->initialize_rest_api_registration_connector();
938
	}
939
940
	/**
941
	 * This is ported over from the manage module, which has been deprecated and baked in here.
942
	 *
943
	 * @param $domains
944
	 */
945
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
946
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
947
	}
948
949
	/**
950
	 * Return $domains, with 'wordpress.com' appended.
951
	 * This is ported over from the manage module, which has been deprecated and baked in here.
952
	 *
953
	 * @param $domains
954
	 * @return array
955
	 */
956
	function allow_wpcom_domain( $domains ) {
957
		if ( empty( $domains ) ) {
958
			$domains = array();
959
		}
960
		$domains[] = 'wordpress.com';
961
		return array_unique( $domains );
962
	}
963
964
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
965
		$post = get_post( $post_id );
966
967
		if ( empty( $post ) ) {
968
			return $default_url;
969
		}
970
971
		$post_type = $post->post_type;
972
973
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
974
		// https://en.support.wordpress.com/custom-post-types/
975
		$allowed_post_types = array(
976
			'post',
977
			'page',
978
			'jetpack-portfolio',
979
			'jetpack-testimonial',
980
		);
981
982
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
983
			return $default_url;
984
		}
985
986
		return Redirect::get_url(
987
			'calypso-edit-' . $post_type,
988
			array(
989
				'path' => $post_id,
990
			)
991
		);
992
	}
993
994
	function point_edit_comment_links_to_calypso( $url ) {
995
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
996
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
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...
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
997
998
		return Redirect::get_url(
999
			'calypso-edit-comment',
1000
			array(
1001
				'path' => $query_args['amp;c'],
1002
			)
1003
		);
1004
1005
	}
1006
1007
	function jetpack_track_last_sync_callback( $params ) {
1008
		/**
1009
		 * Filter to turn off jitm caching
1010
		 *
1011
		 * @since 5.4.0
1012
		 *
1013
		 * @param bool false Whether to cache just in time messages
1014
		 */
1015
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1016
			return $params;
1017
		}
1018
1019
		if ( is_array( $params ) && isset( $params[0] ) ) {
1020
			$option = $params[0];
1021
			if ( 'active_plugins' === $option ) {
1022
				// use the cache if we can, but not terribly important if it gets evicted
1023
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1024
			}
1025
		}
1026
1027
		return $params;
1028
	}
1029
1030
	function jetpack_connection_banner_callback() {
1031
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1032
1033
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1034
		if (
1035
			isset( $_REQUEST['dismissBanner'] ) &&
1036
			! Jetpack_Connection_Banner::force_display()
1037
		) {
1038
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1039
			wp_send_json_success();
1040
		}
1041
1042
		wp_die();
1043
	}
1044
1045
	/**
1046
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1047
	 * Only used in our alternate XML-RPC endpoint, where we want to
1048
	 * ensure that Core and other plugins' methods are not exposed.
1049
	 *
1050
	 * @deprecated since 7.7.0
1051
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1052
	 *
1053
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1054
	 * @return array Filtered $methods
1055
	 */
1056 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1057
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1058
1059
		if ( ! $this->connection_manager ) {
1060
			$this->connection_manager = new Connection_Manager();
1061
		}
1062
1063
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1064
	}
1065
1066
	/**
1067
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1068
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1069
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1070
	 * which is accessible via a different URI. Most of the below is copied directly
1071
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1072
	 *
1073
	 * @deprecated since 7.7.0
1074
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1075
	 */
1076 View Code Duplication
	public function alternate_xmlrpc() {
1077
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1078
1079
		if ( ! $this->connection_manager ) {
1080
			$this->connection_manager = new Connection_Manager();
1081
		}
1082
1083
		$this->connection_manager->alternate_xmlrpc();
1084
	}
1085
1086
	/**
1087
	 * The callback for the JITM ajax requests.
1088
	 *
1089
	 * @deprecated since 7.9.0
1090
	 */
1091
	function jetpack_jitm_ajax_callback() {
1092
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1093
	}
1094
1095
	/**
1096
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1097
	 */
1098
	function push_stats() {
1099
		if ( ! empty( $this->stats ) ) {
1100
			$this->do_stats( 'server_side' );
1101
		}
1102
	}
1103
1104
	/**
1105
	 * Sets the Jetpack custom capabilities.
1106
	 *
1107
	 * @param string[] $caps    Array of the user's capabilities.
1108
	 * @param string   $cap     Capability name.
1109
	 * @param int      $user_id The user ID.
1110
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1111
	 */
1112
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1113
		$is_offline_mode = ( new Status() )->is_offline_mode();
1114
		switch ( $cap ) {
1115
			case 'jetpack_manage_modules':
1116
			case 'jetpack_activate_modules':
1117
			case 'jetpack_deactivate_modules':
1118
				$caps = array( 'manage_options' );
1119
				break;
1120
			case 'jetpack_configure_modules':
1121
				$caps = array( 'manage_options' );
1122
				break;
1123
			case 'jetpack_manage_autoupdates':
1124
				$caps = array(
1125
					'manage_options',
1126
					'update_plugins',
1127
				);
1128
				break;
1129
			case 'jetpack_network_admin_page':
1130
			case 'jetpack_network_settings_page':
1131
				$caps = array( 'manage_network_plugins' );
1132
				break;
1133
			case 'jetpack_network_sites_page':
1134
				$caps = array( 'manage_sites' );
1135
				break;
1136
			case 'jetpack_admin_page':
1137
				if ( $is_offline_mode ) {
1138
					$caps = array( 'manage_options' );
1139
					break;
1140
				} else {
1141
					$caps = array( 'read' );
1142
				}
1143
				break;
1144
		}
1145
		return $caps;
1146
	}
1147
1148
	/**
1149
	 * Require a Jetpack authentication.
1150
	 *
1151
	 * @deprecated since 7.7.0
1152
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1153
	 */
1154 View Code Duplication
	public function require_jetpack_authentication() {
1155
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1156
1157
		if ( ! $this->connection_manager ) {
1158
			$this->connection_manager = new Connection_Manager();
1159
		}
1160
1161
		$this->connection_manager->require_jetpack_authentication();
1162
	}
1163
1164
	/**
1165
	 * Register assets for use in various modules and the Jetpack admin page.
1166
	 *
1167
	 * @uses wp_script_is, wp_register_script, plugins_url
1168
	 * @action wp_loaded
1169
	 * @return null
1170
	 */
1171
	public function register_assets() {
1172 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1173
			wp_register_script(
1174
				'jetpack-gallery-settings',
1175
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1176
				array( 'media-views' ),
1177
				'20121225'
1178
			);
1179
		}
1180
1181
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1182
			wp_register_script(
1183
				'jetpack-twitter-timeline',
1184
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1185
				array( 'jquery' ),
1186
				'4.0.0',
1187
				true
1188
			);
1189
		}
1190
1191
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1192
			wp_register_script(
1193
				'jetpack-facebook-embed',
1194
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1195
				array(),
1196
				null,
1197
				true
1198
			);
1199
1200
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1201
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1202
			if ( ! is_numeric( $fb_app_id ) ) {
1203
				$fb_app_id = '';
1204
			}
1205
			wp_localize_script(
1206
				'jetpack-facebook-embed',
1207
				'jpfbembed',
1208
				array(
1209
					'appid'  => $fb_app_id,
1210
					'locale' => $this->get_locale(),
1211
				)
1212
			);
1213
		}
1214
1215
		/**
1216
		 * As jetpack_register_genericons is by default fired off a hook,
1217
		 * the hook may have already fired by this point.
1218
		 * So, let's just trigger it manually.
1219
		 */
1220
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1221
		jetpack_register_genericons();
1222
1223
		/**
1224
		 * Register the social logos
1225
		 */
1226
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1227
		jetpack_register_social_logos();
1228
1229 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1230
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1231
		}
1232
	}
1233
1234
	/**
1235
	 * Guess locale from language code.
1236
	 *
1237
	 * @param string $lang Language code.
1238
	 * @return string|bool
1239
	 */
1240 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1241
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1242
			return 'en_US';
1243
		}
1244
1245
		if ( ! class_exists( 'GP_Locales' ) ) {
1246
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1247
				return false;
1248
			}
1249
1250
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1251
		}
1252
1253
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1254
			// WP.com: get_locale() returns 'it'
1255
			$locale = GP_Locales::by_slug( $lang );
1256
		} else {
1257
			// Jetpack: get_locale() returns 'it_IT';
1258
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1259
		}
1260
1261
		if ( ! $locale ) {
1262
			return false;
1263
		}
1264
1265
		if ( empty( $locale->facebook_locale ) ) {
1266
			if ( empty( $locale->wp_locale ) ) {
1267
				return false;
1268
			} else {
1269
				// Facebook SDK is smart enough to fall back to en_US if a
1270
				// locale isn't supported. Since supported Facebook locales
1271
				// can fall out of sync, we'll attempt to use the known
1272
				// wp_locale value and rely on said fallback.
1273
				return $locale->wp_locale;
1274
			}
1275
		}
1276
1277
		return $locale->facebook_locale;
1278
	}
1279
1280
	/**
1281
	 * Get the locale.
1282
	 *
1283
	 * @return string|bool
1284
	 */
1285
	function get_locale() {
1286
		$locale = $this->guess_locale_from_lang( get_locale() );
1287
1288
		if ( ! $locale ) {
1289
			$locale = 'en_US';
1290
		}
1291
1292
		return $locale;
1293
	}
1294
1295
	/**
1296
	 * Return the network_site_url so that .com knows what network this site is a part of.
1297
	 *
1298
	 * @param  bool $option
1299
	 * @return string
1300
	 */
1301
	public function jetpack_main_network_site_option( $option ) {
1302
		return network_site_url();
1303
	}
1304
	/**
1305
	 * Network Name.
1306
	 */
1307
	static function network_name( $option = null ) {
1308
		global $current_site;
1309
		return $current_site->site_name;
1310
	}
1311
	/**
1312
	 * Does the network allow new user and site registrations.
1313
	 *
1314
	 * @return string
1315
	 */
1316
	static function network_allow_new_registrations( $option = null ) {
1317
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1318
	}
1319
	/**
1320
	 * Does the network allow admins to add new users.
1321
	 *
1322
	 * @return boolian
1323
	 */
1324
	static function network_add_new_users( $option = null ) {
1325
		return (bool) get_site_option( 'add_new_users' );
1326
	}
1327
	/**
1328
	 * File upload psace left per site in MB.
1329
	 *  -1 means NO LIMIT.
1330
	 *
1331
	 * @return number
1332
	 */
1333
	static function network_site_upload_space( $option = null ) {
1334
		// value in MB
1335
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1336
	}
1337
1338
	/**
1339
	 * Network allowed file types.
1340
	 *
1341
	 * @return string
1342
	 */
1343
	static function network_upload_file_types( $option = null ) {
1344
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1345
	}
1346
1347
	/**
1348
	 * Maximum file upload size set by the network.
1349
	 *
1350
	 * @return number
1351
	 */
1352
	static function network_max_upload_file_size( $option = null ) {
1353
		// value in KB
1354
		return get_site_option( 'fileupload_maxk', 300 );
1355
	}
1356
1357
	/**
1358
	 * Lets us know if a site allows admins to manage the network.
1359
	 *
1360
	 * @return array
1361
	 */
1362
	static function network_enable_administration_menus( $option = null ) {
1363
		return get_site_option( 'menu_items' );
1364
	}
1365
1366
	/**
1367
	 * If a user has been promoted to or demoted from admin, we need to clear the
1368
	 * jetpack_other_linked_admins transient.
1369
	 *
1370
	 * @since 4.3.2
1371
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1372
	 *
1373
	 * @param int    $user_id   The user ID whose role changed.
1374
	 * @param string $role      The new role.
1375
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
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...
1376
	 */
1377
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1378
		if ( 'administrator' == $role
1379
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1380
			|| is_null( $old_roles )
1381
		) {
1382
			delete_transient( 'jetpack_other_linked_admins' );
1383
		}
1384
	}
1385
1386
	/**
1387
	 * Checks to see if there are any other users available to become primary
1388
	 * Users must both:
1389
	 * - Be linked to wpcom
1390
	 * - Be an admin
1391
	 *
1392
	 * @return mixed False if no other users are linked, Int if there are.
1393
	 */
1394
	static function get_other_linked_admins() {
1395
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1396
1397
		if ( false === $other_linked_users ) {
1398
			$admins = get_users( array( 'role' => 'administrator' ) );
1399
			if ( count( $admins ) > 1 ) {
1400
				$available = array();
1401
				foreach ( $admins as $admin ) {
1402
					if ( self::is_user_connected( $admin->ID ) ) {
1403
						$available[] = $admin->ID;
1404
					}
1405
				}
1406
1407
				$count_connected_admins = count( $available );
1408
				if ( count( $available ) > 1 ) {
1409
					$other_linked_users = $count_connected_admins;
1410
				} else {
1411
					$other_linked_users = 0;
1412
				}
1413
			} else {
1414
				$other_linked_users = 0;
1415
			}
1416
1417
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1418
		}
1419
1420
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1421
	}
1422
1423
	/**
1424
	 * Return whether we are dealing with a multi network setup or not.
1425
	 * The reason we are type casting this is because we want to avoid the situation where
1426
	 * the result is false since when is_main_network_option return false it cases
1427
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1428
	 * database which could be set to anything as opposed to what this function returns.
1429
	 *
1430
	 * @param  bool $option
1431
	 *
1432
	 * @return boolean
1433
	 */
1434
	public function is_main_network_option( $option ) {
1435
		// return '1' or ''
1436
		return (string) (bool) self::is_multi_network();
1437
	}
1438
1439
	/**
1440
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1441
	 *
1442
	 * @param  string $option
1443
	 * @return boolean
1444
	 */
1445
	public function is_multisite( $option ) {
1446
		return (string) (bool) is_multisite();
1447
	}
1448
1449
	/**
1450
	 * Implemented since there is no core is multi network function
1451
	 * Right now there is no way to tell if we which network is the dominant network on the system
1452
	 *
1453
	 * @since  3.3
1454
	 * @return boolean
1455
	 */
1456 View Code Duplication
	public static function is_multi_network() {
1457
		global  $wpdb;
1458
1459
		// if we don't have a multi site setup no need to do any more
1460
		if ( ! is_multisite() ) {
1461
			return false;
1462
		}
1463
1464
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1465
		if ( $num_sites > 1 ) {
1466
			return true;
1467
		} else {
1468
			return false;
1469
		}
1470
	}
1471
1472
	/**
1473
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1474
	 *
1475
	 * @return null
1476
	 */
1477
	function update_jetpack_main_network_site_option() {
1478
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1479
	}
1480
	/**
1481
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1482
	 */
1483
	function update_jetpack_network_settings() {
1484
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1485
		// Only sync this info for the main network site.
1486
	}
1487
1488
	/**
1489
	 * Get back if the current site is single user site.
1490
	 *
1491
	 * @return bool
1492
	 */
1493 View Code Duplication
	public static function is_single_user_site() {
1494
		global $wpdb;
1495
1496
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1497
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1498
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1499
		}
1500
		return 1 === (int) $some_users;
1501
	}
1502
1503
	/**
1504
	 * Returns true if the site has file write access false otherwise.
1505
	 *
1506
	 * @return string ( '1' | '0' )
1507
	 **/
1508
	public static function file_system_write_access() {
1509
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1510
			require_once ABSPATH . 'wp-admin/includes/file.php';
1511
		}
1512
1513
		require_once ABSPATH . 'wp-admin/includes/template.php';
1514
1515
		$filesystem_method = get_filesystem_method();
1516
		if ( $filesystem_method === 'direct' ) {
1517
			return 1;
1518
		}
1519
1520
		ob_start();
1521
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1522
		ob_end_clean();
1523
		if ( $filesystem_credentials_are_stored ) {
1524
			return 1;
1525
		}
1526
		return 0;
1527
	}
1528
1529
	/**
1530
	 * Finds out if a site is using a version control system.
1531
	 *
1532
	 * @return string ( '1' | '0' )
1533
	 **/
1534
	public static function is_version_controlled() {
1535
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1536
		return (string) (int) Functions::is_version_controlled();
1537
	}
1538
1539
	/**
1540
	 * Determines whether the current theme supports featured images or not.
1541
	 *
1542
	 * @return string ( '1' | '0' )
1543
	 */
1544
	public static function featured_images_enabled() {
1545
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1546
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1547
	}
1548
1549
	/**
1550
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1551
	 *
1552
	 * @deprecated 4.7 use get_avatar_url instead.
1553
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1554
	 * @param int               $size Size of the avatar image
1555
	 * @param string            $default URL to a default image to use if no avatar is available
1556
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1557
	 *
1558
	 * @return array
1559
	 */
1560
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1561
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1562
		return get_avatar_url(
1563
			$id_or_email,
1564
			array(
1565
				'size'          => $size,
1566
				'default'       => $default,
1567
				'force_default' => $force_display,
1568
			)
1569
		);
1570
	}
1571
1572
	/**
1573
	 * jetpack_updates is saved in the following schema:
1574
	 *
1575
	 * array (
1576
	 *      'plugins'                       => (int) Number of plugin updates available.
1577
	 *      'themes'                        => (int) Number of theme updates available.
1578
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1579
	 *      'translations'                  => (int) Number of translation updates available.
1580
	 *      'total'                         => (int) Total of all available updates.
1581
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1582
	 * )
1583
	 *
1584
	 * @return array
1585
	 */
1586
	public static function get_updates() {
1587
		$update_data = wp_get_update_data();
1588
1589
		// Stores the individual update counts as well as the total count.
1590
		if ( isset( $update_data['counts'] ) ) {
1591
			$updates = $update_data['counts'];
1592
		}
1593
1594
		// If we need to update WordPress core, let's find the latest version number.
1595 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1596
			$cur = get_preferred_from_update_core();
1597
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1598
				$updates['wp_update_version'] = $cur->current;
1599
			}
1600
		}
1601
		return isset( $updates ) ? $updates : array();
1602
	}
1603
1604
	public static function get_update_details() {
1605
		$update_details = array(
1606
			'update_core'    => get_site_transient( 'update_core' ),
1607
			'update_plugins' => get_site_transient( 'update_plugins' ),
1608
			'update_themes'  => get_site_transient( 'update_themes' ),
1609
		);
1610
		return $update_details;
1611
	}
1612
1613
	public static function refresh_update_data() {
1614
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1615
1616
	}
1617
1618
	public static function refresh_theme_data() {
1619
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1620
	}
1621
1622
	/**
1623
	 * Is Jetpack active?
1624
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1625
	 *
1626
	 * @return bool
1627
	 */
1628
	public static function is_active() {
1629
		return self::connection()->is_active();
1630
	}
1631
1632
	/**
1633
	 * Make an API call to WordPress.com for plan status
1634
	 *
1635
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1636
	 *
1637
	 * @return bool True if plan is updated, false if no update
1638
	 */
1639
	public static function refresh_active_plan_from_wpcom() {
1640
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1641
		return Jetpack_Plan::refresh_from_wpcom();
1642
	}
1643
1644
	/**
1645
	 * Get the plan that this Jetpack site is currently using
1646
	 *
1647
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1648
	 * @return array Active Jetpack plan details.
1649
	 */
1650
	public static function get_active_plan() {
1651
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1652
		return Jetpack_Plan::get();
1653
	}
1654
1655
	/**
1656
	 * Determine whether the active plan supports a particular feature
1657
	 *
1658
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1659
	 * @return bool True if plan supports feature, false if not.
1660
	 */
1661
	public static function active_plan_supports( $feature ) {
1662
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1663
		return Jetpack_Plan::supports( $feature );
1664
	}
1665
1666
	/**
1667
	 * Deprecated: Is Jetpack in development (offline) mode?
1668
	 *
1669
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1670
	 * and themes still use it, and we do not want to flood them with notices.
1671
	 *
1672
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1673
	 *
1674
	 * @deprecated since 8.0.
1675
	 */
1676
	public static function is_development_mode() {
1677
		return ( new Status() )->is_offline_mode();
1678
	}
1679
1680
	/**
1681
	 * Whether the site is currently onboarding or not.
1682
	 * A site is considered as being onboarded if it currently has an onboarding token.
1683
	 *
1684
	 * @since 5.8
1685
	 *
1686
	 * @access public
1687
	 * @static
1688
	 *
1689
	 * @return bool True if the site is currently onboarding, false otherwise
1690
	 */
1691
	public static function is_onboarding() {
1692
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1693
	}
1694
1695
	/**
1696
	 * Determines reason for Jetpack offline mode.
1697
	 */
1698
	public static function development_mode_trigger_text() {
1699
		$status = new Status();
1700
1701
		if ( ! $status->is_offline_mode() ) {
1702
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1703
		}
1704
1705
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1706
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1707
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1708
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1709
		} elseif ( $status->is_local_site() ) {
1710
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1711
			/** This filter is documented in packages/status/src/class-status.php */
1712
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1713
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1714
		} else {
1715
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1716
		}
1717
1718
		return $notice;
1719
1720
	}
1721
	/**
1722
	 * Get Jetpack offline mode notice text and notice class.
1723
	 *
1724
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1725
	 */
1726
	public static function show_development_mode_notice() {
1727 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1728
			$notice = sprintf(
1729
				/* translators: %s is a URL */
1730
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1731
				Redirect::get_url( 'jetpack-support-development-mode' )
1732
			);
1733
1734
			$notice .= ' ' . self::development_mode_trigger_text();
1735
1736
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1737
		}
1738
1739
		// Throw up a notice if using a development version and as for feedback.
1740
		if ( self::is_development_version() ) {
1741
			/* translators: %s is a URL */
1742
			$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' ) );
1743
1744
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1745
		}
1746
		// Throw up a notice if using staging mode
1747 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1748
			/* translators: %s is a URL */
1749
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1750
1751
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1752
		}
1753
	}
1754
1755
	/**
1756
	 * Whether Jetpack's version maps to a public release, or a development version.
1757
	 */
1758
	public static function is_development_version() {
1759
		/**
1760
		 * Allows filtering whether this is a development version of Jetpack.
1761
		 *
1762
		 * This filter is especially useful for tests.
1763
		 *
1764
		 * @since 4.3.0
1765
		 *
1766
		 * @param bool $development_version Is this a develoment version of Jetpack?
1767
		 */
1768
		return (bool) apply_filters(
1769
			'jetpack_development_version',
1770
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1771
		);
1772
	}
1773
1774
	/**
1775
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1776
	 */
1777
	public static function is_user_connected( $user_id = false ) {
1778
		return self::connection()->is_user_connected( $user_id );
1779
	}
1780
1781
	/**
1782
	 * Get the wpcom user data of the current|specified connected user.
1783
	 */
1784 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1785
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1786
		if ( ! $user_id ) {
1787
			$user_id = get_current_user_id();
1788
		}
1789
1790
		$transient_key = "jetpack_connected_user_data_$user_id";
1791
1792
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1793
			return $cached_user_data;
1794
		}
1795
1796
		$xml = new Jetpack_IXR_Client(
1797
			array(
1798
				'user_id' => $user_id,
1799
			)
1800
		);
1801
		$xml->query( 'wpcom.getUser' );
1802
		if ( ! $xml->isError() ) {
1803
			$user_data = $xml->getResponse();
1804
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1805
			return $user_data;
1806
		}
1807
1808
		return false;
1809
	}
1810
1811
	/**
1812
	 * Get the wpcom email of the current|specified connected user.
1813
	 */
1814
	public static function get_connected_user_email( $user_id = null ) {
1815
		if ( ! $user_id ) {
1816
			$user_id = get_current_user_id();
1817
		}
1818
1819
		$xml = new Jetpack_IXR_Client(
1820
			array(
1821
				'user_id' => $user_id,
1822
			)
1823
		);
1824
		$xml->query( 'wpcom.getUserEmail' );
1825
		if ( ! $xml->isError() ) {
1826
			return $xml->getResponse();
1827
		}
1828
		return false;
1829
	}
1830
1831
	/**
1832
	 * Get the wpcom email of the master user.
1833
	 */
1834
	public static function get_master_user_email() {
1835
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1836
		if ( $master_user_id ) {
1837
			return self::get_connected_user_email( $master_user_id );
1838
		}
1839
		return '';
1840
	}
1841
1842
	/**
1843
	 * Whether the current user is the connection owner.
1844
	 *
1845
	 * @deprecated since 7.7
1846
	 *
1847
	 * @return bool Whether the current user is the connection owner.
1848
	 */
1849
	public function current_user_is_connection_owner() {
1850
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1851
		return self::connection()->is_connection_owner();
1852
	}
1853
1854
	/**
1855
	 * Gets current user IP address.
1856
	 *
1857
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1858
	 *
1859
	 * @return string                  Current user IP address.
1860
	 */
1861
	public static function current_user_ip( $check_all_headers = false ) {
1862
		if ( $check_all_headers ) {
1863
			foreach ( array(
1864
				'HTTP_CF_CONNECTING_IP',
1865
				'HTTP_CLIENT_IP',
1866
				'HTTP_X_FORWARDED_FOR',
1867
				'HTTP_X_FORWARDED',
1868
				'HTTP_X_CLUSTER_CLIENT_IP',
1869
				'HTTP_FORWARDED_FOR',
1870
				'HTTP_FORWARDED',
1871
				'HTTP_VIA',
1872
			) as $key ) {
1873
				if ( ! empty( $_SERVER[ $key ] ) ) {
1874
					return $_SERVER[ $key ];
1875
				}
1876
			}
1877
		}
1878
1879
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1880
	}
1881
1882
	/**
1883
	 * Synchronize connected user role changes
1884
	 */
1885
	function user_role_change( $user_id ) {
1886
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1887
		Users::user_role_change( $user_id );
1888
	}
1889
1890
	/**
1891
	 * Loads the currently active modules.
1892
	 */
1893
	public static function load_modules() {
1894
		$is_offline_mode = ( new Status() )->is_offline_mode();
1895
		if (
1896
			! self::is_active()
1897
			&& ! $is_offline_mode
1898
			&& ! self::is_onboarding()
1899
			&& (
1900
				! is_multisite()
1901
				|| ! get_site_option( 'jetpack_protect_active' )
1902
			)
1903
		) {
1904
			return;
1905
		}
1906
1907
		$version = Jetpack_Options::get_option( 'version' );
1908 View Code Duplication
		if ( ! $version ) {
1909
			$version = $old_version = JETPACK__VERSION . ':' . time();
1910
			/** This action is documented in class.jetpack.php */
1911
			do_action( 'updating_jetpack_version', $version, false );
1912
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1913
		}
1914
		list( $version ) = explode( ':', $version );
1915
1916
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1917
1918
		$modules_data = array();
1919
1920
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1921
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1922
			$updated_modules = array();
1923
			foreach ( $modules as $module ) {
1924
				$modules_data[ $module ] = self::get_module( $module );
1925
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1926
					continue;
1927
				}
1928
1929
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1930
					continue;
1931
				}
1932
1933
				$updated_modules[] = $module;
1934
			}
1935
1936
			$modules = array_diff( $modules, $updated_modules );
1937
		}
1938
1939
		foreach ( $modules as $index => $module ) {
1940
			// If we're in offline mode, disable modules requiring a connection.
1941
			if ( $is_offline_mode ) {
1942
				// Prime the pump if we need to
1943
				if ( empty( $modules_data[ $module ] ) ) {
1944
					$modules_data[ $module ] = self::get_module( $module );
1945
				}
1946
				// If the module requires a connection, but we're in local mode, don't include it.
1947
				if ( $modules_data[ $module ]['requires_connection'] ) {
1948
					continue;
1949
				}
1950
			}
1951
1952
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1953
				continue;
1954
			}
1955
1956
			if ( ! include_once self::get_module_path( $module ) ) {
1957
				unset( $modules[ $index ] );
1958
				self::update_active_modules( array_values( $modules ) );
1959
				continue;
1960
			}
1961
1962
			/**
1963
			 * Fires when a specific module is loaded.
1964
			 * The dynamic part of the hook, $module, is the module slug.
1965
			 *
1966
			 * @since 1.1.0
1967
			 */
1968
			do_action( 'jetpack_module_loaded_' . $module );
1969
		}
1970
1971
		/**
1972
		 * Fires when all the modules are loaded.
1973
		 *
1974
		 * @since 1.1.0
1975
		 */
1976
		do_action( 'jetpack_modules_loaded' );
1977
1978
		// 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.
1979
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1980
	}
1981
1982
	/**
1983
	 * Check if Jetpack's REST API compat file should be included
1984
	 *
1985
	 * @action plugins_loaded
1986
	 * @return null
1987
	 */
1988
	public function check_rest_api_compat() {
1989
		/**
1990
		 * Filters the list of REST API compat files to be included.
1991
		 *
1992
		 * @since 2.2.5
1993
		 *
1994
		 * @param array $args Array of REST API compat files to include.
1995
		 */
1996
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1997
1998
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1999
			require_once $_jetpack_rest_api_compat_include;
2000
		}
2001
	}
2002
2003
	/**
2004
	 * Gets all plugins currently active in values, regardless of whether they're
2005
	 * traditionally activated or network activated.
2006
	 *
2007
	 * @todo Store the result in core's object cache maybe?
2008
	 */
2009
	public static function get_active_plugins() {
2010
		$active_plugins = (array) get_option( 'active_plugins', array() );
2011
2012
		if ( is_multisite() ) {
2013
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2014
			// whereas active_plugins stores them in the values.
2015
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2016
			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...
2017
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2018
			}
2019
		}
2020
2021
		sort( $active_plugins );
2022
2023
		return array_unique( $active_plugins );
2024
	}
2025
2026
	/**
2027
	 * Gets and parses additional plugin data to send with the heartbeat data
2028
	 *
2029
	 * @since 3.8.1
2030
	 *
2031
	 * @return array Array of plugin data
2032
	 */
2033
	public static function get_parsed_plugin_data() {
2034
		if ( ! function_exists( 'get_plugins' ) ) {
2035
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2036
		}
2037
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2038
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2039
		$active_plugins = self::get_active_plugins();
2040
2041
		$plugins = array();
2042
		foreach ( $all_plugins as $path => $plugin_data ) {
2043
			$plugins[ $path ] = array(
2044
				'is_active' => in_array( $path, $active_plugins ),
2045
				'file'      => $path,
2046
				'name'      => $plugin_data['Name'],
2047
				'version'   => $plugin_data['Version'],
2048
				'author'    => $plugin_data['Author'],
2049
			);
2050
		}
2051
2052
		return $plugins;
2053
	}
2054
2055
	/**
2056
	 * Gets and parses theme data to send with the heartbeat data
2057
	 *
2058
	 * @since 3.8.1
2059
	 *
2060
	 * @return array Array of theme data
2061
	 */
2062
	public static function get_parsed_theme_data() {
2063
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2064
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2065
2066
		$themes = array();
2067
		foreach ( $all_themes as $slug => $theme_data ) {
2068
			$theme_headers = array();
2069
			foreach ( $header_keys as $header_key ) {
2070
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2071
			}
2072
2073
			$themes[ $slug ] = array(
2074
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2075
				'slug'            => $slug,
2076
				'theme_root'      => $theme_data->get_theme_root_uri(),
2077
				'parent'          => $theme_data->parent(),
2078
				'headers'         => $theme_headers,
2079
			);
2080
		}
2081
2082
		return $themes;
2083
	}
2084
2085
	/**
2086
	 * Checks whether a specific plugin is active.
2087
	 *
2088
	 * We don't want to store these in a static variable, in case
2089
	 * there are switch_to_blog() calls involved.
2090
	 */
2091
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2092
		return in_array( $plugin, self::get_active_plugins() );
2093
	}
2094
2095
	/**
2096
	 * Check if Jetpack's Open Graph tags should be used.
2097
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2098
	 *
2099
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2100
	 * @action plugins_loaded
2101
	 * @return null
2102
	 */
2103
	public function check_open_graph() {
2104
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2105
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2106
		}
2107
2108
		$active_plugins = self::get_active_plugins();
2109
2110
		if ( ! empty( $active_plugins ) ) {
2111
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2112
				if ( in_array( $plugin, $active_plugins ) ) {
2113
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2114
					break;
2115
				}
2116
			}
2117
		}
2118
2119
		/**
2120
		 * Allow the addition of Open Graph Meta Tags to all pages.
2121
		 *
2122
		 * @since 2.0.3
2123
		 *
2124
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2125
		 */
2126
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2127
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2128
		}
2129
	}
2130
2131
	/**
2132
	 * Check if Jetpack's Twitter tags should be used.
2133
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2134
	 *
2135
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2136
	 * @action plugins_loaded
2137
	 * @return null
2138
	 */
2139
	public function check_twitter_tags() {
2140
2141
		$active_plugins = self::get_active_plugins();
2142
2143
		if ( ! empty( $active_plugins ) ) {
2144
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2145
				if ( in_array( $plugin, $active_plugins ) ) {
2146
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2147
					break;
2148
				}
2149
			}
2150
		}
2151
2152
		/**
2153
		 * Allow Twitter Card Meta tags to be disabled.
2154
		 *
2155
		 * @since 2.6.0
2156
		 *
2157
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2158
		 */
2159
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2160
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2161
		}
2162
	}
2163
2164
	/**
2165
	 * Allows plugins to submit security reports.
2166
	 *
2167
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2168
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2169
	 * @param array  $args         See definitions above
2170
	 */
2171
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2172
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2173
	}
2174
2175
	/* Jetpack Options API */
2176
2177
	public static function get_option_names( $type = 'compact' ) {
2178
		return Jetpack_Options::get_option_names( $type );
2179
	}
2180
2181
	/**
2182
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2183
	 *
2184
	 * @param string $name    Option name
2185
	 * @param mixed  $default (optional)
2186
	 */
2187
	public static function get_option( $name, $default = false ) {
2188
		return Jetpack_Options::get_option( $name, $default );
2189
	}
2190
2191
	/**
2192
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2193
	 *
2194
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2195
	 * @param string $name  Option name
2196
	 * @param mixed  $value Option value
2197
	 */
2198
	public static function update_option( $name, $value ) {
2199
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2200
		return Jetpack_Options::update_option( $name, $value );
2201
	}
2202
2203
	/**
2204
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2205
	 *
2206
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2207
	 * @param array $array array( option name => option value, ... )
2208
	 */
2209
	public static function update_options( $array ) {
2210
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2211
		return Jetpack_Options::update_options( $array );
2212
	}
2213
2214
	/**
2215
	 * Deletes the given option.  May be passed multiple option names as an array.
2216
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2217
	 *
2218
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2219
	 * @param string|array $names
2220
	 */
2221
	public static function delete_option( $names ) {
2222
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2223
		return Jetpack_Options::delete_option( $names );
2224
	}
2225
2226
	/**
2227
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2228
	 *
2229
	 * Enters a user token into the user_tokens option
2230
	 *
2231
	 * @param int    $user_id The user id.
2232
	 * @param string $token The user token.
2233
	 * @param bool   $is_master_user Whether the user is the master user.
2234
	 * @return bool
2235
	 */
2236
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2237
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2238
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2239
	}
2240
2241
	/**
2242
	 * Returns an array of all PHP files in the specified absolute path.
2243
	 * Equivalent to glob( "$absolute_path/*.php" ).
2244
	 *
2245
	 * @param string $absolute_path The absolute path of the directory to search.
2246
	 * @return array Array of absolute paths to the PHP files.
2247
	 */
2248
	public static function glob_php( $absolute_path ) {
2249
		if ( function_exists( 'glob' ) ) {
2250
			return glob( "$absolute_path/*.php" );
2251
		}
2252
2253
		$absolute_path = untrailingslashit( $absolute_path );
2254
		$files         = array();
2255
		if ( ! $dir = @opendir( $absolute_path ) ) {
2256
			return $files;
2257
		}
2258
2259
		while ( false !== $file = readdir( $dir ) ) {
2260
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2261
				continue;
2262
			}
2263
2264
			$file = "$absolute_path/$file";
2265
2266
			if ( ! is_file( $file ) ) {
2267
				continue;
2268
			}
2269
2270
			$files[] = $file;
2271
		}
2272
2273
		closedir( $dir );
2274
2275
		return $files;
2276
	}
2277
2278
	public static function activate_new_modules( $redirect = false ) {
2279
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2280
			return;
2281
		}
2282
2283
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2284 View Code Duplication
		if ( ! $jetpack_old_version ) {
2285
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2286
			/** This action is documented in class.jetpack.php */
2287
			do_action( 'updating_jetpack_version', $version, false );
2288
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2289
		}
2290
2291
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2292
2293
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2294
			return;
2295
		}
2296
2297
		$active_modules     = self::get_active_modules();
2298
		$reactivate_modules = array();
2299
		foreach ( $active_modules as $active_module ) {
2300
			$module = self::get_module( $active_module );
2301
			if ( ! isset( $module['changed'] ) ) {
2302
				continue;
2303
			}
2304
2305
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2306
				continue;
2307
			}
2308
2309
			$reactivate_modules[] = $active_module;
2310
			self::deactivate_module( $active_module );
2311
		}
2312
2313
		$new_version = JETPACK__VERSION . ':' . time();
2314
		/** This action is documented in class.jetpack.php */
2315
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2316
		Jetpack_Options::update_options(
2317
			array(
2318
				'version'     => $new_version,
2319
				'old_version' => $jetpack_old_version,
2320
			)
2321
		);
2322
2323
		self::state( 'message', 'modules_activated' );
2324
2325
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
0 ignored issues
show
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...
2326
2327
		if ( $redirect ) {
2328
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2329
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2330
				$page = $_GET['page'];
2331
			}
2332
2333
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2334
			exit;
2335
		}
2336
	}
2337
2338
	/**
2339
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2340
	 * Make sure to tuck away module "library" files in a sub-directory.
2341
	 */
2342
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2343
		static $modules = null;
2344
2345
		if ( ! isset( $modules ) ) {
2346
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2347
			// Use the cache if we're on the front-end and it's available...
2348
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2349
				$modules = $available_modules_option[ JETPACK__VERSION ];
2350
			} else {
2351
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2352
2353
				$modules = array();
2354
2355
				foreach ( $files as $file ) {
2356
					if ( ! $headers = self::get_module( $file ) ) {
2357
						continue;
2358
					}
2359
2360
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2361
				}
2362
2363
				Jetpack_Options::update_option(
2364
					'available_modules',
2365
					array(
2366
						JETPACK__VERSION => $modules,
2367
					)
2368
				);
2369
			}
2370
		}
2371
2372
		/**
2373
		 * Filters the array of modules available to be activated.
2374
		 *
2375
		 * @since 2.4.0
2376
		 *
2377
		 * @param array $modules Array of available modules.
2378
		 * @param string $min_version Minimum version number required to use modules.
2379
		 * @param string $max_version Maximum version number required to use modules.
2380
		 */
2381
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
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...
2382
2383
		if ( ! $min_version && ! $max_version ) {
2384
			return array_keys( $mods );
2385
		}
2386
2387
		$r = array();
2388
		foreach ( $mods as $slug => $introduced ) {
2389
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2390
				continue;
2391
			}
2392
2393
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2394
				continue;
2395
			}
2396
2397
			$r[] = $slug;
2398
		}
2399
2400
		return $r;
2401
	}
2402
2403
	/**
2404
	 * Default modules loaded on activation.
2405
	 */
2406
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2407
		$return = array();
2408
2409
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2410
			$module_data = self::get_module( $module );
2411
2412
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2413
				case 'yes':
2414
					$return[] = $module;
2415
					break;
2416
				case 'public':
2417
					if ( Jetpack_Options::get_option( 'public' ) ) {
2418
						$return[] = $module;
2419
					}
2420
					break;
2421
				case 'no':
2422
				default:
2423
					break;
2424
			}
2425
		}
2426
		/**
2427
		 * Filters the array of default modules.
2428
		 *
2429
		 * @since 2.5.0
2430
		 *
2431
		 * @param array $return Array of default modules.
2432
		 * @param string $min_version Minimum version number required to use modules.
2433
		 * @param string $max_version Maximum version number required to use modules.
2434
		 */
2435
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
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...
2436
	}
2437
2438
	/**
2439
	 * Checks activated modules during auto-activation to determine
2440
	 * if any of those modules are being deprecated.  If so, close
2441
	 * them out, and add any replacement modules.
2442
	 *
2443
	 * Runs at priority 99 by default.
2444
	 *
2445
	 * This is run late, so that it can still activate a module if
2446
	 * the new module is a replacement for another that the user
2447
	 * currently has active, even if something at the normal priority
2448
	 * would kibosh everything.
2449
	 *
2450
	 * @since 2.6
2451
	 * @uses jetpack_get_default_modules filter
2452
	 * @param array $modules
2453
	 * @return array
2454
	 */
2455
	function handle_deprecated_modules( $modules ) {
2456
		$deprecated_modules = array(
2457
			'debug'            => null,  // Closed out and moved to the debugger library.
2458
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2459
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2460
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2461
		);
2462
2463
		// Don't activate SSO if they never completed activating WPCC.
2464
		if ( self::is_module_active( 'wpcc' ) ) {
2465
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2466
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2467
				$deprecated_modules['wpcc'] = null;
2468
			}
2469
		}
2470
2471
		foreach ( $deprecated_modules as $module => $replacement ) {
2472
			if ( self::is_module_active( $module ) ) {
2473
				self::deactivate_module( $module );
2474
				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...
2475
					$modules[] = $replacement;
2476
				}
2477
			}
2478
		}
2479
2480
		return array_unique( $modules );
2481
	}
2482
2483
	/**
2484
	 * Checks activated plugins during auto-activation to determine
2485
	 * if any of those plugins are in the list with a corresponding module
2486
	 * that is not compatible with the plugin. The module will not be allowed
2487
	 * to auto-activate.
2488
	 *
2489
	 * @since 2.6
2490
	 * @uses jetpack_get_default_modules filter
2491
	 * @param array $modules
2492
	 * @return array
2493
	 */
2494
	function filter_default_modules( $modules ) {
2495
2496
		$active_plugins = self::get_active_plugins();
2497
2498
		if ( ! empty( $active_plugins ) ) {
2499
2500
			// For each module we'd like to auto-activate...
2501
			foreach ( $modules as $key => $module ) {
2502
				// If there are potential conflicts for it...
2503
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2504
					// For each potential conflict...
2505
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2506
						// If that conflicting plugin is active...
2507
						if ( in_array( $plugin, $active_plugins ) ) {
2508
							// Remove that item from being auto-activated.
2509
							unset( $modules[ $key ] );
2510
						}
2511
					}
2512
				}
2513
			}
2514
		}
2515
2516
		return $modules;
2517
	}
2518
2519
	/**
2520
	 * Extract a module's slug from its full path.
2521
	 */
2522
	public static function get_module_slug( $file ) {
2523
		return str_replace( '.php', '', basename( $file ) );
2524
	}
2525
2526
	/**
2527
	 * Generate a module's path from its slug.
2528
	 */
2529
	public static function get_module_path( $slug ) {
2530
		/**
2531
		 * Filters the path of a modules.
2532
		 *
2533
		 * @since 7.4.0
2534
		 *
2535
		 * @param array $return The absolute path to a module's root php file
2536
		 * @param string $slug The module slug
2537
		 */
2538
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
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...
2539
	}
2540
2541
	/**
2542
	 * Load module data from module file. Headers differ from WordPress
2543
	 * plugin headers to avoid them being identified as standalone
2544
	 * plugins on the WordPress plugins page.
2545
	 */
2546
	public static function get_module( $module ) {
2547
		$headers = array(
2548
			'name'                      => 'Module Name',
2549
			'description'               => 'Module Description',
2550
			'sort'                      => 'Sort Order',
2551
			'recommendation_order'      => 'Recommendation Order',
2552
			'introduced'                => 'First Introduced',
2553
			'changed'                   => 'Major Changes In',
2554
			'deactivate'                => 'Deactivate',
2555
			'free'                      => 'Free',
2556
			'requires_connection'       => 'Requires Connection',
2557
			'auto_activate'             => 'Auto Activate',
2558
			'module_tags'               => 'Module Tags',
2559
			'feature'                   => 'Feature',
2560
			'additional_search_queries' => 'Additional Search Queries',
2561
			'plan_classes'              => 'Plans',
2562
		);
2563
2564
		$file = self::get_module_path( self::get_module_slug( $module ) );
2565
2566
		$mod = self::get_file_data( $file, $headers );
2567
		if ( empty( $mod['name'] ) ) {
2568
			return false;
2569
		}
2570
2571
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2572
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2573
		$mod['deactivate']           = empty( $mod['deactivate'] );
2574
		$mod['free']                 = empty( $mod['free'] );
2575
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2576
2577
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2578
			$mod['auto_activate'] = 'No';
2579
		} else {
2580
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2581
		}
2582
2583
		if ( $mod['module_tags'] ) {
2584
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2585
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2586
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2587
		} else {
2588
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2589
		}
2590
2591 View Code Duplication
		if ( $mod['plan_classes'] ) {
2592
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2593
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2594
		} else {
2595
			$mod['plan_classes'] = array( 'free' );
2596
		}
2597
2598 View Code Duplication
		if ( $mod['feature'] ) {
2599
			$mod['feature'] = explode( ',', $mod['feature'] );
2600
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2601
		} else {
2602
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2603
		}
2604
2605
		/**
2606
		 * Filters the feature array on a module.
2607
		 *
2608
		 * This filter allows you to control where each module is filtered: Recommended,
2609
		 * and the default "Other" listing.
2610
		 *
2611
		 * @since 3.5.0
2612
		 *
2613
		 * @param array   $mod['feature'] The areas to feature this module:
2614
		 *     'Recommended' shows on the main Jetpack admin screen.
2615
		 *     'Other' should be the default if no other value is in the array.
2616
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2617
		 * @param array   $mod All the currently assembled module data.
2618
		 */
2619
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
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...
2620
2621
		/**
2622
		 * Filter the returned data about a module.
2623
		 *
2624
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2625
		 * so please be careful.
2626
		 *
2627
		 * @since 3.6.0
2628
		 *
2629
		 * @param array   $mod    The details of the requested module.
2630
		 * @param string  $module The slug of the module, e.g. sharedaddy
2631
		 * @param string  $file   The path to the module source file.
2632
		 */
2633
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
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...
2634
	}
2635
2636
	/**
2637
	 * Like core's get_file_data implementation, but caches the result.
2638
	 */
2639
	public static function get_file_data( $file, $headers ) {
2640
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2641
		$file_name = basename( $file );
2642
2643
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2644
2645
		$file_data_option = get_transient( $cache_key );
2646
2647
		if ( ! is_array( $file_data_option ) ) {
2648
			delete_transient( $cache_key );
2649
			$file_data_option = false;
2650
		}
2651
2652
		if ( false === $file_data_option ) {
2653
			$file_data_option = array();
2654
		}
2655
2656
		$key           = md5( $file_name . serialize( $headers ) );
2657
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2658
2659
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2660
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2661
			return $file_data_option[ $key ];
2662
		}
2663
2664
		$data = get_file_data( $file, $headers );
2665
2666
		$file_data_option[ $key ] = $data;
2667
2668
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2669
2670
		return $data;
2671
	}
2672
2673
2674
	/**
2675
	 * Return translated module tag.
2676
	 *
2677
	 * @param string $tag Tag as it appears in each module heading.
2678
	 *
2679
	 * @return mixed
2680
	 */
2681
	public static function translate_module_tag( $tag ) {
2682
		return jetpack_get_module_i18n_tag( $tag );
2683
	}
2684
2685
	/**
2686
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2687
	 *
2688
	 * @since 3.9.2
2689
	 *
2690
	 * @param array $modules
2691
	 *
2692
	 * @return string|void
2693
	 */
2694
	public static function get_translated_modules( $modules ) {
2695
		foreach ( $modules as $index => $module ) {
2696
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2697
			if ( isset( $module['name'] ) ) {
2698
				$modules[ $index ]['name'] = $i18n_module['name'];
2699
			}
2700
			if ( isset( $module['description'] ) ) {
2701
				$modules[ $index ]['description']       = $i18n_module['description'];
2702
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2703
			}
2704
		}
2705
		return $modules;
2706
	}
2707
2708
	/**
2709
	 * Get a list of activated modules as an array of module slugs.
2710
	 */
2711
	public static function get_active_modules() {
2712
		$active = Jetpack_Options::get_option( 'active_modules' );
2713
2714
		if ( ! is_array( $active ) ) {
2715
			$active = array();
2716
		}
2717
2718
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2719
			$active[] = 'vaultpress';
2720
		} else {
2721
			$active = array_diff( $active, array( 'vaultpress' ) );
2722
		}
2723
2724
		// If protect is active on the main site of a multisite, it should be active on all sites.
2725
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2726
			$active[] = 'protect';
2727
		}
2728
2729
		/**
2730
		 * Allow filtering of the active modules.
2731
		 *
2732
		 * Gives theme and plugin developers the power to alter the modules that
2733
		 * are activated on the fly.
2734
		 *
2735
		 * @since 5.8.0
2736
		 *
2737
		 * @param array $active Array of active module slugs.
2738
		 */
2739
		$active = apply_filters( 'jetpack_active_modules', $active );
2740
2741
		return array_unique( $active );
2742
	}
2743
2744
	/**
2745
	 * Check whether or not a Jetpack module is active.
2746
	 *
2747
	 * @param string $module The slug of a Jetpack module.
2748
	 * @return bool
2749
	 *
2750
	 * @static
2751
	 */
2752
	public static function is_module_active( $module ) {
2753
		return in_array( $module, self::get_active_modules() );
2754
	}
2755
2756
	public static function is_module( $module ) {
2757
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2758
	}
2759
2760
	/**
2761
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2762
	 *
2763
	 * @param bool $catch True to start catching, False to stop.
2764
	 *
2765
	 * @static
2766
	 */
2767
	public static function catch_errors( $catch ) {
2768
		static $display_errors, $error_reporting;
2769
2770
		if ( $catch ) {
2771
			$display_errors  = @ini_set( 'display_errors', 1 );
2772
			$error_reporting = @error_reporting( E_ALL );
2773
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2774
		} else {
2775
			@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...
2776
			@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...
2777
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2778
		}
2779
	}
2780
2781
	/**
2782
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2783
	 */
2784
	public static function catch_errors_on_shutdown() {
2785
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2786
	}
2787
2788
	/**
2789
	 * Rewrite any string to make paths easier to read.
2790
	 *
2791
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2792
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2793
	 *
2794
	 * @param $string
2795
	 * @return mixed
2796
	 */
2797
	public static function alias_directories( $string ) {
2798
		// ABSPATH has a trailing slash.
2799
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2800
		// WP_CONTENT_DIR does not have a trailing slash.
2801
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2802
2803
		return $string;
2804
	}
2805
2806
	public static function activate_default_modules(
2807
		$min_version = false,
2808
		$max_version = false,
2809
		$other_modules = array(),
2810
		$redirect = null,
2811
		$send_state_messages = null
2812
	) {
2813
		$jetpack = self::init();
2814
2815
		if ( is_null( $redirect ) ) {
2816
			if (
2817
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2818
			||
2819
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2820
			||
2821
				( defined( 'WP_CLI' ) && WP_CLI )
2822
			||
2823
				( defined( 'DOING_CRON' ) && DOING_CRON )
2824
			||
2825
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2826
			) {
2827
				$redirect = false;
2828
			} elseif ( is_admin() ) {
2829
				$redirect = true;
2830
			} else {
2831
				$redirect = false;
2832
			}
2833
		}
2834
2835
		if ( is_null( $send_state_messages ) ) {
2836
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2837
		}
2838
2839
		$modules = self::get_default_modules( $min_version, $max_version );
2840
		$modules = array_merge( $other_modules, $modules );
2841
2842
		// Look for standalone plugins and disable if active.
2843
2844
		$to_deactivate = array();
2845
		foreach ( $modules as $module ) {
2846
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2847
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2848
			}
2849
		}
2850
2851
		$deactivated = array();
2852
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2853
			list( $probable_file, $probable_title ) = $deactivate_me;
2854
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2855
				$deactivated[] = $module;
2856
			}
2857
		}
2858
2859
		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...
2860
			if ( $send_state_messages ) {
2861
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2862
			}
2863
2864
			if ( $redirect ) {
2865
				$url = add_query_arg(
2866
					array(
2867
						'action'   => 'activate_default_modules',
2868
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2869
					),
2870
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2871
				);
2872
				wp_safe_redirect( $url );
2873
				exit;
2874
			}
2875
		}
2876
2877
		/**
2878
		 * Fires before default modules are activated.
2879
		 *
2880
		 * @since 1.9.0
2881
		 *
2882
		 * @param string $min_version Minimum version number required to use modules.
2883
		 * @param string $max_version Maximum version number required to use modules.
2884
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2885
		 */
2886
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2887
2888
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2889
		if ( $send_state_messages ) {
2890
			self::restate();
2891
			self::catch_errors( true );
2892
		}
2893
2894
		$active = self::get_active_modules();
2895
2896
		foreach ( $modules as $module ) {
2897
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2898
				$active[] = $module;
2899
				self::update_active_modules( $active );
2900
				continue;
2901
			}
2902
2903
			if ( $send_state_messages && in_array( $module, $active ) ) {
2904
				$module_info = self::get_module( $module );
2905 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2906
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2907
					if ( $active_state = self::state( $state ) ) {
2908
						$active_state = explode( ',', $active_state );
2909
					} else {
2910
						$active_state = array();
2911
					}
2912
					$active_state[] = $module;
2913
					self::state( $state, implode( ',', $active_state ) );
2914
				}
2915
				continue;
2916
			}
2917
2918
			$file = self::get_module_path( $module );
2919
			if ( ! file_exists( $file ) ) {
2920
				continue;
2921
			}
2922
2923
			// we'll override this later if the plugin can be included without fatal error
2924
			if ( $redirect ) {
2925
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2926
			}
2927
2928
			if ( $send_state_messages ) {
2929
				self::state( 'error', 'module_activation_failed' );
2930
				self::state( 'module', $module );
2931
			}
2932
2933
			ob_start();
2934
			require_once $file;
2935
2936
			$active[] = $module;
2937
2938 View Code Duplication
			if ( $send_state_messages ) {
2939
2940
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2941
				if ( $active_state = self::state( $state ) ) {
2942
					$active_state = explode( ',', $active_state );
2943
				} else {
2944
					$active_state = array();
2945
				}
2946
				$active_state[] = $module;
2947
				self::state( $state, implode( ',', $active_state ) );
2948
			}
2949
2950
			self::update_active_modules( $active );
2951
2952
			ob_end_clean();
2953
		}
2954
2955
		if ( $send_state_messages ) {
2956
			self::state( 'error', false );
0 ignored issues
show
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...
2957
			self::state( 'module', false );
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2958
		}
2959
2960
		self::catch_errors( false );
2961
		/**
2962
		 * Fires when default modules are activated.
2963
		 *
2964
		 * @since 1.9.0
2965
		 *
2966
		 * @param string $min_version Minimum version number required to use modules.
2967
		 * @param string $max_version Maximum version number required to use modules.
2968
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2969
		 */
2970
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2971
	}
2972
2973
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2974
		/**
2975
		 * Fires before a module is activated.
2976
		 *
2977
		 * @since 2.6.0
2978
		 *
2979
		 * @param string $module Module slug.
2980
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2981
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2982
		 */
2983
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2984
2985
		$jetpack = self::init();
2986
2987
		if ( ! strlen( $module ) ) {
2988
			return false;
2989
		}
2990
2991
		if ( ! self::is_module( $module ) ) {
2992
			return false;
2993
		}
2994
2995
		// If it's already active, then don't do it again
2996
		$active = self::get_active_modules();
2997
		foreach ( $active as $act ) {
2998
			if ( $act == $module ) {
2999
				return true;
3000
			}
3001
		}
3002
3003
		$module_data = self::get_module( $module );
3004
3005
		$is_offline_mode = ( new Status() )->is_offline_mode();
3006
		if ( ! self::is_active() ) {
3007
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3008
				return false;
3009
			}
3010
3011
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3012
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3013
				return false;
3014
			}
3015
		}
3016
3017
		// Check and see if the old plugin is active
3018
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3019
			// Deactivate the old plugin
3020
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3021
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3022
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3023
				self::state( 'deactivated_plugins', $module );
3024
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3025
				exit;
3026
			}
3027
		}
3028
3029
		// Protect won't work with mis-configured IPs
3030
		if ( 'protect' === $module ) {
3031
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3032
			if ( ! jetpack_protect_get_ip() ) {
3033
				self::state( 'message', 'protect_misconfigured_ip' );
3034
				return false;
3035
			}
3036
		}
3037
3038
		if ( ! Jetpack_Plan::supports( $module ) ) {
3039
			return false;
3040
		}
3041
3042
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3043
		self::state( 'module', $module );
3044
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3045
3046
		self::catch_errors( true );
3047
		ob_start();
3048
		require self::get_module_path( $module );
3049
		/** This action is documented in class.jetpack.php */
3050
		do_action( 'jetpack_activate_module', $module );
3051
		$active[] = $module;
3052
		self::update_active_modules( $active );
3053
3054
		self::state( 'error', false ); // the override
0 ignored issues
show
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...
3055
		ob_end_clean();
3056
		self::catch_errors( false );
3057
3058
		if ( $redirect ) {
3059
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3060
		}
3061
		if ( $exit ) {
3062
			exit;
3063
		}
3064
		return true;
3065
	}
3066
3067
	function activate_module_actions( $module ) {
3068
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3069
	}
3070
3071
	public static function deactivate_module( $module ) {
3072
		/**
3073
		 * Fires when a module is deactivated.
3074
		 *
3075
		 * @since 1.9.0
3076
		 *
3077
		 * @param string $module Module slug.
3078
		 */
3079
		do_action( 'jetpack_pre_deactivate_module', $module );
3080
3081
		$jetpack = self::init();
0 ignored issues
show
$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...
3082
3083
		$active = self::get_active_modules();
3084
		$new    = array_filter( array_diff( $active, (array) $module ) );
3085
3086
		return self::update_active_modules( $new );
3087
	}
3088
3089
	public static function enable_module_configurable( $module ) {
3090
		$module = self::get_module_slug( $module );
3091
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3092
	}
3093
3094
	/**
3095
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3096
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3097
	 *
3098
	 * @param string $module Module slug
3099
	 * @return string $url module configuration URL
3100
	 */
3101
	public static function module_configuration_url( $module ) {
3102
		$module      = self::get_module_slug( $module );
3103
		$default_url = self::admin_url() . "#/settings?term=$module";
3104
		/**
3105
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3106
		 *
3107
		 * @since 6.9.0
3108
		 *
3109
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3110
		 */
3111
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3112
3113
		return $url;
3114
	}
3115
3116
	/* Installation */
3117
	public static function bail_on_activation( $message, $deactivate = true ) {
3118
		?>
3119
<!doctype html>
3120
<html>
3121
<head>
3122
<meta charset="<?php bloginfo( 'charset' ); ?>">
3123
<style>
3124
* {
3125
	text-align: center;
3126
	margin: 0;
3127
	padding: 0;
3128
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3129
}
3130
p {
3131
	margin-top: 1em;
3132
	font-size: 18px;
3133
}
3134
</style>
3135
<body>
3136
<p><?php echo esc_html( $message ); ?></p>
3137
</body>
3138
</html>
3139
		<?php
3140
		if ( $deactivate ) {
3141
			$plugins = get_option( 'active_plugins' );
3142
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3143
			$update  = false;
3144
			foreach ( $plugins as $i => $plugin ) {
3145
				if ( $plugin === $jetpack ) {
3146
					$plugins[ $i ] = false;
3147
					$update        = true;
3148
				}
3149
			}
3150
3151
			if ( $update ) {
3152
				update_option( 'active_plugins', array_filter( $plugins ) );
3153
			}
3154
		}
3155
		exit;
3156
	}
3157
3158
	/**
3159
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3160
	 *
3161
	 * @static
3162
	 */
3163
	public static function plugin_activation( $network_wide ) {
3164
		Jetpack_Options::update_option( 'activated', 1 );
3165
3166
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3167
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3168
		}
3169
3170
		if ( $network_wide ) {
3171
			self::state( 'network_nag', true );
0 ignored issues
show
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...
3172
		}
3173
3174
		// For firing one-off events (notices) immediately after activation
3175
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3176
3177
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3178
3179
		Health::on_jetpack_activated();
3180
3181
		self::plugin_initialize();
3182
	}
3183
3184
	public static function get_activation_source( $referer_url ) {
3185
3186
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3187
			return array( 'wp-cli', null );
3188
		}
3189
3190
		$referer = wp_parse_url( $referer_url );
3191
3192
		$source_type  = 'unknown';
3193
		$source_query = null;
3194
3195
		if ( ! is_array( $referer ) ) {
3196
			return array( $source_type, $source_query );
3197
		}
3198
3199
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

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...
3200
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

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...
3201
3202
		if ( isset( $referer['query'] ) ) {
3203
			parse_str( $referer['query'], $query_parts );
3204
		} else {
3205
			$query_parts = array();
3206
		}
3207
3208
		if ( $plugins_path === $referer['path'] ) {
3209
			$source_type = 'list';
3210
		} elseif ( $plugins_install_path === $referer['path'] ) {
3211
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3212
			switch ( $tab ) {
3213
				case 'popular':
3214
					$source_type = 'popular';
3215
					break;
3216
				case 'recommended':
3217
					$source_type = 'recommended';
3218
					break;
3219
				case 'favorites':
3220
					$source_type = 'favorites';
3221
					break;
3222
				case 'search':
3223
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3224
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3225
					break;
3226
				default:
3227
					$source_type = 'featured';
3228
			}
3229
		}
3230
3231
		return array( $source_type, $source_query );
3232
	}
3233
3234
	/**
3235
	 * Runs before bumping version numbers up to a new version
3236
	 *
3237
	 * @param string $version    Version:timestamp.
3238
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3239
	 */
3240
	public static function do_version_bump( $version, $old_version ) {
3241
		if ( $old_version ) { // For existing Jetpack installations.
3242
3243
			// If a front end page is visited after the update, the 'wp' action will fire.
3244
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3245
3246
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3247
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3248
		}
3249
	}
3250
3251
	/**
3252
	 * Sets the display_update_modal state.
3253
	 */
3254
	public static function set_update_modal_display() {
3255
		self::state( 'display_update_modal', true );
0 ignored issues
show
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...
3256
	}
3257
3258
	/**
3259
	 * Sets the internal version number and activation state.
3260
	 *
3261
	 * @static
3262
	 */
3263
	public static function plugin_initialize() {
3264
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3265
			Jetpack_Options::update_option( 'activated', 2 );
3266
		}
3267
3268 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3269
			$version = $old_version = JETPACK__VERSION . ':' . time();
3270
			/** This action is documented in class.jetpack.php */
3271
			do_action( 'updating_jetpack_version', $version, false );
3272
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3273
		}
3274
3275
		self::load_modules();
3276
3277
		Jetpack_Options::delete_option( 'do_activate' );
3278
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3279
	}
3280
3281
	/**
3282
	 * Removes all connection options
3283
	 *
3284
	 * @static
3285
	 */
3286
	public static function plugin_deactivation() {
3287
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3288
		$tracking = new Tracking();
3289
		$tracking->record_user_event( 'deactivate_plugin', array() );
3290
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3291
			Jetpack_Network::init()->deactivate();
3292
		} else {
3293
			self::disconnect( false );
3294
			// Jetpack_Heartbeat::init()->deactivate();
3295
		}
3296
	}
3297
3298
	/**
3299
	 * Disconnects from the Jetpack servers.
3300
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3301
	 *
3302
	 * @static
3303
	 */
3304
	public static function disconnect( $update_activated_state = true ) {
3305
		// The hook is not being set since Jetpack 9.0.0,
3306
		// but we're removing it just in case it wasn't properly cleaned up after the plugin update.
3307
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3308
3309
		Nonce_Handler::clean_all();
3310
3311
		$connection = self::connection();
3312
3313
		// If the site is in an IDC because sync is not allowed,
3314
		// let's make sure to not disconnect the production site.
3315
		if ( ! self::validate_sync_error_idc_option() ) {
3316
			$tracking = new Tracking();
3317
			$tracking->record_user_event( 'disconnect_site', array() );
3318
3319
			$connection->disconnect_site_wpcom( true );
3320
		}
3321
3322
		$connection->delete_all_connection_tokens( true );
3323
		Jetpack_IDC::clear_all_idc_options();
3324
3325
		if ( $update_activated_state ) {
3326
			Jetpack_Options::update_option( 'activated', 4 );
3327
		}
3328
3329
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3330
			// Check then record unique disconnection if site has never been disconnected previously
3331
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3332
				$jetpack_unique_connection['disconnected'] = 1;
3333
			} else {
3334
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3335
					// track unique disconnect
3336
					$jetpack = self::init();
3337
3338
					$jetpack->stat( 'connections', 'unique-disconnect' );
3339
					$jetpack->do_stats( 'server_side' );
3340
				}
3341
				// increment number of times disconnected
3342
				$jetpack_unique_connection['disconnected'] += 1;
3343
			}
3344
3345
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3346
		}
3347
3348
		// Delete all the sync related data. Since it could be taking up space.
3349
		Sender::get_instance()->uninstall();
3350
3351
	}
3352
3353
	/**
3354
	 * Unlinks the current user from the linked WordPress.com user.
3355
	 *
3356
	 * @deprecated since 7.7
3357
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3358
	 *
3359
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
3360
	 * @return Boolean Whether the disconnection of the user was successful.
3361
	 */
3362
	public static function unlink_user( $user_id = null ) {
3363
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3364
		return Connection_Manager::disconnect_user( $user_id );
3365
	}
3366
3367
	/**
3368
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3369
	 */
3370
	public static function try_registration() {
3371
		$terms_of_service = new Terms_Of_Service();
3372
		// The user has agreed to the TOS at some point by now.
3373
		$terms_of_service->agree();
3374
3375
		// Let's get some testing in beta versions and such.
3376
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3377
			// Before attempting to connect, let's make sure that the domains are viable.
3378
			$domains_to_check = array_unique(
3379
				array(
3380
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
3381
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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

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

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

Loading history...
3783
		if ( ! $token || is_wp_error( $token ) ) {
3784
			return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
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...
3785
		}
3786
3787
		$uploaded_files = array();
3788
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3789
		unset( $GLOBALS['post'] );
3790
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3791
			$file = array();
3792
			foreach ( $media_keys as $media_key ) {
3793
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3794
			}
3795
3796
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3797
3798
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3799
			if ( $hmac_provided !== $hmac_file ) {
3800
				$uploaded_files[ $index ] = (object) array(
3801
					'error'             => 'invalid_hmac',
3802
					'error_description' => 'The corresponding HMAC for this file does not match',
3803
				);
3804
				continue;
3805
			}
3806
3807
			$_FILES['.jetpack.upload.'] = $file;
3808
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3809
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3810
				$post_id = 0;
3811
			}
3812
3813
			if ( $update_media_item ) {
3814
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3815
					return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
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...
3816
				}
3817
3818
				$media_array = $_FILES['media'];
3819
3820
				$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...
3821
				$file_array['type']     = $media_array['type'][0];
3822
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3823
				$file_array['error']    = $media_array['error'][0];
3824
				$file_array['size']     = $media_array['size'][0];
3825
3826
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3827
3828
				if ( is_wp_error( $edited_media_item ) ) {
3829
					return $edited_media_item;
3830
				}
3831
3832
				$response = (object) array(
3833
					'id'   => (string) $post_id,
3834
					'file' => (string) $edited_media_item->post_title,
3835
					'url'  => (string) wp_get_attachment_url( $post_id ),
3836
					'type' => (string) $edited_media_item->post_mime_type,
3837
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3838
				);
3839
3840
				return (array) array( $response );
3841
			}
3842
3843
			$attachment_id = media_handle_upload(
3844
				'.jetpack.upload.',
3845
				$post_id,
3846
				array(),
3847
				array(
3848
					'action' => 'jetpack_upload_file',
3849
				)
3850
			);
3851
3852
			if ( ! $attachment_id ) {
3853
				$uploaded_files[ $index ] = (object) array(
3854
					'error'             => 'unknown',
3855
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3856
				);
3857
			} elseif ( is_wp_error( $attachment_id ) ) {
3858
				$uploaded_files[ $index ] = (object) array(
3859
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3860
					'error_description' => $attachment_id->get_error_message(),
3861
				);
3862
			} else {
3863
				$attachment               = get_post( $attachment_id );
3864
				$uploaded_files[ $index ] = (object) array(
3865
					'id'   => (string) $attachment_id,
3866
					'file' => $attachment->post_title,
3867
					'url'  => wp_get_attachment_url( $attachment_id ),
3868
					'type' => $attachment->post_mime_type,
3869
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3870
				);
3871
				// Zip files uploads are not supported unless they are done for installation purposed
3872
				// lets delete them in case something goes wrong in this whole process
3873
				if ( 'application/zip' === $attachment->post_mime_type ) {
3874
					// Schedule a cleanup for 2 hours from now in case of failed install.
3875
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3876
				}
3877
			}
3878
		}
3879
		if ( ! is_null( $global_post ) ) {
3880
			$GLOBALS['post'] = $global_post;
3881
		}
3882
3883
		return $uploaded_files;
3884
	}
3885
3886
	/**
3887
	 * Add help to the Jetpack page
3888
	 *
3889
	 * @since Jetpack (1.2.3)
3890
	 * @return false if not the Jetpack page
3891
	 */
3892
	function admin_help() {
3893
		$current_screen = get_current_screen();
3894
3895
		// Overview
3896
		$current_screen->add_help_tab(
3897
			array(
3898
				'id'      => 'home',
3899
				'title'   => __( 'Home', 'jetpack' ),
3900
				'content' =>
3901
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3902
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3903
					'<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>',
3904
			)
3905
		);
3906
3907
		// Screen Content
3908
		if ( current_user_can( 'manage_options' ) ) {
3909
			$current_screen->add_help_tab(
3910
				array(
3911
					'id'      => 'settings',
3912
					'title'   => __( 'Settings', 'jetpack' ),
3913
					'content' =>
3914
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3915
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3916
						'<ol>' .
3917
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3918
							'<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>' .
3919
						'</ol>' .
3920
						'<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>',
3921
				)
3922
			);
3923
		}
3924
3925
		// Help Sidebar
3926
		$support_url = Redirect::get_url( 'jetpack-support' );
3927
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3928
		$current_screen->set_help_sidebar(
3929
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3930
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3931
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3932
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3933
		);
3934
	}
3935
3936
	function admin_menu_css() {
3937
		wp_enqueue_style( 'jetpack-icons' );
3938
	}
3939
3940
	function admin_menu_order() {
3941
		return true;
3942
	}
3943
3944 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3945
		$jp_menu_order = array();
3946
3947
		foreach ( $menu_order as $index => $item ) {
3948
			if ( $item != 'jetpack' ) {
3949
				$jp_menu_order[] = $item;
3950
			}
3951
3952
			if ( $index == 0 ) {
3953
				$jp_menu_order[] = 'jetpack';
3954
			}
3955
		}
3956
3957
		return $jp_menu_order;
3958
	}
3959
3960
	function admin_banner_styles() {
3961
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3962
3963 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3964
			wp_register_style(
3965
				'jetpack-dops-style',
3966
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3967
				array(),
3968
				JETPACK__VERSION
3969
			);
3970
		}
3971
3972
		wp_enqueue_style(
3973
			'jetpack',
3974
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3975
			array( 'jetpack-dops-style' ),
3976
			JETPACK__VERSION . '-20121016'
3977
		);
3978
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3979
		wp_style_add_data( 'jetpack', 'suffix', $min );
3980
	}
3981
3982
	function plugin_action_links( $actions ) {
3983
3984
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3985
3986
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
3987
			return array_merge(
3988
				$jetpack_home,
3989
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3990
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3991
				$actions
3992
			);
3993
		}
3994
3995
		return array_merge( $jetpack_home, $actions );
3996
	}
3997
3998
	/**
3999
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4000
	 *
4001
	 * @param string $hook The current admin page.
4002
	 *
4003
	 * @return void
4004
	 */
4005
	public function deactivate_dialog( $hook ) {
4006
		if (
4007
			'plugins.php' === $hook
4008
			&& self::is_active()
4009
		) {
4010
4011
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4012
4013
			if ( count( $active_plugins_using_connection ) > 1 ) {
4014
4015
				add_thickbox();
4016
4017
				wp_register_script(
4018
					'jp-tracks',
4019
					'//stats.wp.com/w.js',
4020
					array(),
4021
					gmdate( 'YW' ),
4022
					true
4023
				);
4024
4025
				wp_register_script(
4026
					'jp-tracks-functions',
4027
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4028
					array( 'jp-tracks' ),
4029
					JETPACK__VERSION,
4030
					false
4031
				);
4032
4033
				wp_enqueue_script(
4034
					'jetpack-deactivate-dialog-js',
4035
					Assets::get_file_url_for_environment(
4036
						'_inc/build/jetpack-deactivate-dialog.min.js',
4037
						'_inc/jetpack-deactivate-dialog.js'
4038
					),
4039
					array( 'jquery', 'jp-tracks-functions' ),
4040
					JETPACK__VERSION,
4041
					true
4042
				);
4043
4044
				wp_localize_script(
4045
					'jetpack-deactivate-dialog-js',
4046
					'deactivate_dialog',
4047
					array(
4048
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4049
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4050
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4051
					)
4052
				);
4053
4054
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4055
4056
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4057
			}
4058
		}
4059
	}
4060
4061
	/**
4062
	 * Outputs the content of the deactivation modal
4063
	 *
4064
	 * @return void
4065
	 */
4066
	public function deactivate_dialog_content() {
4067
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4068
		unset( $active_plugins_using_connection['jetpack'] );
4069
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
It seems like $active_plugins_using_connection defined by \Automattic\Jetpack\Conn...ugin_Storage::get_all() on line 4067 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...
4070
	}
4071
4072
	/**
4073
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4074
	 *
4075
	 * @param string $login_url The wp-login URL.
4076
	 * @param string $redirect  URL to redirect users after logging in.
4077
	 * @since Jetpack 8.4
4078
	 * @return string
4079
	 */
4080
	public function login_url( $login_url, $redirect ) {
4081
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
4082
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4083
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4084
		}
4085
		return $login_url;
4086
	}
4087
4088
	/**
4089
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4090
	 *
4091
	 * @since Jetpack 8.4
4092
	 */
4093
	public function login_init() {
4094
		// phpcs:ignore WordPress.Security.NonceVerification
4095
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4096
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4097
			wp_safe_redirect(
4098
				add_query_arg(
4099
					array(
4100
						'forceInstall' => 1,
4101
						'url'          => rawurlencode( get_site_url() ),
4102
					),
4103
					// @todo provide way to go to specific calypso env.
4104
					self::get_calypso_host() . 'jetpack/connect'
4105
				)
4106
			);
4107
			exit;
4108
		}
4109
	}
4110
4111
	/*
4112
	 * Registration flow:
4113
	 * 1 - ::admin_page_load() action=register
4114
	 * 2 - ::try_registration()
4115
	 * 3 - ::register()
4116
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4117
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4118
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4119
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4120
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4121
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4122
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4123
	 *       jetpack_id, jetpack_secret, jetpack_public
4124
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4125
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4126
	 * 5 - user logs in with WP.com account
4127
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4128
	 *		- Manager::authorize()
4129
	 *		- Manager::get_token()
4130
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4131
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4132
	 *			- which responds with access_token, token_type, scope
4133
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4134
	 *		- Jetpack::activate_default_modules()
4135
	 *     		- Deactivates deprecated plugins
4136
	 *     		- Activates all default modules
4137
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4138
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4139
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4140
	 *     Done!
4141
	 */
4142
4143
	/**
4144
	 * Handles the page load events for the Jetpack admin page
4145
	 */
4146
	function admin_page_load() {
4147
		$error = false;
4148
4149
		// Make sure we have the right body class to hook stylings for subpages off of.
4150
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4151
4152
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4153
			// Should only be used in intermediate redirects to preserve state across redirects
4154
			self::restate();
4155
		}
4156
4157
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4158
			// @todo: Add validation against a known allowed list.
4159
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4160
			// User clicked in the iframe to link their accounts
4161
			if ( ! self::is_user_connected() ) {
4162
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4163
4164
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4165
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4166
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4167
4168
				if ( isset( $_GET['notes_iframe'] ) ) {
4169
					$connect_url .= '&notes_iframe';
4170
				}
4171
				wp_redirect( $connect_url );
4172
				exit;
4173
			} else {
4174
				if ( ! isset( $_GET['calypso_env'] ) ) {
4175
					self::state( 'message', 'already_authorized' );
4176
					wp_safe_redirect( self::admin_url() );
4177
					exit;
4178
				} else {
4179
					$connect_url  = $this->build_connect_url( true, false, $from );
4180
					$connect_url .= '&already_authorized=true';
4181
					wp_redirect( $connect_url );
4182
					exit;
4183
				}
4184
			}
4185
		}
4186
4187
		if ( isset( $_GET['action'] ) ) {
4188
			switch ( $_GET['action'] ) {
4189
				case 'authorize':
4190
					if ( self::is_active() && self::is_user_connected() ) {
4191
						self::state( 'message', 'already_authorized' );
4192
						wp_safe_redirect( self::admin_url() );
4193
						exit;
4194
					}
4195
					self::log( 'authorize' );
4196
					$client_server = new Jetpack_Client_Server();
4197
					$client_server->client_authorize();
4198
					exit;
4199
				case 'register':
4200
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4201
						$error = 'cheatin';
4202
						break;
4203
					}
4204
					check_admin_referer( 'jetpack-register' );
4205
					self::log( 'register' );
4206
					self::maybe_set_version_option();
4207
					$registered = self::try_registration();
4208 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4209
						$error = $registered->get_error_code();
0 ignored issues
show
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...
4210
						self::state( 'error', $error );
4211
						self::state( 'error', $registered->get_error_message() );
0 ignored issues
show
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...
4212
4213
						/**
4214
						 * Jetpack registration Error.
4215
						 *
4216
						 * @since 7.5.0
4217
						 *
4218
						 * @param string|int $error The error code.
4219
						 * @param \WP_Error $registered The error object.
4220
						 */
4221
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4222
						break;
4223
					}
4224
4225
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4226
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4227
4228
					/**
4229
					 * Jetpack registration Success.
4230
					 *
4231
					 * @since 7.5.0
4232
					 *
4233
					 * @param string $from 'from' GET parameter;
4234
					 */
4235
					do_action( 'jetpack_connection_register_success', $from );
4236
4237
					$url = $this->build_connect_url( true, $redirect, $from );
4238
4239
					if ( ! empty( $_GET['onboarding'] ) ) {
4240
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4241
					}
4242
4243
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4244
						$url = add_query_arg( 'auth_approved', 'true', $url );
4245
					}
4246
4247
					wp_redirect( $url );
4248
					exit;
4249
				case 'activate':
4250
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4251
						$error = 'cheatin';
4252
						break;
4253
					}
4254
4255
					$module = stripslashes( $_GET['module'] );
4256
					check_admin_referer( "jetpack_activate-$module" );
4257
					self::log( 'activate', $module );
4258
					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...
4259
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4260
					}
4261
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4262
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4263
					exit;
4264
				case 'activate_default_modules':
4265
					check_admin_referer( 'activate_default_modules' );
4266
					self::log( 'activate_default_modules' );
4267
					self::restate();
4268
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4269
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4270
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4271
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4272
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4273
					exit;
4274
				case 'disconnect':
4275
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4276
						$error = 'cheatin';
4277
						break;
4278
					}
4279
4280
					check_admin_referer( 'jetpack-disconnect' );
4281
					self::log( 'disconnect' );
4282
					self::disconnect();
4283
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4284
					exit;
4285
				case 'reconnect':
4286
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4287
						$error = 'cheatin';
4288
						break;
4289
					}
4290
4291
					check_admin_referer( 'jetpack-reconnect' );
4292
					self::log( 'reconnect' );
4293
					$this->disconnect();
4294
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4295
					exit;
4296 View Code Duplication
				case 'deactivate':
4297
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4298
						$error = 'cheatin';
4299
						break;
4300
					}
4301
4302
					$modules = stripslashes( $_GET['module'] );
4303
					check_admin_referer( "jetpack_deactivate-$modules" );
4304
					foreach ( explode( ',', $modules ) as $module ) {
4305
						self::log( 'deactivate', $module );
4306
						self::deactivate_module( $module );
4307
						self::state( 'message', 'module_deactivated' );
4308
					}
4309
					self::state( 'module', $modules );
4310
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4311
					exit;
4312
				case 'unlink':
4313
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4314
					check_admin_referer( 'jetpack-unlink' );
4315
					self::log( 'unlink' );
4316
					Connection_Manager::disconnect_user();
4317
					self::state( 'message', 'unlinked' );
4318
					if ( 'sub-unlink' == $redirect ) {
4319
						wp_safe_redirect( admin_url() );
4320
					} else {
4321
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4322
					}
4323
					exit;
4324
				case 'onboard':
4325
					if ( ! current_user_can( 'manage_options' ) ) {
4326
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4327
					} else {
4328
						self::create_onboarding_token();
4329
						$url = $this->build_connect_url( true );
4330
4331
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4332
							$url = add_query_arg( 'onboarding', $token, $url );
4333
						}
4334
4335
						$calypso_env = $this->get_calypso_env();
4336
						if ( ! empty( $calypso_env ) ) {
4337
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4338
						}
4339
4340
						wp_redirect( $url );
4341
						exit;
4342
					}
4343
					exit;
4344
				default:
4345
					/**
4346
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4347
					 *
4348
					 * @since 2.6.0
4349
					 *
4350
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4351
					 */
4352
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4353
			}
4354
		}
4355
4356
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4357
			self::activate_new_modules( true );
4358
		}
4359
4360
		$message_code = self::state( 'message' );
4361
		if ( self::state( 'optin-manage' ) ) {
4362
			$activated_manage = $message_code;
4363
			$message_code     = 'jetpack-manage';
4364
		}
4365
4366
		switch ( $message_code ) {
4367
			case 'jetpack-manage':
4368
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4369
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4370
				$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>';
4371
				if ( $activated_manage ) {
0 ignored issues
show
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...
4372
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4373
				}
4374
				break;
4375
4376
		}
4377
4378
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4379
4380
		if ( ! empty( $deactivated_plugins ) ) {
4381
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4382
			$deactivated_titles  = array();
4383
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4384
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4385
					continue;
4386
				}
4387
4388
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4389
			}
4390
4391
			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...
4392
				if ( $this->message ) {
4393
					$this->message .= "<br /><br />\n";
4394
				}
4395
4396
				$this->message .= wp_sprintf(
4397
					_n(
4398
						'Jetpack contains the most recent version of the old %l plugin.',
4399
						'Jetpack contains the most recent versions of the old %l plugins.',
4400
						count( $deactivated_titles ),
4401
						'jetpack'
4402
					),
4403
					$deactivated_titles
4404
				);
4405
4406
				$this->message .= "<br />\n";
4407
4408
				$this->message .= _n(
4409
					'The old version has been deactivated and can be removed from your site.',
4410
					'The old versions have been deactivated and can be removed from your site.',
4411
					count( $deactivated_titles ),
4412
					'jetpack'
4413
				);
4414
			}
4415
		}
4416
4417
		$this->privacy_checks = self::state( 'privacy_checks' );
4418
4419
		if ( $this->message || $this->error || $this->privacy_checks ) {
4420
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4421
		}
4422
4423
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4424
	}
4425
4426
	function admin_notices() {
4427
4428
		if ( $this->error ) {
4429
			?>
4430
<div id="message" class="jetpack-message jetpack-err">
4431
	<div class="squeezer">
4432
		<h2>
4433
			<?php
4434
			echo wp_kses(
4435
				$this->error,
4436
				array(
4437
					'a'      => array( 'href' => array() ),
4438
					'small'  => true,
4439
					'code'   => true,
4440
					'strong' => true,
4441
					'br'     => true,
4442
					'b'      => true,
4443
				)
4444
			);
4445
			?>
4446
			</h2>
4447
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4448
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4449
<?php	endif; ?>
4450
	</div>
4451
</div>
4452
			<?php
4453
		}
4454
4455
		if ( $this->message ) {
4456
			?>
4457
<div id="message" class="jetpack-message">
4458
	<div class="squeezer">
4459
		<h2>
4460
			<?php
4461
			echo wp_kses(
4462
				$this->message,
4463
				array(
4464
					'strong' => array(),
4465
					'a'      => array( 'href' => true ),
4466
					'br'     => true,
4467
				)
4468
			);
4469
			?>
4470
			</h2>
4471
	</div>
4472
</div>
4473
			<?php
4474
		}
4475
4476
		if ( $this->privacy_checks ) :
4477
			$module_names = $module_slugs = array();
4478
4479
			$privacy_checks = explode( ',', $this->privacy_checks );
4480
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4481
			foreach ( $privacy_checks as $module_slug ) {
4482
				$module = self::get_module( $module_slug );
4483
				if ( ! $module ) {
4484
					continue;
4485
				}
4486
4487
				$module_slugs[] = $module_slug;
4488
				$module_names[] = "<strong>{$module['name']}</strong>";
4489
			}
4490
4491
			$module_slugs = join( ',', $module_slugs );
4492
			?>
4493
<div id="message" class="jetpack-message jetpack-err">
4494
	<div class="squeezer">
4495
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4496
		<p>
4497
			<?php
4498
			echo wp_kses(
4499
				wptexturize(
4500
					wp_sprintf(
4501
						_nx(
4502
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4503
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4504
							count( $privacy_checks ),
4505
							'%l = list of Jetpack module/feature names',
4506
							'jetpack'
4507
						),
4508
						$module_names
4509
					)
4510
				),
4511
				array( 'strong' => true )
4512
			);
4513
4514
			echo "\n<br />\n";
4515
4516
			echo wp_kses(
4517
				sprintf(
4518
					_nx(
4519
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4520
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4521
						count( $privacy_checks ),
4522
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4523
						'jetpack'
4524
					),
4525
					wp_nonce_url(
4526
						self::admin_url(
4527
							array(
4528
								'page'   => 'jetpack',
4529
								'action' => 'deactivate',
4530
								'module' => urlencode( $module_slugs ),
4531
							)
4532
						),
4533
						"jetpack_deactivate-$module_slugs"
4534
					),
4535
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4536
				),
4537
				array(
4538
					'a' => array(
4539
						'href'  => true,
4540
						'title' => true,
4541
					),
4542
				)
4543
			);
4544
			?>
4545
		</p>
4546
	</div>
4547
</div>
4548
			<?php
4549
endif;
4550
	}
4551
4552
	/**
4553
	 * We can't always respond to a signed XML-RPC request with a
4554
	 * helpful error message. In some circumstances, doing so could
4555
	 * leak information.
4556
	 *
4557
	 * Instead, track that the error occurred via a Jetpack_Option,
4558
	 * and send that data back in the heartbeat.
4559
	 * All this does is increment a number, but it's enough to find
4560
	 * trends.
4561
	 *
4562
	 * @param WP_Error $xmlrpc_error The error produced during
4563
	 *                               signature validation.
4564
	 */
4565
	function track_xmlrpc_error( $xmlrpc_error ) {
4566
		$code = is_wp_error( $xmlrpc_error )
4567
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
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...
4568
			: 'should-not-happen';
4569
4570
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4571
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4572
			// No need to update the option if we already have
4573
			// this code stored.
4574
			return;
4575
		}
4576
		$xmlrpc_errors[ $code ] = true;
4577
4578
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
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...
4579
	}
4580
4581
	/**
4582
	 * Initialize the jetpack stats instance only when needed
4583
	 *
4584
	 * @return void
4585
	 */
4586
	private function initialize_stats() {
4587
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4588
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4589
		}
4590
	}
4591
4592
	/**
4593
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4594
	 */
4595
	function stat( $group, $detail ) {
4596
		$this->initialize_stats();
4597
		$this->a8c_mc_stats_instance->add( $group, $detail );
4598
4599
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4600
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4601
	}
4602
4603
	/**
4604
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4605
	 */
4606
	function do_stats( $method = '' ) {
4607
		$this->initialize_stats();
4608
		if ( 'server_side' === $method ) {
4609
			$this->a8c_mc_stats_instance->do_server_side_stats();
4610
		} else {
4611
			$this->a8c_mc_stats_instance->do_stats();
4612
		}
4613
4614
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4615
		$this->stats = array();
4616
	}
4617
4618
	/**
4619
	 * Runs stats code for a one-off, server-side.
4620
	 *
4621
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4622
	 *
4623
	 * @return bool If it worked.
4624
	 */
4625
	static function do_server_side_stat( $args ) {
4626
		$url                   = self::build_stats_url( $args );
4627
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4628
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4629
	}
4630
4631
	/**
4632
	 * Builds the stats url.
4633
	 *
4634
	 * @param $args array|string The arguments to append to the URL.
4635
	 *
4636
	 * @return string The URL to be pinged.
4637
	 */
4638
	static function build_stats_url( $args ) {
4639
4640
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4641
		return $a8c_mc_stats_instance->build_stats_url( $args );
4642
4643
	}
4644
4645
	/**
4646
	 * Get the role of the current user.
4647
	 *
4648
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4649
	 *
4650
	 * @access public
4651
	 * @static
4652
	 *
4653
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4654
	 */
4655
	public static function translate_current_user_to_role() {
4656
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4657
4658
		$roles = new Roles();
4659
		return $roles->translate_current_user_to_role();
4660
	}
4661
4662
	/**
4663
	 * Get the role of a particular user.
4664
	 *
4665
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4666
	 *
4667
	 * @access public
4668
	 * @static
4669
	 *
4670
	 * @param \WP_User $user User object.
4671
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4672
	 */
4673
	public static function translate_user_to_role( $user ) {
4674
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4675
4676
		$roles = new Roles();
4677
		return $roles->translate_user_to_role( $user );
4678
	}
4679
4680
	/**
4681
	 * Get the minimum capability for a role.
4682
	 *
4683
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4684
	 *
4685
	 * @access public
4686
	 * @static
4687
	 *
4688
	 * @param string $role Role name.
4689
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4690
	 */
4691
	public static function translate_role_to_cap( $role ) {
4692
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4693
4694
		$roles = new Roles();
4695
		return $roles->translate_role_to_cap( $role );
4696
	}
4697
4698
	/**
4699
	 * Sign a user role with the master access token.
4700
	 * If not specified, will default to the current user.
4701
	 *
4702
	 * @deprecated since 7.7
4703
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4704
	 *
4705
	 * @access public
4706
	 * @static
4707
	 *
4708
	 * @param string $role    User role.
4709
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
4710
	 * @return string Signed user role.
4711
	 */
4712
	public static function sign_role( $role, $user_id = null ) {
4713
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4714
		return self::connection()->sign_role( $role, $user_id );
4715
	}
4716
4717
	/**
4718
	 * Builds a URL to the Jetpack connection auth page
4719
	 *
4720
	 * @since 3.9.5
4721
	 *
4722
	 * @param bool        $raw If true, URL will not be escaped.
4723
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4724
	 *                              If string, will be a custom redirect.
4725
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4726
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4727
	 *
4728
	 * @return string Connect URL
4729
	 */
4730
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4731
		$site_id    = Jetpack_Options::get_option( 'id' );
4732
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4733
4734
		if ( $register || ! $blog_token || ! $site_id ) {
4735
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4736
4737
			if ( ! empty( $redirect ) ) {
4738
				$url = add_query_arg(
4739
					'redirect',
4740
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4741
					$url
4742
				);
4743
			}
4744
4745
			if ( is_network_admin() ) {
4746
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4747
			}
4748
4749
			$calypso_env = self::get_calypso_env();
4750
4751
			if ( ! empty( $calypso_env ) ) {
4752
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4753
			}
4754
		} else {
4755
4756
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4757
			// because otherwise this logic can get us in to a loop.
4758
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4759
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4760
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4761
4762
				$response = Client::wpcom_json_api_request_as_blog(
4763
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4764
					'1.1'
4765
				);
4766
4767
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4768
4769
					// Generating a register URL instead to refresh the existing token
4770
					return $this->build_connect_url( $raw, $redirect, $from, true );
4771
				}
4772
			}
4773
4774
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4730 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...
4775
		}
4776
4777
		if ( $from ) {
4778
			$url = add_query_arg( 'from', $from, $url );
4779
		}
4780
4781
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4782
		/**
4783
		 * Filter the URL used when connecting a user to a WordPress.com account.
4784
		 *
4785
		 * @since 8.1.0
4786
		 *
4787
		 * @param string $url Connection URL.
4788
		 * @param bool   $raw If true, URL will not be escaped.
4789
		 */
4790
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
0 ignored issues
show
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...
4791
	}
4792
4793
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4794
4795
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4796
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4797
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4798
4799
		if ( $iframe ) {
4800
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4801
		}
4802
4803
		$c8n = self::connection();
4804
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
$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...
4805
4806
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4807
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4808
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4809
4810
		if ( $iframe ) {
4811
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4812
		}
4813
4814
		/**
4815
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4816
		 *
4817
		 * @since 8.9.0
4818
		 *
4819
		 * @param string $url Connection URL.
4820
		 */
4821
		return apply_filters( 'jetpack_build_authorize_url', $url );
4822
	}
4823
4824
	/**
4825
	 * Filters the connection URL parameter array.
4826
	 *
4827
	 * @param array $args default URL parameters used by the package.
4828
	 * @return array the modified URL arguments array.
4829
	 */
4830
	public static function filter_connect_request_body( $args ) {
4831
		if (
4832
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4833
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4834
		) {
4835
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4836
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4837
				? $gp_locale->slug
4838
				: '';
4839
		}
4840
4841
		$tracking        = new Tracking();
4842
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4843
4844
		$args = array_merge(
4845
			$args,
4846
			array(
4847
				'_ui' => $tracks_identity['_ui'],
4848
				'_ut' => $tracks_identity['_ut'],
4849
			)
4850
		);
4851
4852
		$calypso_env = self::get_calypso_env();
4853
4854
		if ( ! empty( $calypso_env ) ) {
4855
			$args['calypso_env'] = $calypso_env;
4856
		}
4857
4858
		return $args;
4859
	}
4860
4861
	/**
4862
	 * Filters the URL that will process the connection data. It can be different from the URL
4863
	 * that we send the user to after everything is done.
4864
	 *
4865
	 * @param String $processing_url the default redirect URL used by the package.
4866
	 * @return String the modified URL.
4867
	 */
4868
	public static function filter_connect_processing_url( $processing_url ) {
4869
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4870
		return $processing_url;
4871
	}
4872
4873
	/**
4874
	 * Filters the redirection URL that is used for connect requests. The redirect
4875
	 * URL should return the user back to the Jetpack console.
4876
	 *
4877
	 * @param String $redirect the default redirect URL used by the package.
4878
	 * @return String the modified URL.
4879
	 */
4880
	public static function filter_connect_redirect_url( $redirect ) {
4881
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4882
		$redirect           = $redirect
4883
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4884
			: $jetpack_admin_page;
4885
4886
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4887
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4888
		}
4889
4890
		return $redirect;
4891
	}
4892
4893
	/**
4894
	 * This action fires at the beginning of the Manager::authorize method.
4895
	 */
4896
	public static function authorize_starting() {
4897
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4898
		// Checking if site has been active/connected previously before recording unique connection.
4899
		if ( ! $jetpack_unique_connection ) {
4900
			// jetpack_unique_connection option has never been set.
4901
			$jetpack_unique_connection = array(
4902
				'connected'    => 0,
4903
				'disconnected' => 0,
4904
				'version'      => '3.6.1',
4905
			);
4906
4907
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4908
4909
			// Track unique connection.
4910
			$jetpack = self::init();
4911
4912
			$jetpack->stat( 'connections', 'unique-connection' );
4913
			$jetpack->do_stats( 'server_side' );
4914
		}
4915
4916
		// Increment number of times connected.
4917
		$jetpack_unique_connection['connected'] += 1;
4918
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4919
	}
4920
4921
	/**
4922
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4923
	 * linked.
4924
	 */
4925
	public static function authorize_ending_linked() {
4926
		// Don't activate anything since we are just connecting a user.
4927
		self::state( 'message', 'linked' );
4928
	}
4929
4930
	/**
4931
	 * This action fires at the end of the Manager::authorize method when the master user is
4932
	 * authorized.
4933
	 *
4934
	 * @param array $data The request data.
4935
	 */
4936
	public static function authorize_ending_authorized( $data ) {
4937
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4938
		self::invalidate_onboarding_token();
4939
4940
		// If redirect_uri is SSO, ensure SSO module is enabled.
4941
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
4942
4943
		/** This filter is documented in class.jetpack-cli.php */
4944
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4945
4946
		$activate_sso = (
4947
			isset( $redirect_options['action'] ) &&
4948
			'jetpack-sso' === $redirect_options['action'] &&
4949
			$jetpack_start_enable_sso
4950
		);
4951
4952
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4953
4954
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4955
	}
4956
4957
	/**
4958
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
4959
	 * reconnect process is completed.
4960
	 * Note that this currently only happens when we don't need the user to re-authorize
4961
	 * their WP.com account, eg in cases where we are restoring a connection with
4962
	 * unhealthy blog token.
4963
	 */
4964
	public static function reconnection_completed() {
4965
		self::state( 'message', 'reconnection_completed' );
4966
	}
4967
4968
	/**
4969
	 * Get our assumed site creation date.
4970
	 * Calculated based on the earlier date of either:
4971
	 * - Earliest admin user registration date.
4972
	 * - Earliest date of post of any post type.
4973
	 *
4974
	 * @since 7.2.0
4975
	 * @deprecated since 7.8.0
4976
	 *
4977
	 * @return string Assumed site creation date and time.
4978
	 */
4979
	public static function get_assumed_site_creation_date() {
4980
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4981
		return self::connection()->get_assumed_site_creation_date();
4982
	}
4983
4984 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4985
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4986
4987
		if ( $activation_source_name ) {
4988
			$args['_as'] = urlencode( $activation_source_name );
4989
		}
4990
4991
		if ( $activation_source_keyword ) {
4992
			$args['_ak'] = urlencode( $activation_source_keyword );
4993
		}
4994
	}
4995
4996
	function build_reconnect_url( $raw = false ) {
4997
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4998
		return $raw ? $url : esc_url( $url );
4999
	}
5000
5001
	public static function admin_url( $args = null ) {
5002
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
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...
5003
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5004
		return $url;
5005
	}
5006
5007
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5008
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5009
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5010
	}
5011
5012
	function dismiss_jetpack_notice() {
5013
5014
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5015
			return;
5016
		}
5017
5018
		switch ( $_GET['jetpack-notice'] ) {
5019
			case 'dismiss':
5020
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5021
5022
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5023
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5024
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5025
				}
5026
				break;
5027
		}
5028
	}
5029
5030
	public static function sort_modules( $a, $b ) {
5031
		if ( $a['sort'] == $b['sort'] ) {
5032
			return 0;
5033
		}
5034
5035
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5036
	}
5037
5038
	function ajax_recheck_ssl() {
5039
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5040
		$result = self::permit_ssl( true );
5041
		wp_send_json(
5042
			array(
5043
				'enabled' => $result,
5044
				'message' => get_transient( 'jetpack_https_test_message' ),
5045
			)
5046
		);
5047
	}
5048
5049
	/* Client API */
5050
5051
	/**
5052
	 * Returns the requested Jetpack API URL
5053
	 *
5054
	 * @deprecated since 7.7
5055
	 * @return string
5056
	 */
5057
	public static function api_url( $relative_url ) {
5058
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5059
		$connection = self::connection();
5060
		return $connection->api_url( $relative_url );
5061
	}
5062
5063
	/**
5064
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5065
	 *
5066
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5067
	 */
5068
	public static function fix_url_for_bad_hosts( $url ) {
5069
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5070
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5071
	}
5072
5073
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5074
		// Default to a blog token.
5075
		$token_type = 'blog';
5076
5077
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5078
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5079
			if ( ! empty( $_GET['onboarding'] ) ) {
5080
				$jpo = $_GET;
5081
			} else {
5082
				$jpo = json_decode( $request_data, true );
5083
			}
5084
5085
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5086
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5087
5088
			if (
5089
				isset( $jpo_user )
5090
				&& isset( $jpo_token )
5091
				&& is_email( $jpo_user )
5092
				&& ctype_alnum( $jpo_token )
5093
				&& isset( $_GET['rest_route'] )
5094
				&& self::validate_onboarding_token_action(
5095
					$jpo_token,
5096
					$_GET['rest_route']
5097
				)
5098
			) {
5099
				$jp_user = get_user_by( 'email', $jpo_user );
5100
				if ( is_a( $jp_user, 'WP_User' ) ) {
5101
					wp_set_current_user( $jp_user->ID );
5102
					$user_can = is_multisite()
5103
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5104
						: current_user_can( 'manage_options' );
5105
					if ( $user_can ) {
5106
						$token_type              = 'user';
5107
						$token->external_user_id = $jp_user->ID;
5108
					}
5109
				}
5110
			}
5111
5112
			$token_data['type']    = $token_type;
5113
			$token_data['user_id'] = $token->external_user_id;
5114
		}
5115
5116
		return $token_data;
5117
	}
5118
5119
	/**
5120
	 * Create a random secret for validating onboarding payload
5121
	 *
5122
	 * @return string Secret token
5123
	 */
5124
	public static function create_onboarding_token() {
5125
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5126
			$token = wp_generate_password( 32, false );
5127
			Jetpack_Options::update_option( 'onboarding', $token );
5128
		}
5129
5130
		return $token;
5131
	}
5132
5133
	/**
5134
	 * Remove the onboarding token
5135
	 *
5136
	 * @return bool True on success, false on failure
5137
	 */
5138
	public static function invalidate_onboarding_token() {
5139
		return Jetpack_Options::delete_option( 'onboarding' );
5140
	}
5141
5142
	/**
5143
	 * Validate an onboarding token for a specific action
5144
	 *
5145
	 * @return boolean True if token/action pair is accepted, false if not
5146
	 */
5147
	public static function validate_onboarding_token_action( $token, $action ) {
5148
		// Compare tokens, bail if tokens do not match
5149
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5150
			return false;
5151
		}
5152
5153
		// List of valid actions we can take
5154
		$valid_actions = array(
5155
			'/jetpack/v4/settings',
5156
		);
5157
5158
		// Only allow valid actions.
5159
		if ( ! in_array( $action, $valid_actions ) ) {
5160
			return false;
5161
		}
5162
5163
		return true;
5164
	}
5165
5166
	/**
5167
	 * Checks to see if the URL is using SSL to connect with Jetpack
5168
	 *
5169
	 * @since 2.3.3
5170
	 * @return boolean
5171
	 */
5172
	public static function permit_ssl( $force_recheck = false ) {
5173
		// Do some fancy tests to see if ssl is being supported
5174
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5175
			$message = '';
5176
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5177
				$ssl = 0;
5178
			} else {
5179
				switch ( JETPACK_CLIENT__HTTPS ) {
5180
					case 'NEVER':
5181
						$ssl     = 0;
5182
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5183
						break;
5184
					case 'ALWAYS':
5185
					case 'AUTO':
5186
					default:
5187
						$ssl = 1;
5188
						break;
5189
				}
5190
5191
				// If it's not 'NEVER', test to see
5192
				if ( $ssl ) {
5193
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5194
						$ssl     = 0;
5195
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5196
					} else {
5197
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5198
						if ( is_wp_error( $response ) ) {
5199
							$ssl     = 0;
5200
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5201
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5202
							$ssl     = 0;
5203
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5204
						}
5205
					}
5206
				}
5207
			}
5208
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5209
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5210
		}
5211
5212
		return (bool) $ssl;
5213
	}
5214
5215
	/*
5216
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5217
	 */
5218
	public function alert_auto_ssl_fail() {
5219
		if ( ! current_user_can( 'manage_options' ) ) {
5220
			return;
5221
		}
5222
5223
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5224
		?>
5225
5226
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5227
			<div class="jp-banner__content">
5228
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5229
				<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>
5230
				<p>
5231
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5232
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5233
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5234
				</p>
5235
				<p>
5236
					<?php
5237
					printf(
5238
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5239
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5240
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5241
					);
5242
					?>
5243
				</p>
5244
			</div>
5245
		</div>
5246
		<style>
5247
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5248
		</style>
5249
		<script type="text/javascript">
5250
			jQuery( document ).ready( function( $ ) {
5251
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5252
					var $this = $( this );
5253
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5254
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5255
					e.preventDefault();
5256
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5257
					$.post( ajaxurl, data )
5258
					  .done( function( response ) {
5259
						  if ( response.enabled ) {
5260
							  $( '#jetpack-ssl-warning' ).hide();
5261
						  } else {
5262
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5263
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5264
						  }
5265
					  }.bind( $this ) );
5266
				} );
5267
			} );
5268
		</script>
5269
5270
		<?php
5271
	}
5272
5273
	/**
5274
	 * Returns the Jetpack XML-RPC API
5275
	 *
5276
	 * @deprecated 8.0 Use Connection_Manager instead.
5277
	 * @return string
5278
	 */
5279
	public static function xmlrpc_api_url() {
5280
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5281
		return self::connection()->xmlrpc_api_url();
5282
	}
5283
5284
	/**
5285
	 * Returns the connection manager object.
5286
	 *
5287
	 * @return Automattic\Jetpack\Connection\Manager
5288
	 */
5289
	public static function connection() {
5290
		$jetpack = static::init();
5291
5292
		// If the connection manager hasn't been instantiated, do that now.
5293
		if ( ! $jetpack->connection_manager ) {
5294
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5295
		}
5296
5297
		return $jetpack->connection_manager;
5298
	}
5299
5300
	/**
5301
	 * Creates two secret tokens and the end of life timestamp for them.
5302
	 *
5303
	 * Note these tokens are unique per call, NOT static per site for connecting.
5304
	 *
5305
	 * @since 2.6
5306
	 * @param String  $action  The action name.
5307
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
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...
5308
	 * @param Integer $exp     Expiration time in seconds.
5309
	 * @return array
5310
	 */
5311
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5312
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5313
	}
5314
5315
	public static function get_secrets( $action, $user_id ) {
5316
		$secrets = self::connection()->get_secrets( $action, $user_id );
5317
5318
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5319
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
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...
5320
		}
5321
5322
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5323
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
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...
5324
		}
5325
5326
		return $secrets;
5327
	}
5328
5329
	/**
5330
	 * @deprecated 7.5 Use Connection_Manager instead.
5331
	 *
5332
	 * @param $action
5333
	 * @param $user_id
5334
	 */
5335
	public static function delete_secrets( $action, $user_id ) {
5336
		return self::connection()->delete_secrets( $action, $user_id );
5337
	}
5338
5339
	/**
5340
	 * Builds the timeout limit for queries talking with the wpcom servers.
5341
	 *
5342
	 * Based on local php max_execution_time in php.ini
5343
	 *
5344
	 * @since 2.6
5345
	 * @return int
5346
	 * @deprecated
5347
	 **/
5348
	public function get_remote_query_timeout_limit() {
5349
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5350
		return self::get_max_execution_time();
5351
	}
5352
5353
	/**
5354
	 * Builds the timeout limit for queries talking with the wpcom servers.
5355
	 *
5356
	 * Based on local php max_execution_time in php.ini
5357
	 *
5358
	 * @since 5.4
5359
	 * @return int
5360
	 **/
5361
	public static function get_max_execution_time() {
5362
		$timeout = (int) ini_get( 'max_execution_time' );
5363
5364
		// Ensure exec time set in php.ini
5365
		if ( ! $timeout ) {
5366
			$timeout = 30;
5367
		}
5368
		return $timeout;
5369
	}
5370
5371
	/**
5372
	 * Sets a minimum request timeout, and returns the current timeout
5373
	 *
5374
	 * @since 5.4
5375
	 **/
5376 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5377
		$timeout = self::get_max_execution_time();
5378
		if ( $timeout < $min_timeout ) {
5379
			$timeout = $min_timeout;
5380
			set_time_limit( $timeout );
5381
		}
5382
		return $timeout;
5383
	}
5384
5385
	/**
5386
	 * Takes the response from the Jetpack register new site endpoint and
5387
	 * verifies it worked properly.
5388
	 *
5389
	 * @since 2.6
5390
	 * @deprecated since 7.7.0
5391
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5392
	 **/
5393
	public function validate_remote_register_response() {
5394
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5395
	}
5396
5397
	/**
5398
	 * @return bool|WP_Error
5399
	 */
5400
	public static function register() {
5401
		$tracking = new Tracking();
5402
		$tracking->record_user_event( 'jpc_register_begin' );
5403
5404
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5405
5406
		$connection   = self::connection();
5407
		$registration = $connection->register();
5408
5409
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5410
5411
		if ( ! $registration || is_wp_error( $registration ) ) {
5412
			return $registration;
5413
		}
5414
5415
		return true;
5416
	}
5417
5418
	/**
5419
	 * Filters the registration request body to include tracking properties.
5420
	 *
5421
	 * @param array $properties
5422
	 * @return array amended properties.
5423
	 */
5424 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5425
		$tracking        = new Tracking();
5426
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5427
5428
		return array_merge(
5429
			$properties,
5430
			array(
5431
				'_ui' => $tracks_identity['_ui'],
5432
				'_ut' => $tracks_identity['_ut'],
5433
			)
5434
		);
5435
	}
5436
5437
	/**
5438
	 * Filters the token request body to include tracking properties.
5439
	 *
5440
	 * @param array $properties
5441
	 * @return array amended properties.
5442
	 */
5443 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5444
		$tracking        = new Tracking();
5445
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5446
5447
		return array_merge(
5448
			$properties,
5449
			array(
5450
				'_ui' => $tracks_identity['_ui'],
5451
				'_ut' => $tracks_identity['_ut'],
5452
			)
5453
		);
5454
	}
5455
5456
	/**
5457
	 * If the db version is showing something other that what we've got now, bump it to current.
5458
	 *
5459
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
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...
5460
	 */
5461
	public static function maybe_set_version_option() {
5462
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5463
		if ( JETPACK__VERSION != $version ) {
5464
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5465
5466
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5467
				/** This action is documented in class.jetpack.php */
5468
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5469
			}
5470
5471
			return true;
5472
		}
5473
		return false;
5474
	}
5475
5476
	/* Client Server API */
5477
5478
	/**
5479
	 * Loads the Jetpack XML-RPC client.
5480
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5481
	 *
5482
	 * @deprecated since 7.7.0
5483
	 */
5484
	public static function load_xml_rpc_client() {
5485
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5486
	}
5487
5488
	/**
5489
	 * Resets the saved authentication state in between testing requests.
5490
	 *
5491
	 * @deprecated since 8.9.0
5492
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5493
	 */
5494
	public function reset_saved_auth_state() {
5495
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5496
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5497
	}
5498
5499
	/**
5500
	 * Verifies the signature of the current request.
5501
	 *
5502
	 * @deprecated since 7.7.0
5503
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5504
	 *
5505
	 * @return false|array
5506
	 */
5507
	public function verify_xml_rpc_signature() {
5508
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5509
		return self::connection()->verify_xml_rpc_signature();
5510
	}
5511
5512
	/**
5513
	 * Verifies the signature of the current request.
5514
	 *
5515
	 * This function has side effects and should not be used. Instead,
5516
	 * use the memoized version `->verify_xml_rpc_signature()`.
5517
	 *
5518
	 * @deprecated since 7.7.0
5519
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5520
	 * @internal
5521
	 */
5522
	private function internal_verify_xml_rpc_signature() {
5523
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5524
	}
5525
5526
	/**
5527
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5528
	 *
5529
	 * @deprecated since 7.7.0
5530
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5531
	 *
5532
	 * @param \WP_User|mixed $user     User object if authenticated.
5533
	 * @param string         $username Username.
5534
	 * @param string         $password Password string.
5535
	 * @return \WP_User|mixed Authenticated user or error.
5536
	 */
5537 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5538
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5539
5540
		if ( ! $this->connection_manager ) {
5541
			$this->connection_manager = new Connection_Manager();
5542
		}
5543
5544
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5545
	}
5546
5547
	/**
5548
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5549
	 * Uses the existing XMLRPC request signing implementation.
5550
	 *
5551
	 * @deprecated since 8.9.0
5552
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5553
	 */
5554
	function wp_rest_authenticate( $user ) {
5555
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5556
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5557
	}
5558
5559
	/**
5560
	 * Report authentication status to the WP REST API.
5561
	 *
5562
	 * @deprecated since 8.9.0
5563
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5564
	 *
5565
	 * @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
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...
5566
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5567
	 */
5568
	public function wp_rest_authentication_errors( $value ) {
5569
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5570
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5571
	}
5572
5573
	/**
5574
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5575
	 * Capture it here so we can verify the signature later.
5576
	 *
5577
	 * @deprecated since 7.7.0
5578
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5579
	 *
5580
	 * @param array $methods XMLRPC methods.
5581
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5582
	 */
5583 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5584
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5585
5586
		if ( ! $this->connection_manager ) {
5587
			$this->connection_manager = new Connection_Manager();
5588
		}
5589
5590
		return $this->connection_manager->xmlrpc_methods( $methods );
5591
	}
5592
5593
	/**
5594
	 * Register additional public XMLRPC methods.
5595
	 *
5596
	 * @deprecated since 7.7.0
5597
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5598
	 *
5599
	 * @param array $methods Public XMLRPC methods.
5600
	 * @return array Public XMLRPC methods, with the getOptions one.
5601
	 */
5602 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5603
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5604
5605
		if ( ! $this->connection_manager ) {
5606
			$this->connection_manager = new Connection_Manager();
5607
		}
5608
5609
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5610
	}
5611
5612
	/**
5613
	 * Handles a getOptions XMLRPC method call.
5614
	 *
5615
	 * @deprecated since 7.7.0
5616
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5617
	 *
5618
	 * @param array $args method call arguments.
5619
	 * @return array an amended XMLRPC server options array.
5620
	 */
5621 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5622
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5623
5624
		if ( ! $this->connection_manager ) {
5625
			$this->connection_manager = new Connection_Manager();
5626
		}
5627
5628
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
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...
5629
	}
5630
5631
	/**
5632
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5633
	 *
5634
	 * @deprecated since 7.7.0
5635
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5636
	 *
5637
	 * @param array $options Standard Core options.
5638
	 * @return array Amended options.
5639
	 */
5640 View Code Duplication
	public function xmlrpc_options( $options ) {
5641
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5642
5643
		if ( ! $this->connection_manager ) {
5644
			$this->connection_manager = new Connection_Manager();
5645
		}
5646
5647
		return $this->connection_manager->xmlrpc_options( $options );
5648
	}
5649
5650
	/**
5651
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5652
	 * SET: state( $key, $value );
5653
	 * GET: $value = state( $key );
5654
	 *
5655
	 * @param string $key
0 ignored issues
show
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...
5656
	 * @param string $value
0 ignored issues
show
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...
5657
	 * @param bool   $restate private
5658
	 */
5659
	public static function state( $key = null, $value = null, $restate = false ) {
5660
		static $state = array();
5661
		static $path, $domain;
5662
		if ( ! isset( $path ) ) {
5663
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5664
			$admin_url = self::admin_url();
5665
			$bits      = wp_parse_url( $admin_url );
5666
5667
			if ( is_array( $bits ) ) {
5668
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5669
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5670
			} else {
5671
				$path = $domain = null;
5672
			}
5673
		}
5674
5675
		// Extract state from cookies and delete cookies
5676
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5677
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5678
			unset( $_COOKIE['jetpackState'] );
5679
			foreach ( $yum as $k => $v ) {
0 ignored issues
show
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...
5680
				if ( strlen( $v ) ) {
5681
					$state[ $k ] = $v;
5682
				}
5683
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5684
			}
5685
		}
5686
5687
		if ( $restate ) {
5688
			foreach ( $state as $k => $v ) {
5689
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5690
			}
5691
			return;
5692
		}
5693
5694
		// Get a state variable.
5695
		if ( isset( $key ) && ! isset( $value ) ) {
5696
			if ( array_key_exists( $key, $state ) ) {
5697
				return $state[ $key ];
5698
			}
5699
			return null;
5700
		}
5701
5702
		// Set a state variable.
5703
		if ( isset( $key ) && isset( $value ) ) {
5704
			if ( is_array( $value ) && isset( $value[0] ) ) {
5705
				$value = $value[0];
5706
			}
5707
			$state[ $key ] = $value;
5708
			if ( ! headers_sent() ) {
5709
				if ( self::should_set_cookie( $key ) ) {
5710
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5711
				}
5712
			}
5713
		}
5714
	}
5715
5716
	public static function restate() {
5717
		self::state( null, null, true );
5718
	}
5719
5720
	/**
5721
	 * Determines whether the jetpackState[$key] value should be added to the
5722
	 * cookie.
5723
	 *
5724
	 * @param string $key The state key.
5725
	 *
5726
	 * @return boolean Whether the value should be added to the cookie.
5727
	 */
5728
	public static function should_set_cookie( $key ) {
5729
		global $current_screen;
5730
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5731
5732
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5733
			return false;
5734
		}
5735
5736
		return true;
5737
	}
5738
5739
	public static function check_privacy( $file ) {
5740
		static $is_site_publicly_accessible = null;
5741
5742
		if ( is_null( $is_site_publicly_accessible ) ) {
5743
			$is_site_publicly_accessible = false;
5744
5745
			$rpc = new Jetpack_IXR_Client();
5746
5747
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5748
			if ( $success ) {
5749
				$response = $rpc->getResponse();
5750
				if ( $response ) {
5751
					$is_site_publicly_accessible = true;
5752
				}
5753
			}
5754
5755
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5756
		}
5757
5758
		if ( $is_site_publicly_accessible ) {
5759
			return;
5760
		}
5761
5762
		$module_slug = self::get_module_slug( $file );
5763
5764
		$privacy_checks = self::state( 'privacy_checks' );
5765
		if ( ! $privacy_checks ) {
5766
			$privacy_checks = $module_slug;
5767
		} else {
5768
			$privacy_checks .= ",$module_slug";
5769
		}
5770
5771
		self::state( 'privacy_checks', $privacy_checks );
5772
	}
5773
5774
	/**
5775
	 * Helper method for multicall XMLRPC.
5776
	 *
5777
	 * @deprecated since 8.9.0
5778
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5779
	 *
5780
	 * @param ...$args Args for the async_call.
5781
	 */
5782
	public static function xmlrpc_async_call( ...$args ) {
5783
5784
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5785
5786
		global $blog_id;
5787
		static $clients = array();
5788
5789
		$client_blog_id = is_multisite() ? $blog_id : 0;
5790
5791
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5792
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5793
			if ( function_exists( 'ignore_user_abort' ) ) {
5794
				ignore_user_abort( true );
5795
			}
5796
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5797
		}
5798
5799
		if ( ! empty( $args[0] ) ) {
5800
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5801
		} elseif ( is_multisite() ) {
5802
			foreach ( $clients as $client_blog_id => $client ) {
5803
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5804
					continue;
5805
				}
5806
5807
				$switch_success = switch_to_blog( $client_blog_id, true );
5808
				if ( ! $switch_success ) {
5809
					continue;
5810
				}
5811
5812
				flush();
5813
				$client->query();
5814
5815
				restore_current_blog();
5816
			}
5817
		} else {
5818
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5819
				flush();
5820
				$clients[0]->query();
5821
			}
5822
		}
5823
	}
5824
5825
	public static function staticize_subdomain( $url ) {
5826
5827
		// Extract hostname from URL
5828
		$host = wp_parse_url( $url, PHP_URL_HOST );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
5829
5830
		// Explode hostname on '.'
5831
		$exploded_host = explode( '.', $host );
5832
5833
		// Retrieve the name and TLD
5834
		if ( count( $exploded_host ) > 1 ) {
5835
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5836
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5837
			// Rebuild domain excluding subdomains
5838
			$domain = $name . '.' . $tld;
5839
		} else {
5840
			$domain = $host;
5841
		}
5842
		// Array of Automattic domains.
5843
		$domains_allowed = array( 'wordpress.com', 'wp.com' );
5844
5845
		// Return $url if not an Automattic domain.
5846
		if ( ! in_array( $domain, $domains_allowed, true ) ) {
5847
			return $url;
5848
		}
5849
5850
		if ( is_ssl() ) {
5851
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5852
		}
5853
5854
		srand( crc32( basename( $url ) ) );
5855
		$static_counter = rand( 0, 2 );
5856
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5857
5858
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5859
	}
5860
5861
	/* JSON API Authorization */
5862
5863
	/**
5864
	 * Handles the login action for Authorizing the JSON API
5865
	 */
5866
	function login_form_json_api_authorization() {
5867
		$this->verify_json_api_authorization_request();
5868
5869
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5870
5871
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5872
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5873
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5874
	}
5875
5876
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5877
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5878
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5879
			return $url;
5880
		}
5881
5882
		$parsed_url = wp_parse_url( $url );
5883
		$url        = strtok( $url, '?' );
5884
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5885
		if ( ! empty( $parsed_url['query'] ) ) {
5886
			$url .= "&{$parsed_url['query']}";
5887
		}
5888
5889
		return $url;
5890
	}
5891
5892
	// Make sure the POSTed request is handled by the same action
5893
	function preserve_action_in_login_form_for_json_api_authorization() {
5894
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5895
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5896
	}
5897
5898
	// If someone logs in to approve API access, store the Access Code in usermeta
5899
	function store_json_api_authorization_token( $user_login, $user ) {
5900
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5901
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5902
		$token = wp_generate_password( 32, false );
5903
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5904
	}
5905
5906
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5907
	function allow_wpcom_public_api_domain( $domains ) {
5908
		$domains[] = 'public-api.wordpress.com';
5909
		return $domains;
5910
	}
5911
5912
	static function is_redirect_encoded( $redirect_url ) {
5913
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5914
	}
5915
5916
	// Add all wordpress.com environments to the safe redirect allowed list.
5917
	function allow_wpcom_environments( $domains ) {
5918
		$domains[] = 'wordpress.com';
5919
		$domains[] = 'wpcalypso.wordpress.com';
5920
		$domains[] = 'horizon.wordpress.com';
5921
		$domains[] = 'calypso.localhost';
5922
		return $domains;
5923
	}
5924
5925
	// Add the Access Code details to the public-api.wordpress.com redirect
5926
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5927
		return add_query_arg(
5928
			urlencode_deep(
5929
				array(
5930
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5931
					'jetpack-user-id' => (int) $user->ID,
5932
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5933
				)
5934
			),
5935
			$redirect_to
5936
		);
5937
	}
5938
5939
5940
	/**
5941
	 * Verifies the request by checking the signature
5942
	 *
5943
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5944
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5945
	 *
5946
	 * @param null|array $environment
5947
	 */
5948
	function verify_json_api_authorization_request( $environment = null ) {
5949
		$environment = is_null( $environment )
5950
			? $_REQUEST
5951
			: $environment;
5952
5953
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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

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

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

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