Completed
Push — fix/broken-multisites ( 28d8fb )
by
unknown
06:39
created

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

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...
5448
				__( 'This request method is not supported.', 'jetpack' ),
5449
				array( 'status' => 400 )
5450
			);
5451
			return null;
5452
		}
5453
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5454
			$this->rest_authentication_status = new WP_Error(
5455
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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...
5456
				__( 'This request method does not support body parameters.', 'jetpack' ),
5457
				array( 'status' => 400 )
5458
			);
5459
			return null;
5460
		}
5461
5462
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5463
5464
		if (
5465
			$verified &&
5466
			isset( $verified['type'] ) &&
5467
			'user' === $verified['type'] &&
5468
			! empty( $verified['user_id'] )
5469
		) {
5470
			// Authentication successful.
5471
			$this->rest_authentication_status = true;
5472
			return $verified['user_id'];
5473
		}
5474
5475
		// Something else went wrong.  Probably a signature error.
5476
		$this->rest_authentication_status = new WP_Error(
5477
			'rest_invalid_signature',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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...
5478
			__( 'The request is not signed correctly.', 'jetpack' ),
5479
			array( 'status' => 400 )
5480
		);
5481
		return null;
5482
	}
5483
5484
	/**
5485
	 * Report authentication status to the WP REST API.
5486
	 *
5487
	 * @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...
5488
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5489
	 */
5490
	public function wp_rest_authentication_errors( $value ) {
5491
		if ( $value !== null ) {
5492
			return $value;
5493
		}
5494
		return $this->rest_authentication_status;
5495
	}
5496
5497
	/**
5498
	 * Add our nonce to this request.
5499
	 *
5500
	 * @deprecated since 7.7.0
5501
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5502
	 *
5503
	 * @param int    $timestamp Timestamp of the request.
5504
	 * @param string $nonce     Nonce string.
5505
	 */
5506
	public function add_nonce( $timestamp, $nonce ) {
5507
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5508
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5509
	}
5510
5511
	/**
5512
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5513
	 * Capture it here so we can verify the signature later.
5514
	 *
5515
	 * @deprecated since 7.7.0
5516
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5517
	 *
5518
	 * @param array $methods XMLRPC methods.
5519
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5520
	 */
5521
	public function xmlrpc_methods( $methods ) {
5522
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5523
		return $this->connection_manager->xmlrpc_methods( $methods );
5524
	}
5525
5526
	/**
5527
	 * Register additional public XMLRPC methods.
5528
	 *
5529
	 * @deprecated since 7.7.0
5530
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5531
	 *
5532
	 * @param array $methods Public XMLRPC methods.
5533
	 * @return array Public XMLRPC methods, with the getOptions one.
5534
	 */
5535
	public function public_xmlrpc_methods( $methods ) {
5536
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5537
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5538
	}
5539
5540
	/**
5541
	 * Handles a getOptions XMLRPC method call.
5542
	 *
5543
	 * @deprecated since 7.7.0
5544
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5545
	 *
5546
	 * @param array $args method call arguments.
5547
	 * @return array an amended XMLRPC server options array.
5548
	 */
5549
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5550
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5551
		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...
5552
	}
5553
5554
	/**
5555
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5556
	 *
5557
	 * @deprecated since 7.7.0
5558
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5559
	 *
5560
	 * @param array $options Standard Core options.
5561
	 * @return array Amended options.
5562
	 */
5563
	public function xmlrpc_options( $options ) {
5564
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5565
		return $this->connection_manager->xmlrpc_options( $options );
5566
	}
5567
5568
	/**
5569
	 * Cleans nonces that were saved when calling ::add_nonce.
5570
	 *
5571
	 * @deprecated since 7.7.0
5572
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5573
	 *
5574
	 * @param bool $all whether to clean even non-expired nonces.
5575
	 */
5576
	public static function clean_nonces( $all = false ) {
5577
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5578
		return self::connection()->clean_nonces( $all );
5579
	}
5580
5581
	/**
5582
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5583
	 * SET: state( $key, $value );
5584
	 * GET: $value = state( $key );
5585
	 *
5586
	 * @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...
5587
	 * @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...
5588
	 * @param bool   $restate private
5589
	 */
5590
	public static function state( $key = null, $value = null, $restate = false ) {
5591
		static $state = array();
5592
		static $path, $domain;
5593
		if ( ! isset( $path ) ) {
5594
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5595
			$admin_url = self::admin_url();
5596
			$bits      = wp_parse_url( $admin_url );
5597
5598
			if ( is_array( $bits ) ) {
5599
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5600
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5601
			} else {
5602
				$path = $domain = null;
5603
			}
5604
		}
5605
5606
		// Extract state from cookies and delete cookies
5607
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5608
			$yum = $_COOKIE['jetpackState'];
5609
			unset( $_COOKIE['jetpackState'] );
5610
			foreach ( $yum as $k => $v ) {
5611
				if ( strlen( $v ) ) {
5612
					$state[ $k ] = $v;
5613
				}
5614
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5615
			}
5616
		}
5617
5618
		if ( $restate ) {
5619
			foreach ( $state as $k => $v ) {
5620
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5621
			}
5622
			return;
5623
		}
5624
5625
		// Get a state variable
5626
		if ( isset( $key ) && ! isset( $value ) ) {
5627
			if ( array_key_exists( $key, $state ) ) {
5628
				return $state[ $key ];
5629
			}
5630
			return null;
5631
		}
5632
5633
		// Set a state variable
5634
		if ( isset( $key ) && isset( $value ) ) {
5635
			if ( is_array( $value ) && isset( $value[0] ) ) {
5636
				$value = $value[0];
5637
			}
5638
			$state[ $key ] = $value;
5639
			if ( ! headers_sent() ) {
5640
				setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5641
			}
5642
		}
5643
	}
5644
5645
	public static function restate() {
5646
		self::state( null, null, true );
5647
	}
