From dcc71eddcd63905427a5a43cd072a38aea693695 Mon Sep 17 00:00:00 2001 From: Gary Pendergast Date: Thu, 27 Oct 2016 03:42:09 +0000 Subject: [PATCH] I18N: Fix a PHP fatal when `get_locale()` is called before `$wpdb` is ready. If WPDB needs to bail early, it loads the translations, which need to load the locale. Without WPDB, we can't get any database options, so can only rely on what's been loaded so far. Fixes #29783. git-svn-id: https://develop.svn.wordpress.org/trunk@38976 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/l10n.php | 11 ++++++++- tests/phpunit/tests/l10n/getLocale.php | 34 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/l10n.php b/src/wp-includes/l10n.php index ba856491af..30cacf4a67 100644 --- a/src/wp-includes/l10n.php +++ b/src/wp-includes/l10n.php @@ -28,7 +28,7 @@ * @return string The locale of the blog or from the {@see 'locale'} hook. */ function get_locale() { - global $locale, $wp_local_package; + global $locale, $wp_local_package, $wpdb; if ( isset( $locale ) ) { /** @@ -50,6 +50,15 @@ function get_locale() { $locale = WPLANG; } + // If $wpdb hasn't been initialised yet, we can only return what we have. + if ( ! $wpdb ) { + if ( ! $locale ) { + return 'en_US'; + } + + return $locale; + } + // If multisite, check options. if ( is_multisite() ) { // Don't check blog option when installing. diff --git a/tests/phpunit/tests/l10n/getLocale.php b/tests/phpunit/tests/l10n/getLocale.php index 64b9900ab4..e7dc7255ab 100644 --- a/tests/phpunit/tests/l10n/getLocale.php +++ b/tests/phpunit/tests/l10n/getLocale.php @@ -81,6 +81,40 @@ class Tests_L10n_GetLocale extends WP_UnitTestCase { $this->assertSame( 'en_US', $found ); } + public function test_should_fall_back_on_locale_when_wpdb_is_unavailable() { + global $locale, $wpdb; + + $old_locale = $locale; + $old_wpdb = $wpdb; + + $locale = $expected = "Is this a locale? No. No it isn't."; + $wpdb = null; + + $found = get_locale(); + + $locale = $old_locale; + $wpdb = $old_wpdb; + + $this->assertSame( $expected, $found ); + } + + public function test_should_fall_back_on_es_US_when_locale_and_wpdb_are_unavailable() { + global $locale, $wpdb; + + $old_locale = $locale; + $old_wpdb = $wpdb; + + $locale = null; + $wpdb = null; + + $found = get_locale(); + + $locale = $old_locale; + $wpdb = $old_wpdb; + + $this->assertSame( 'en_US', $found ); + } + public function test_should_respect_get_locale_filter() { add_filter( 'locale', array( $this, 'filter_get_locale' ) ); $found = get_locale();