5648
5649
	public static function check_privacy( $file ) {
5650
		static $is_site_publicly_accessible = null;
5651
5652
		if ( is_null( $is_site_publicly_accessible ) ) {
5653
			$is_site_publicly_accessible = false;
5654
5655
			$rpc = new Jetpack_IXR_Client();
5656
5657
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5658
			if ( $success ) {
5659
				$response = $rpc->getResponse();
5660
				if ( $response ) {
5661
					$is_site_publicly_accessible = true;
5662
				}
5663
			}
5664
5665
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5666
		}
5667
5668
		if ( $is_site_publicly_accessible ) {
5669
			return;
5670
		}
5671
5672
		$module_slug = self::get_module_slug( $file );
5673
5674
		$privacy_checks = self::state( 'privacy_checks' );
5675
		if ( ! $privacy_checks ) {
5676
			$privacy_checks = $module_slug;
5677
		} else {
5678
			$privacy_checks .= ",$module_slug";
5679
		}
5680
5681
		self::state( 'privacy_checks', $privacy_checks );
5682
	}
5683
5684
	/**
5685
	 * Helper method for multicall XMLRPC.
5686
	 *
5687
	 * @param ...$args Args for the async_call.
5688
	 */
5689
	public static function xmlrpc_async_call( ...$args ) {
5690
		global $blog_id;
5691
		static $clients = array();
5692
5693
		$client_blog_id = is_multisite() ? $blog_id : 0;
5694
5695
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5696
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5697
			if ( function_exists( 'ignore_user_abort' ) ) {
5698
				ignore_user_abort( true );
5699
			}
5700
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5701
		}
5702
5703
		if ( ! empty( $args[0] ) ) {
5704
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5705
		} elseif ( is_multisite() ) {
5706
			foreach ( $clients as $client_blog_id => $client ) {
5707
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5708
					continue;
5709
				}
5710
5711
				$switch_success = switch_to_blog( $client_blog_id, true );
5712
				if ( ! $switch_success ) {
5713
					continue;
5714
				}
5715
5716
				flush();
5717
				$client->query();
5718
5719
				restore_current_blog();
5720
			}
5721
		} else {
5722
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5723
				flush();
5724
				$clients[0]->query();
5725
			}
5726
		}
5727
	}
5728
5729
	public static function staticize_subdomain( $url ) {
5730
5731
		// Extract hostname from URL
5732
		$host = wp_parse_url( $url, PHP_URL_HOST );
5733
5734
		// Explode hostname on '.'
5735
		$exploded_host = explode( '.', $host );
5736
5737
		// Retrieve the name and TLD
5738
		if ( count( $exploded_host ) > 1 ) {
5739
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5740
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5741
			// Rebuild domain excluding subdomains
5742
			$domain = $name . '.' . $tld;
5743
		} else {
5744
			$domain = $host;
5745
		}
5746
		// Array of Automattic domains
5747
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5748
5749
		// Return $url if not an Automattic domain
5750
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5751
			return $url;
5752
		}
5753
5754
		if ( is_ssl() ) {
5755
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5756
		}
5757
5758
		srand( crc32( basename( $url ) ) );
5759
		$static_counter = rand( 0, 2 );
5760
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5761
5762
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5763
	}
5764
5765
	/* JSON API Authorization */
5766
5767
	/**
5768
	 * Handles the login action for Authorizing the JSON API
5769
	 */
5770
	function login_form_json_api_authorization() {
5771
		$this->verify_json_api_authorization_request();
5772
5773
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5774
5775
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5776
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5777
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5778
	}
5779
5780
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5781
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5782
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5783
			return $url;
5784
		}
5785
5786
		$parsed_url = wp_parse_url( $url );
5787
		$url        = strtok( $url, '?' );
5788
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5789
		if ( ! empty( $parsed_url['query'] ) ) {
5790
			$url .= "&{$parsed_url['query']}";
5791
		}
5792
5793
		return $url;
5794
	}
5795
5796
	// Make sure the POSTed request is handled by the same action
5797
	function preserve_action_in_login_form_for_json_api_authorization() {
5798
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5799
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5800
	}
5801
5802
	// If someone logs in to approve API access, store the Access Code in usermeta
5803
	function store_json_api_authorization_token( $user_login, $user ) {
5804
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5805
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5806
		$token = wp_generate_password( 32, false );
5807
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5808
	}
5809
5810
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5811
	function allow_wpcom_public_api_domain( $domains ) {
5812
		$domains[] = 'public-api.wordpress.com';
5813
		return $domains;
5814
	}
5815
5816
	static function is_redirect_encoded( $redirect_url ) {
5817
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5818
	}
5819
5820
	// Add all wordpress.com environments to the safe redirect whitelist
5821
	function allow_wpcom_environments( $domains ) {
5822
		$domains[] = 'wordpress.com';
5823
		$domains[] = 'wpcalypso.wordpress.com';
5824
		$domains[] = 'horizon.wordpress.com';
5825
		$domains[] = 'calypso.localhost';
5826
		return $domains;
5827
	}
5828
5829
	// Add the Access Code details to the public-api.wordpress.com redirect
5830
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5831
		return add_query_arg(
5832
			urlencode_deep(
5833
				array(
5834
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5835
					'jetpack-user-id' => (int) $user->ID,
5836
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5837
				)
5838
			),
5839
			$redirect_to
5840
		);
5841
	}
5842
5843
5844
	/**
5845
	 * Verifies the request by checking the signature
5846
	 *
5847
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5848
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5849
	 *
5850
	 * @param null|array $environment
5851
	 */
5852
	function verify_json_api_authorization_request( $environment = null ) {
5853
		$environment = is_null( $environment )
5854
			? $_REQUEST
5855
			: $environment;
5856
5857
		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...
5858
		$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...
5859
		if ( ! $token || empty( $token->secret ) ) {
5860
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5861
		}
5862
5863
		$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' );
5864
5865
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5866
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5867
			/**
5868
			 * Jetpack authorisation request Error.
5869
			 *
5870
			 * @since 7.5.0
5871
			 */
5872
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5873
			$die_error = sprintf(
5874
				/* translators: %s is a URL */
5875
				__( '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' ),
5876
				'https://jetpack.com/support/double-encoding/'
5877
			);
5878
		}
5879
5880
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5881
5882
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5883
			$signature = $jetpack_signature->sign_request(
5884
				$environment['token'],
5885
				$environment['timestamp'],
5886
				$environment['nonce'],
5887
				'',
5888
				'GET',
5889
				$environment['jetpack_json_api_original_query'],
5890
				null,
5891
				true
5892
			);
5893
		} else {
5894
			$signature = $jetpack_signature->sign_current_request(
5895
				array(
5896
					'body'   => null,
5897
					'method' => 'GET',
5898
				)
5899
			);
5900
		}
5901
5902
		if ( ! $signature ) {
5903
			wp_die( $die_error );
5904
		} elseif ( is_wp_error( $signature ) ) {
5905
			wp_die( $die_error );
5906
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5907
			if ( is_ssl() ) {
5908
				// 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
5909
				$signature = $jetpack_signature->sign_current_request(
5910
					array(
5911
						'scheme' => 'http',
5912
						'body'   => null,
5913
						'method' => 'GET',
5914
					)
5915
				);
5916
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5917
					wp_die( $die_error );
5918
				}
5919
			} else {
5920
				wp_die( $die_error );
5921
			}
5922
		}
5923
5924
		$timestamp = (int) $environment['timestamp'];
5925
		$nonce     = stripslashes( (string) $environment['nonce'] );
5926
5927
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
5928
			// De-nonce the nonce, at least for 5 minutes.
5929
			// 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)
5930
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5931
			if ( $old_nonce_time < time() - 300 ) {
5932
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5933
			}
5934
		}
5935
5936
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5937
		$data_filters = array(
5938
			'state'        => 'opaque',
5939
			'client_id'    => 'int',
5940
			'client_title' => 'string',
5941
			'client_image' => 'url',
5942
		);
5943
5944
		foreach ( $data_filters as $key => $sanitation ) {
5945
			if ( ! isset( $data->$key ) ) {
5946
				wp_die( $die_error );
5947
			}
5948
5949
			switch ( $sanitation ) {
5950
				case 'int':
5951
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
5952
					break;
5953
				case 'opaque':
5954
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
5955
					break;
5956
				case 'string':
5957
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
5958
					break;
5959
				case 'url':
5960
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
5961
					break;
5962
			}
5963
		}
5964
5965
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5966
			wp_die( $die_error );
5967
		}
5968
	}
5969
5970
	function login_message_json_api_authorization( $message ) {
5971
		return '<p class="message">' . sprintf(
5972
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
5973
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5974
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5975
	}
5976
5977
	/**
5978
	 * Get $content_width, but with a <s>twist</s> filter.
5979
	 */
5980
	public static function get_content_width() {
5981
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5982
			? $GLOBALS['content_width']
5983
			: false;
5984
		/**
5985
		 * Filter the Content Width value.
5986
		 *
5987
		 * @since 2.2.3
5988
		 *
5989
		 * @param string $content_width Content Width value.
5990
		 */
5991
		return apply_filters( 'jetpack_content_width', $content_width );
5992
	}
5993
5994
	/**
5995
	 * Pings the WordPress.com Mirror Site for the specified options.
5996
	 *
5997
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5998
	 *
5999
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6000
	 */
6001
	public function get_cloud_site_options( $option_names ) {
6002
		$option_names = array_filter( (array) $option_names, 'is_string' );
6003
6004
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6005
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6006
		if ( $xml->isError() ) {
6007
			return array(
6008
				'error_code' => $xml->getErrorCode(),
6009
				'error_msg'  => $xml->getErrorMessage(),
6010
			);
6011
		}
6012
		$cloud_site_options = $xml->getResponse();
6013
6014
		return $cloud_site_options;
6015
	}
6016
6017
	/**
6018
	 * Checks if the site is currently in an identity crisis.
6019
	 *
6020
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6021
	 */
6022
	public static function check_identity_crisis() {
6023
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6024
			return false;
6025
		}
6026
6027
		return Jetpack_Options::get_option( 'sync_error_idc' );
6028
	}
6029
6030
	/**
6031
	 * Checks whether the home and siteurl specifically are whitelisted
6032
	 * Written so that we don't have re-check $key and $value params every time
6033
	 * we want to check if this site is whitelisted, for example in footer.php
6034
	 *
6035
	 * @since  3.8.0
6036
	 * @return bool True = already whitelisted False = not whitelisted
6037
	 */
6038
	public static function is_staging_site() {
6039
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6040
		return ( new Status() )->is_staging_site();
6041
	}
6042
6043
	/**
6044
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6045
	 *
6046
	 * @since 4.4.0
6047
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6048
	 *
6049
	 * @return bool
6050
	 */
6051
	public static function validate_sync_error_idc_option() {
6052
		$is_valid = false;
6053
6054
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6055
		if ( false === $idc_allowed ) {
6056
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6057
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6058
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6059
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6060
				$transient_duration = HOUR_IN_SECONDS;
6061
			} else {
6062
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6063
				$idc_allowed        = '1';
6064
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6065
			}
6066
6067
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6068
		}
6069
6070
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6071
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6072
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6073
			$local_options = self::get_sync_error_idc_option();
6074
			// Ensure all values are set.
6075
			if ( isset( $sync_error['home'] ) && isset ( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6076
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6077
					$is_valid = true;
6078
				}
6079
			}
6080
6081
		}
6082
6083
		/**
6084
		 * Filters whether the sync_error_idc option is valid.
6085
		 *
6086
		 * @since 4.4.0
6087
		 *
6088
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6089
		 */
6090
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6091
6092
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6093
			// Since the option exists, and did not validate, delete it
6094
			Jetpack_Options::delete_option( 'sync_error_idc' );
6095
		}
6096
6097
		return $is_valid;
6098
	}
6099
6100
	/**
6101
	 * Normalizes a url by doing three things:
6102
	 *  - Strips protocol
6103
	 *  - Strips www
6104
	 *  - Adds a trailing slash
6105
	 *
6106
	 * @since 4.4.0
6107
	 * @param string $url
6108
	 * @return WP_Error|string
6109
	 */
6110
	public static function normalize_url_protocol_agnostic( $url ) {
6111
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6112
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6113
			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...
6114
		}
6115
6116
		// Strip www and protocols
6117
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6118
		return $url;
6119
	}
6120
6121
	/**
6122
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6123
	 *
6124
	 * @since 4.4.0
6125
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6126
	 *
6127
	 * @param array $response
6128
	 * @return array Array of the local urls, wpcom urls, and error code
6129
	 */
6130
	public static function get_sync_error_idc_option( $response = array() ) {
6131
		// Since the local options will hit the database directly, store the values
6132
		// in a transient to allow for autoloading and caching on subsequent views.
6133
		$local_options = get_transient( 'jetpack_idc_local' );
6134
		if ( false === $local_options ) {
6135
			$local_options = array(
6136
				'home'    => Functions::home_url(),
6137
				'siteurl' => Functions::site_url(),
6138
			);
6139
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6140
		}
6141
6142
		$options = array_merge( $local_options, $response );
6143
6144
		$returned_values = array();
6145
		foreach ( $options as $key => $option ) {
6146
			if ( 'error_code' === $key ) {
6147
				$returned_values[ $key ] = $option;
6148
				continue;
6149
			}
6150
6151
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6152
				continue;
6153
			}
6154
6155
			$returned_values[ $key ] = $normalized_url;
6156
		}
6157
6158
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6159
6160
		return $returned_values;
6161
	}
6162
6163
	/**
6164
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6165
	 * If set to true, the site will be put into staging mode.
6166
	 *
6167
	 * @since 4.3.2
6168
	 * @return bool
6169
	 */
6170
	public static function sync_idc_optin() {
6171
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6172
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6173
		} else {
6174
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6175
		}
6176
6177
		/**
6178
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6179
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6180
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6181
		 *
6182
		 * @since 4.3.2
6183
		 *
6184
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6185
		 */
6186
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6187
	}
6188
6189
	/**
6190
	 * Maybe Use a .min.css stylesheet, maybe not.
6191
	 *
6192
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6193
	 */
6194
	public static function maybe_min_asset( $url, $path, $plugin ) {
6195
		// Short out on things trying to find actual paths.
6196
		if ( ! $path || empty( $plugin ) ) {
6197
			return $url;
6198
		}
6199
6200
		$path = ltrim( $path, '/' );
6201
6202
		// Strip out the abspath.
6203
		$base = dirname( plugin_basename( $plugin ) );
6204
6205
		// Short out on non-Jetpack assets.
6206
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6207
			return $url;
6208
		}
6209
6210
		// File name parsing.
6211
		$file              = "{$base}/{$path}";
6212
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6213
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6214
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6215
		$extension         = array_shift( $file_name_parts_r );
6216
6217
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6218
			// Already pointing at the minified version.
6219
			if ( 'min' === $file_name_parts_r[0] ) {
6220
				return $url;
6221
			}
6222
6223
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6224
			if ( file_exists( $min_full_path ) ) {
6225
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6226
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6227
				if ( 'css' === $extension ) {
6228
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6229
					self::$min_assets[ $key ] = $path;
6230
				}
6231
			}
6232
		}
6233
6234
		return $url;
6235
	}
6236
6237
	/**
6238
	 * If the asset is minified, let's flag .min as the suffix.
6239
	 *
6240
	 * Attached to `style_loader_src` filter.
6241
	 *
6242
	 * @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...
6243
	 * @param string $handle The registered handle of the script in question.
6244
	 * @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...
6245
	 */
6246
	public static function set_suffix_on_min( $src, $handle ) {
6247
		if ( false === strpos( $src, '.min.css' ) ) {
6248
			return $src;
6249
		}
6250
6251
		if ( ! empty( self::$min_assets ) ) {
6252
			foreach ( self::$min_assets as $file => $path ) {
6253
				if ( false !== strpos( $src, $file ) ) {
6254
					wp_style_add_data( $handle, 'suffix', '.min' );
6255
					return $src;
6256
				}
6257
			}
6258
		}
6259
6260
		return $src;
6261
	}
6262
6263
	/**
6264
	 * Maybe inlines a stylesheet.
6265
	 *
6266
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6267
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6268
	 *
6269
	 * Attached to `style_loader_tag` filter.
6270
	 *
6271
	 * @param string $tag The tag that would link to the external asset.
6272
	 * @param string $handle The registered handle of the script in question.
6273
	 *
6274
	 * @return string
6275
	 */
6276
	public static function maybe_inline_style( $tag, $handle ) {
6277
		global $wp_styles;
6278
		$item = $wp_styles->registered[ $handle ];
6279
6280
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6281
			return $tag;
6282
		}
6283
6284
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6285
			$href = $matches[1];
6286
			// Strip off query string
6287
			if ( $pos = strpos( $href, '?' ) ) {
6288
				$href = substr( $href, 0, $pos );
6289
			}
6290
			// Strip off fragment
6291
			if ( $pos = strpos( $href, '#' ) ) {
6292
				$href = substr( $href, 0, $pos );
6293
			}
6294
		} else {
6295
			return $tag;
6296
		}
6297
6298
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6299
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6300
			return $tag;
6301
		}
6302
6303
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6304
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6305
			// And this isn't the pass that actually deals with the RTL version...
6306
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6307
				// Short out, as the RTL version will deal with it in a moment.
6308
				return $tag;
6309
			}
6310
		}
6311
6312
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6313
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6314
		if ( $css ) {
6315
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6316
			if ( empty( $item->extra['after'] ) ) {
6317
				wp_add_inline_style( $handle, $css );
6318
			} else {
6319
				array_unshift( $item->extra['after'], $css );
6320
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6321
			}
6322
		}
6323
6324
		return $tag;
6325
	}
6326
6327
	/**
6328
	 * Loads a view file from the views
6329
	 *
6330
	 * Data passed in with the $data parameter will be available in the
6331
	 * template file as $data['value']
6332
	 *
6333
	 * @param string $template - Template file to load
6334
	 * @param array  $data - Any data to pass along to the template
6335
	 * @return boolean - If template file was found
6336
	 **/
6337
	public function load_view( $template, $data = array() ) {
6338
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6339
6340
		if ( file_exists( $views_dir . $template ) ) {
6341
			require_once $views_dir . $template;
6342
			return true;
6343
		}
6344
6345
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6346
		return false;
6347
	}
6348
6349
	/**
6350
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6351
	 */
6352
	public function deprecated_hooks() {
6353
		global $wp_filter;
6354
6355
		/*
6356
		 * Format:
6357
		 * deprecated_filter_name => replacement_name
6358
		 *
6359
		 * If there is no replacement, use null for replacement_name
6360
		 */
6361
		$deprecated_list = array(
6362
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6363
			'wpl_sharing_2014_1'                           => null,
6364
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6365
			'jetpack_identity_crisis_options_to_check'     => null,
6366
			'update_option_jetpack_single_user_site'       => null,
6367
			'audio_player_default_colors'                  => null,
6368
			'add_option_jetpack_featured_images_enabled'   => null,
6369
			'add_option_jetpack_update_details'            => null,
6370
			'add_option_jetpack_updates'                   => null,
6371
			'add_option_jetpack_network_name'              => null,
6372
			'add_option_jetpack_network_allow_new_registrations' => null,
6373
			'add_option_jetpack_network_add_new_users'     => null,
6374
			'add_option_jetpack_network_site_upload_space' => null,
6375
			'add_option_jetpack_network_upload_file_types' => null,
6376
			'add_option_jetpack_network_enable_administration_menus' => null,
6377
			'add_option_jetpack_is_multi_site'             => null,
6378
			'add_option_jetpack_is_main_network'           => null,
6379
			'add_option_jetpack_main_network_site'         => null,
6380
			'jetpack_sync_all_registered_options'          => null,
6381
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6382
			'jetpack_is_post_mailable'                     => null,
6383
			'jetpack_seo_site_host'                        => null,
6384
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6385
			'jetpack_holiday_snow_option_name'             => null,
6386
			'jetpack_holiday_chance_of_snow'               => null,
6387
			'jetpack_holiday_snow_js_url'                  => null,
6388
			'jetpack_is_holiday_snow_season'               => null,
6389
			'jetpack_holiday_snow_option_updated'          => null,
6390
			'jetpack_holiday_snowing'                      => null,
6391
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6392
			'jetpack_cache_plans'                          => null,
6393
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6394
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6395
			'jetpack_enable_site_verification'             => null,
6396
			'can_display_jetpack_manage_notice'            => null,
6397
			// Removed in Jetpack 7.3.0
6398
			'atd_load_scripts'                             => null,
6399
			'atd_http_post_timeout'                        => null,
6400
			'atd_http_post_error'                          => null,
6401
			'atd_service_domain'                           => null,
6402
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6403
			// Removed in Jetpack 7.9.0
6404
			'jetpack_pwa_manifest'                         => null,
6405
			'jetpack_pwa_background_color'                 => null,
6406
			// Removed in Jetpack 8.3.0.
6407
			'jetpack_check_mobile'                         => null,
6408
			'jetpack_mobile_stylesheet'                    => null,
6409
			'jetpack_mobile_template'                      => null,
6410
			'mobile_reject_mobile'                         => null,
6411
			'mobile_force_mobile'                          => null,
6412
			'mobile_app_promo_download'                    => null,
6413
			'mobile_setup'                                 => null,
6414
			'jetpack_mobile_footer_before'                 => null,
6415
			'wp_mobile_theme_footer'                       => null,
6416
			'minileven_credits'                            => null,
6417
			'jetpack_mobile_header_before'                 => null,
6418
			'jetpack_mobile_header_after'                  => null,
6419
			'jetpack_mobile_theme_menu'                    => null,
6420
			'minileven_show_featured_images'               => null,
6421
			'minileven_attachment_size'                    => null,
6422
		);
6423
6424
		// This is a silly loop depth. Better way?
6425
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6426
			if ( has_action( $hook ) ) {
6427
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6428
					foreach ( $values as $hooked ) {
6429
						if ( is_callable( $hooked['function'] ) ) {
6430
							$function_name = 'an anonymous function';
6431
						} else {
6432
							$function_name = $hooked['function'];
6433
						}
6434
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6435
					}
6436
				}
6437
			}
6438
		}
6439
	}
6440
6441
	/**
6442
	 * Converts any url in a stylesheet, to the correct absolute url.
6443
	 *
6444
	 * Considerations:
6445
	 *  - Normal, relative URLs     `feh.png`
6446
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6447
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6448
	 *  - Absolute URLs             `http://domain.com/feh.png`
6449
	 *  - Domain root relative URLs `/feh.png`
6450
	 *
6451
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6452
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6453
	 *
6454
	 * @return mixed|string
6455
	 */
6456
	public static function absolutize_css_urls( $css, $css_file_url ) {
6457
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6458
		$css_dir = dirname( $css_file_url );
6459
		$p       = wp_parse_url( $css_dir );
6460
		$domain  = sprintf(
6461
			'%1$s//%2$s%3$s%4$s',
6462
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6463
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6464
			$p['host'],
6465
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6466
		);
6467
6468
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6469
			$find = $replace = array();
6470
			foreach ( $matches as $match ) {
6471
				$url = trim( $match['path'], "'\" \t" );
6472
6473
				// If this is a data url, we don't want to mess with it.
6474
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6475
					continue;
6476
				}
6477
6478
				// If this is an absolute or protocol-agnostic url,
6479
				// we don't want to mess with it.
6480
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6481
					continue;
6482
				}
6483
6484
				switch ( substr( $url, 0, 1 ) ) {
6485
					case '/':
6486
						$absolute = $domain . $url;
6487
						break;
6488
					default:
6489
						$absolute = $css_dir . '/' . $url;
6490
				}
6491
6492
				$find[]    = $match[0];
6493
				$replace[] = sprintf( 'url("%s")', $absolute );
6494
			}
6495
			$css = str_replace( $find, $replace, $css );
6496
		}
6497
6498
		return $css;
6499
	}
6500
6501
	/**
6502
	 * This methods removes all of the registered css files on the front end
6503
	 * from Jetpack in favor of using a single file. In effect "imploding"
6504
	 * all the files into one file.
6505
	 *
6506
	 * Pros:
6507
	 * - Uses only ONE css asset connection instead of 15
6508
	 * - Saves a minimum of 56k
6509
	 * - Reduces server load
6510
	 * - Reduces time to first painted byte
6511
	 *
6512
	 * Cons:
6513
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6514
	 *      should not cause any issues with themes.
6515
	 * - Plugins/themes dequeuing styles no longer do anything. See
6516
	 *      jetpack_implode_frontend_css filter for a workaround
6517
	 *
6518
	 * For some situations developers may wish to disable css imploding and
6519
	 * instead operate in legacy mode where each file loads seperately and
6520
	 * can be edited individually or dequeued. This can be accomplished with
6521
	 * the following line:
6522
	 *
6523
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6524
	 *
6525
	 * @since 3.2
6526
	 **/
6527
	public function implode_frontend_css( $travis_test = false ) {
6528
		$do_implode = true;
6529
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6530
			$do_implode = false;
6531
		}
6532
6533
		// Do not implode CSS when the page loads via the AMP plugin.
6534
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6535
			$do_implode = false;
6536
		}
6537
6538
		/**
6539
		 * Allow CSS to be concatenated into a single jetpack.css file.
6540
		 *
6541
		 * @since 3.2.0
6542
		 *
6543
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6544
		 */
6545
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6546
6547
		// Do not use the imploded file when default behavior was altered through the filter
6548
		if ( ! $do_implode ) {
6549
			return;
6550
		}
6551
6552
		// We do not want to use the imploded file in dev mode, or if not connected
6553
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6554
			if ( ! $travis_test ) {
6555
				return;
6556
			}
6557
		}
6558
6559
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6560
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6561
			return;
6562
		}
6563
6564
		/*
6565
		 * Now we assume Jetpack is connected and able to serve the single
6566
		 * file.
6567
		 *
6568
		 * In the future there will be a check here to serve the file locally
6569
		 * or potentially from the Jetpack CDN
6570
		 *
6571
		 * For now:
6572
		 * - Enqueue a single imploded css file
6573
		 * - Zero out the style_loader_tag for the bundled ones
6574
		 * - Be happy, drink scotch
6575
		 */
6576
6577
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6578
6579
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6580
6581
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6582
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6583
	}
6584
6585
	function concat_remove_style_loader_tag( $tag, $handle ) {
6586
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6587
			$tag = '';
6588
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6589
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6590
			}
6591
		}
6592
6593
		return $tag;
6594
	}
6595
6596
	/**
6597
	 * Add an async attribute to scripts that can be loaded asynchronously.
6598
	 * https://www.w3schools.com/tags/att_script_async.asp
6599
	 *
6600
	 * @since 7.7.0
6601
	 *
6602
	 * @param string $tag    The <script> tag for the enqueued script.
6603
	 * @param string $handle The script's registered handle.
6604
	 * @param string $src    The script's source URL.
6605
	 */
6606
	public function script_add_async( $tag, $handle, $src ) {
6607
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6608
			return preg_replace( '/^<script /i', '<script async ', $tag );
6609
		}
6610
6611
		return $tag;
6612
	}
6613
6614
	/*
6615
	 * Check the heartbeat data
6616
	 *
6617
	 * Organizes the heartbeat data by severity.  For example, if the site
6618
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6619
	 *
6620
	 * Data will be added to "caution" array, if it either:
6621
	 *  - Out of date Jetpack version
6622
	 *  - Out of date WP version
6623
	 *  - Out of date PHP version
6624
	 *
6625
	 * $return array $filtered_data
6626
	 */
6627
	public static function jetpack_check_heartbeat_data() {
6628
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6629
6630
		$good    = array();
6631
		$caution = array();
6632
		$bad     = array();
6633
6634
		foreach ( $raw_data as $stat => $value ) {
6635
6636
			// Check jetpack version
6637
			if ( 'version' == $stat ) {
6638
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6639
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6640
					continue;
6641
				}
6642
			}
6643
6644
			// Check WP version
6645
			if ( 'wp-version' == $stat ) {
6646
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6647
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6648
					continue;
6649
				}
6650
			}
6651
6652
			// Check PHP version
6653
			if ( 'php-version' == $stat ) {
6654
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6655
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_PHP_VERSION;
6656
					continue;
6657
				}
6658
			}
6659
6660
			// Check ID crisis
6661
			if ( 'identitycrisis' == $stat ) {
6662
				if ( 'yes' == $value ) {
6663
					$bad[ $stat ] = $value;
6664
					continue;
6665
				}
6666
			}
6667
6668
			// The rest are good :)
6669
			$good[ $stat ] = $value;
6670
		}
6671
6672
		$filtered_data = array(
6673
			'good'    => $good,
6674
			'caution' => $caution,
6675
			'bad'     => $bad,
6676
		);
6677
6678
		return $filtered_data;
6679
	}
6680
6681
6682
	/*
6683
	 * This method is used to organize all options that can be reset
6684
	 * without disconnecting Jetpack.
6685
	 *
6686
	 * It is used in class.jetpack-cli.php to reset options
6687
	 *
6688
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6689
	 *
6690
	 * @return array of options to delete.
6691
	 */
6692
	public static function get_jetpack_options_for_reset() {
6693
		return Jetpack_Options::get_options_for_reset();
6694
	}
6695
6696
	/*
6697
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6698
	 * so we can bring them directly to their site in calypso.
6699
	 *
6700
	 * @param string | url
6701
	 * @return string | url without the guff
6702
	 */
6703
	public static function build_raw_urls( $url ) {
6704
		$strip_http = '/.*?:\/\//i';
6705
		$url        = preg_replace( $strip_http, '', $url );
6706
		$url        = str_replace( '/', '::', $url );
6707
		return $url;
6708
	}
6709
6710
	/**
6711
	 * Stores and prints out domains to prefetch for page speed optimization.
6712
	 *
6713
	 * @param mixed $new_urls
6714
	 */
6715
	public static function dns_prefetch( $new_urls = null ) {
6716
		static $prefetch_urls = array();
6717
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6718
			echo "\r\n";
6719
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6720
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6721
			}
6722
		} elseif ( ! empty( $new_urls ) ) {
6723
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6724
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6725
			}
6726
			foreach ( (array) $new_urls as $this_new_url ) {
6727
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6728
			}
6729
			$prefetch_urls = array_unique( $prefetch_urls );
6730
		}
6731
	}
6732
6733
	public function wp_dashboard_setup() {
6734
		if ( self::is_active() ) {
6735
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6736
		}
6737
6738
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6739
			$jetpack_logo = new Jetpack_Logo();
6740
			$widget_title = sprintf(
6741
				wp_kses(
6742
					/* translators: Placeholder is a Jetpack logo. */
6743
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6744
					array( 'span' => array() )
6745
				),
6746
				$jetpack_logo->get_jp_emblem( true )
6747
			);
6748
6749
			wp_add_dashboard_widget(
6750
				'jetpack_summary_widget',
6751
				$widget_title,
6752
				array( __CLASS__, 'dashboard_widget' )
6753
			);
6754
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6755
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6756
6757
			// If we're inactive and not in development mode, sort our box to the top.
6758
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6759
				global $wp_meta_boxes;
6760
6761
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6762
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6763
6764
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6765
			}
6766
		}
6767
	}
6768
6769
	/**
6770
	 * @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...
6771
	 * @return mixed
6772
	 */
6773
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6774
		if ( ! is_array( $sorted ) ) {
6775
			return $sorted;
6776
		}
6777
6778
		foreach ( $sorted as $box_context => $ids ) {
6779
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6780
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6781
				continue;
6782
			}
6783
6784
			$ids_array = explode( ',', $ids );
6785
			$key       = array_search( 'dashboard_stats', $ids_array );
6786
6787
			if ( false !== $key ) {
6788
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6789
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6790
				$sorted[ $box_context ] = implode( ',', $ids_array );
6791
				// We've found it, stop searching, and just return.
6792
				break;
6793
			}
6794
		}
6795
6796
		return $sorted;
6797
	}
6798
6799
	public static function dashboard_widget() {
6800
		/**
6801
		 * Fires when the dashboard is loaded.
6802
		 *
6803
		 * @since 3.4.0
6804
		 */
6805
		do_action( 'jetpack_dashboard_widget' );
6806
	}
6807
6808
	public static function dashboard_widget_footer() {
6809
		?>
6810
		<footer>
6811
6812
		<div class="protect">
6813
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6814
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6815
				<p class="blocked-count">
6816
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6817
				</p>
6818
				<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>
6819
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6820
				<a href="
6821
				<?php
6822
				echo esc_url(
6823
					wp_nonce_url(
6824
						self::admin_url(
6825
							array(
6826
								'action' => 'activate',
6827
								'module' => 'protect',
6828
							)
6829
						),
6830
						'jetpack_activate-protect'
6831
					)
6832
				);
6833
				?>
6834
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6835
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6836
				</a>
6837
			<?php else : ?>
6838
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6839
			<?php endif; ?>
6840
		</div>
6841
6842
		<div class="akismet">
6843
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6844
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6845
				<p class="blocked-count">
6846
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6847
				</p>
6848
				<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>
6849
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6850
				<a href="
6851
				<?php
6852
				echo esc_url(
6853
					wp_nonce_url(
6854
						add_query_arg(
6855
							array(
6856
								'action' => 'activate',
6857
								'plugin' => 'akismet/akismet.php',
6858
							),
6859
							admin_url( 'plugins.php' )
6860
						),
6861
						'activate-plugin_akismet/akismet.php'
6862
					)
6863
				);
6864
				?>
6865
							" class="button button-jetpack">
6866
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
6867
				</a>
6868
			<?php else : ?>
6869
				<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>
6870
			<?php endif; ?>
6871
		</div>
6872
6873
		</footer>
6874
		<?php
6875
	}
6876
6877
	/*
6878
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6879
	 */
6880
	function jetpack_icon_user_connected( $columns ) {
6881
		$columns['user_jetpack'] = '';
6882
		return $columns;
6883
	}
6884
6885
	/*
6886
	 * Show Jetpack icon if the user is linked.
6887
	 */
6888
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6889
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
6890
			$jetpack_logo = new Jetpack_Logo();
6891
			$emblem_html  = sprintf(
6892
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6893
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6894
				$jetpack_logo->get_jp_emblem()
6895
			);
6896
			return $emblem_html;
6897
		}
6898
6899
		return $val;
6900
	}
6901
6902
	/*
6903
	 * Style the Jetpack user column
6904
	 */
6905
	function jetpack_user_col_style() {
6906
		global $current_screen;
6907
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6908
			?>
6909
			<style>
6910
				.fixed .column-user_jetpack {
6911
					width: 21px;
6912
				}
6913
				.jp-emblem-user-admin svg {
6914
					width: 20px;
6915
					height: 20px;
6916
				}
6917
				.jp-emblem-user-admin path {
6918
					fill: #00BE28;
6919
				}
6920
			</style>
6921
			<?php
6922
		}
6923
	}
6924
6925
	/**
6926
	 * Checks if Akismet is active and working.
6927
	 *
6928
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6929
	 * that implied usage of methods present since more recent version.
6930
	 * See https://github.com/Automattic/jetpack/pull/9585
6931
	 *
6932
	 * @since  5.1.0
6933
	 *
6934
	 * @return bool True = Akismet available. False = Aksimet not available.
6935
	 */
6936
	public static function is_akismet_active() {
6937
		static $status = null;
6938
6939
		if ( ! is_null( $status ) ) {
6940
			return $status;
6941
		}
6942
6943
		// Check if a modern version of Akismet is active.
6944
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6945
			$status = false;
6946
			return $status;
6947
		}
6948
6949
		// Make sure there is a key known to Akismet at all before verifying key.
6950
		$akismet_key = Akismet::get_api_key();
6951
		if ( ! $akismet_key ) {
6952
			$status = false;
6953
			return $status;
6954
		}
6955
6956
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6957
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6958
6959
		// 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.
6960
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6961
		// We cache the result of the Akismet key verification for ten minutes.
6962
		if ( ! $akismet_key_state || $recheck ) {
6963
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6964
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6965
		}
6966
6967
		$status = 'valid' === $akismet_key_state;
6968
6969
		return $status;
6970
	}
6971
6972
	/**
6973
	 * @deprecated
6974
	 *
6975
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6976
	 */
6977
	public static function is_function_in_backtrace() {
6978
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6979
	}
6980
6981
	/**
6982
	 * Given a minified path, and a non-minified path, will return
6983
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6984
	 *
6985
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6986
	 * root Jetpack directory.
6987
	 *
6988
	 * @since 5.6.0
6989
	 *
6990
	 * @param string $min_path
6991
	 * @param string $non_min_path
6992
	 * @return string The URL to the file
6993
	 */
6994
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6995
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6996
	}
6997
6998
	/**
6999
	 * Checks for whether Jetpack Backup & Scan is enabled.
7000
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7001
	 *
7002
	 * @return bool|int|mixed
7003
	 */
7004
	public static function is_rewind_enabled() {
7005
		if ( ! self::is_active() ) {
7006
			return false;
7007
		}
7008
7009
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7010
		if ( false === $rewind_enabled ) {
7011
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7012
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7013
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7014
				&& ! empty( $rewind_data['state'] )
7015
				&& 'active' === $rewind_data['state'] )
7016
				? 1
7017
				: 0;
7018
7019
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7020
		}
7021
		return $rewind_enabled;
7022
	}
7023
7024
	/**
7025
	 * Return Calypso environment value; used for developing Jetpack and pairing
7026
	 * it with different Calypso enrionments, such as localhost.
7027
	 *
7028
	 * @since 7.4.0
7029
	 *
7030
	 * @return string Calypso environment
7031
	 */
7032
	public static function get_calypso_env() {
7033
		if ( isset( $_GET['calypso_env'] ) ) {
7034
			return sanitize_key( $_GET['calypso_env'] );
7035
		}
7036
7037
		if ( getenv( 'CALYPSO_ENV' ) ) {
7038
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7039
		}
7040
7041
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7042
			return sanitize_key( CALYPSO_ENV );
7043
		}
7044
7045
		return '';
7046
	}
7047
7048
	/**
7049
	 * Checks whether or not TOS has been agreed upon.
7050
	 * Will return true if a user has clicked to register, or is already connected.
7051
	 */
7052
	public static function jetpack_tos_agreed() {
7053
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7054
7055
		$terms_of_service = new Terms_Of_Service();
7056
		return $terms_of_service->has_agreed();
7057
7058
	}
7059
7060
	/**
7061
	 * Handles activating default modules as well general cleanup for the new connection.
7062
	 *
7063
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7064
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7065
	 * @param boolean $send_state_messages          Whether to send state messages.
7066
	 * @return void
7067
	 */
7068
	public static function handle_post_authorization_actions(
7069
		$activate_sso = false,
7070
		$redirect_on_activation_error = false,
7071
		$send_state_messages = true
7072
	) {
7073
		$other_modules = $activate_sso
7074
			? array( 'sso' )
7075
			: array();
7076
7077
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7078
			self::delete_active_modules();
7079
7080
			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...
7081
		} else {
7082
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7083
		}
7084
7085
		// Since this is a fresh connection, be sure to clear out IDC options
7086
		Jetpack_IDC::clear_all_idc_options();
7087
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7088
7089
		// Start nonce cleaner
7090
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7091
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7092
7093
		if ( $send_state_messages ) {
7094
			self::state( 'message', 'authorized' );
7095
		}
7096
	}
7097
7098
	/**
7099
	 * Returns a boolean for whether backups UI should be displayed or not.
7100
	 *
7101
	 * @return bool Should backups UI be displayed?
7102
	 */
7103
	public static function show_backups_ui() {
7104
		/**
7105
		 * Whether UI for backups should be displayed.
7106
		 *
7107
		 * @since 6.5.0
7108
		 *
7109
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7110
		 */
7111
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7112
	}
7113
7114
	/*
7115
	 * Deprecated manage functions
7116
	 */
7117
	function prepare_manage_jetpack_notice() {
7118
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7119
	}
7120
	function manage_activate_screen() {
7121
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7122
	}
7123
	function admin_jetpack_manage_notice() {
7124
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7125
	}
7126
	function opt_out_jetpack_manage_url() {
7127
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7128
	}
7129
	function opt_in_jetpack_manage_url() {
7130
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7131
	}
7132
	function opt_in_jetpack_manage_notice() {
7133
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7134
	}
7135
	function can_display_jetpack_manage_notice() {
7136
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7137
	}
7138
7139
	/**
7140
	 * Clean leftoveruser meta.
7141
	 *
7142
	 * Delete Jetpack-related user meta when it is no longer needed.
7143
	 *
7144
	 * @since 7.3.0
7145
	 *
7146
	 * @param int $user_id User ID being updated.
7147
	 */
7148
	public static function user_meta_cleanup( $user_id ) {
7149
		$meta_keys = array(
7150
			// AtD removed from Jetpack 7.3
7151
			'AtD_options',
7152
			'AtD_check_when',
7153
			'AtD_guess_lang',
7154
			'AtD_ignored_phrases',
7155
		);
7156
7157
		foreach ( $meta_keys as $meta_key ) {
7158
			if ( get_user_meta( $user_id, $meta_key ) ) {
7159
				delete_user_meta( $user_id, $meta_key );
7160
			}
7161
		}
7162
	}
7163
7164
	/**
7165
	 * Checks if a Jetpack site is both active and not in development.
7166
	 *
7167
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7168
	 *
7169
	 * @return bool True if Jetpack is active and not in development.
7170
	 */
7171
	public static function is_active_and_not_development_mode() {
7172
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7173
			return false;
7174
		}
7175
		return true;
7176
	}
7177
}
7178