diff --git a/src/wp-includes/l10n.php b/src/wp-includes/l10n.php index e90f97fd2025a..d89fdf739619a 100644 --- a/src/wp-includes/l10n.php +++ b/src/wp-includes/l10n.php @@ -2239,3 +2239,216 @@ function wp_get_word_count_type() { function has_translation( string $singular, string $textdomain = 'default', ?string $locale = null ): bool { return WP_Translation_Controller::get_instance()->has_translation( $singular, $textdomain, $locale ); } + +/** + * Determines whether options can be safely retrieved during early bootstrap. + * + * Translations can be loaded very early, e.g. while handling database errors, + * before the object cache is started or before the database connection is ready. + * + * @since 7.3.0 + * @access private + * + * @global wpdb $wpdb WordPress database abstraction object. + * + * @return bool Whether options can be retrieved. + */ +function wp_can_query_options_early() { + global $wpdb; + + return $wpdb instanceof wpdb + && $wpdb->ready + && function_exists( 'get_option' ) + // The options API relies on the object cache, which is started after the database connection. + && function_exists( 'wp_cache_get' ); +} + +/** + * Parses the `Accept-Language` header to get a list of locales. + * + * The locales are returned in the format WordPress expects, + * so "fr-CH" becomes "fr_CH" and "fr" becomes "fr_FR". + * + * If the list of available translations is already cached, + * it is used to map language codes to actually existing locales. + * Otherwise, a best-effort approximation is returned. + * + * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language + * @link https://www.rfc-editor.org/rfc/rfc9110#field.accept-language + * + * @since 7.3.0 + * @access private + * + * @global wpdb $wpdb WordPress database abstraction object. + * + * @return string[] Locales list, ordered by preference. + */ +function get_locales_from_accept_language_header() { + global $wpdb; + + if ( empty( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) || ! is_string( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) { + return array(); + } + + /* + * Parse a header value such as "fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5". + * + * Only a limited number of entries is considered, which is more than enough + * for any real browser and protects against excessively long headers. + */ + $entries = array_slice( explode( ',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] ), 0, 20 ); + + $weighted_codes = array(); + + foreach ( $entries as $index => $entry ) { + $params = explode( ';', $entry ); + $code = trim( array_shift( $params ) ); + + // Language range as per RFC 4647, e.g. "de", "de-CH", "ca-valencia", or the "*" wildcard. + if ( '*' !== $code && ! preg_match( '/^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/', $code ) ) { + continue; + } + + // An absent weight defaults to 1. + $weight = 1.0; + + foreach ( $params as $param ) { + $param = trim( $param ); + + if ( ! preg_match( '/^q\s*=\s*(.*)$/i', $param, $param_matches ) ) { + continue; + } + + if ( ! preg_match( '/^(?:1(?:\.0{0,3})?|0(?:\.\d{0,3})?)$/', $param_matches[1] ) ) { + // Ignore entries with an invalid weight. + continue 2; + } + + $weight = (float) $param_matches[1]; + } + + // A weight of 0 means "not acceptable". + if ( $weight <= 0 ) { + continue; + } + + $weighted_codes[] = array( + 'code' => $code, + 'weight' => $weight, + 'index' => $index, + ); + } + + // Sort codes by weight, keeping the original order for equal weights. + usort( + $weighted_codes, + static function ( $a, $b ) { + $cmp = $b['weight'] <=> $a['weight']; + return 0 !== $cmp ? $cmp : ( $a['index'] <=> $b['index'] ); + } + ); + + $translations = array(); + + /* + * Get list of available translations without potentially deleting an expired transient and causing an HTTP request. + * Only works if either the object cache or the database are already available. + * This function can run very early, e.g. while handling database errors, + * so make sure not to trigger any new errors along the way. + */ + if ( wp_using_ext_object_cache() ) { + if ( function_exists( 'wp_cache_get' ) ) { + $translations = wp_cache_get( 'available_translations', 'site-transient' ); + } + } elseif ( wp_can_query_options_early() ) { + $suppress = $wpdb->suppress_errors(); + $translations = get_site_option( '_site_transient_available_translations' ); + $wpdb->suppress_errors( $suppress ); + } + + $has_available_translations = is_array( $translations ) && ! empty( $translations ); + + $locales = array(); + + foreach ( $weighted_codes as $weighted_code ) { + $code = $weighted_code['code']; + + if ( '*' === $code ) { + // Ignore anything after the wildcard, as we can then just default to en_US. + break; + } + + // Language tags are case-insensitive, normalize them to WordPress' format, e.g. "de-ch" -> "de_CH". + $subtags = explode( '-', strtolower( $code ) ); + $language = array_shift( $subtags ); + $parts = array( $language ); + + foreach ( $subtags as $subtag ) { + if ( 4 === strlen( $subtag ) && ctype_alpha( $subtag ) ) { + // Script subtags such as "Latn" or "Hant" are not part of WordPress locales. + continue; + } + + if ( 2 === strlen( $subtag ) && ctype_alpha( $subtag ) ) { + // Region subtags are uppercase, e.g. "CH". + $subtag = strtoupper( $subtag ); + } + + $parts[] = $subtag; + } + + $locale = implode( '_', $parts ); + + // If English is accepted, then there is no point in adding any other locales after it. + if ( 'en' === $locale || 'en_US' === $locale ) { + break; + } + + if ( $has_available_translations ) { + $found = array(); + + foreach ( $translations as $translation_locale => $translation ) { + $translation_locale = (string) $translation_locale; + + if ( $locale === $translation_locale ) { + $found[] = $translation_locale; + } elseif ( + // Language-only codes such as "de" match all locales for that language. + $locale === $language && + isset( $translation['iso'] ) && + is_array( $translation['iso'] ) && + in_array( $language, $translation['iso'], true ) + ) { + $found[] = $translation_locale; + } + } + + /* + * Prefer exact matches, then the "main" locale for a language (e.g. "fr_FR" for "fr"), + * then everything else in alphabetical order. + */ + $main_locale = $language . '_' . strtoupper( $language ); + + usort( + $found, + static function ( $a, $b ) use ( $locale, $main_locale ) { + $rank_a = $locale === $a ? 0 : ( $main_locale === $a ? 1 : 2 ); + $rank_b = $locale === $b ? 0 : ( $main_locale === $b ? 1 : 2 ); + + return 0 !== $rank_a - $rank_b ? $rank_a - $rank_b : strcmp( $a, $b ); + } + ); + + array_push( $locales, ...$found ); + } else { + $locales[] = $locale; + + // Fallback approximation, supporting cases like "el", but also "fr" -> "fr_FR". + if ( 2 === strlen( $locale ) ) { + $locales[] = $locale . '_' . strtoupper( $locale ); + } + } + } + + return array_values( array_unique( $locales ) ); +} diff --git a/src/wp-includes/load.php b/src/wp-includes/load.php index ce309d2ecd2ae..5949b0cdc010f 100644 --- a/src/wp-includes/load.php +++ b/src/wp-includes/load.php @@ -1612,6 +1612,9 @@ function wp_load_translations_early() { $locales[] = $wp_local_package; } + // Try the browser's locale. + $locales = array_merge( $locales, get_locales_from_accept_language_header() ); + if ( ! $locales ) { break; } diff --git a/tests/e2e/specs/maintenance-mode.test.js b/tests/e2e/specs/maintenance-mode.test.js index 6ccbfbb8063f1..7d293cef97d1f 100644 --- a/tests/e2e/specs/maintenance-mode.test.js +++ b/tests/e2e/specs/maintenance-mode.test.js @@ -32,10 +32,25 @@ test.describe( 'Maintenance mode', () => { }, 'should leave maintenance mode after the lock file is deleted' ).toPass( { timeout: 10_000 } ); } ); - test( 'should display maintenance mode page', async ( { page } ) => { - await page.goto( '/' ); - await expect( - page.getByText( /Briefly unavailable for scheduled maintenance\. Check back in a minute\./ ) - ).toBeVisible(); + test.describe( 'Default (en_US)', () => { + test( 'should display maintenance mode page', async ( { page } ) => { + await page.goto( '/' ); + await expect( + page.getByText( /Briefly unavailable for scheduled maintenance\. Check back in a minute\./ ) + ).toBeVisible(); + } ); + } ); + + test.describe( 'Localized (de_DE)', () => { + test.use( { locale: 'de-DE' } ); // Sets the Accept-Language header. + + test( 'should display maintenance mode page', async ( { page } ) => { + await page.goto( '/' ); + // Only match a part of the string to be resilient against translation changes. + await expect( page.getByText( /Wartungsarbeiten/ ) ).toBeVisible(); + await expect( + page.getByText( /Briefly unavailable for scheduled maintenance/ ) + ).toBeHidden(); + } ); } ); } ); diff --git a/tests/phpunit/tests/l10n.php b/tests/phpunit/tests/l10n.php index 88d867b38f529..43b1e1c101ca2 100644 --- a/tests/phpunit/tests/l10n.php +++ b/tests/phpunit/tests/l10n.php @@ -461,4 +461,294 @@ public function test_length_of_comment_excerpt_should_be_counted_by_chars_in_Jap $this->assertSame( $expect, $comment_excerpt ); } + + /** + * @ticket 30049 + * + * @covers ::wp_can_query_options_early + */ + public function test_wp_can_query_options_early() { + $this->assertTrue( wp_can_query_options_early() ); + } + + /** + * @ticket 30049 + * + * @covers ::wp_can_query_options_early + */ + public function test_wp_can_query_options_early_without_database_connection() { + global $wpdb; + + $ready = $wpdb->ready; + $wpdb->ready = false; + + $actual = wp_can_query_options_early(); + + $wpdb->ready = $ready; + + $this->assertFalse( $actual ); + } + + /** + * @ticket 30049 + * + * @covers ::get_locales_from_accept_language_header + * + * @dataProvider data_get_locales_from_accept_language_header + * + * @param mixed $input Header value, or 'missing' to unset the header. + * @param string[] $expected Expected list of locales. + * @param bool $has_transient Whether the list of available translations is cached. + */ + public function test_get_locales_from_accept_language_header( $input, $expected, $has_transient = false ) { + if ( 'missing' === $input ) { + unset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ); + } else { + $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $input; + } + + if ( $has_transient ) { + set_site_transient( 'available_translations', self::get_available_translations_fixture() ); + } else { + delete_site_transient( 'available_translations' ); + } + + $actual = get_locales_from_accept_language_header(); + + unset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ); + delete_site_transient( 'available_translations' ); + + $this->assertSame( $expected, $actual, 'Parsed locales list does not match expected list.' ); + } + + /** + * Returns a subset of the data returned by the translations API, + * to avoid relying on external HTTP requests in tests. + * + * @return array[] Available translations. + */ + private static function get_available_translations_fixture() { + $translations = array( + 'bn_BD' => array( 'bn' ), + 'ca' => array( 'ca', 'cat' ), + 'de_AT' => array( 'de' ), + 'de_CH' => array( 'de' ), + 'de_CH_informal' => array( 'de' ), + 'de_DE' => array( 'de' ), + 'de_DE_formal' => array( 'de' ), + 'el' => array( 'el', 'ell' ), + 'en_GB' => array( 'en', 'eng', 'eng' ), + 'es_ES' => array( 'es', 'spa', 'spa' ), + 'fr_BE' => array( 'fr', 'fra' ), + 'fr_CA' => array( 'fr', 'fra' ), + 'fr_FR' => array( 'fr' ), + 'kir' => array( 'ky', 'kir', 'kir' ), + 'pt_BR' => array( 'pt', 'por' ), + 'pt_PT' => array( 'pt' ), + 'zh_TW' => array( 'zh', 'zho' ), + ); + + $result = array(); + + foreach ( $translations as $language => $iso ) { + $result[ $language ] = array( + 'language' => $language, + 'iso' => array_combine( range( 1, count( $iso ) ), $iso ), + ); + } + + return $result; + } + + public static function data_get_locales_from_accept_language_header() { + return array( + 'Missing header' => array( + 'missing', // Will be handled specially in the test. + array(), + ), + 'Null header' => array( + null, + array(), + ), + 'Empty header' => array( + false, + array(), + ), + 'Invalid type' => array( + array(), + array(), + ), + 'Wildcard' => array( + '*', + array(), + ), + 'Only separators' => array( + ' ; , ;q=1, ', + array(), + ), + 'English first' => array( + 'en-US, de', + array(), + ), + 'English first, with transient' => array( + 'en, de', + array(), + true, + ), + 'Two-letter locales' => array( + 'de, fr, el, bn, ky', + array( + 'de', + 'de_DE', + 'fr', + 'fr_FR', + 'el', + 'el_EL', + 'bn', + 'bn_BN', + 'ky', + 'ky_KY', + ), + ), + 'Two-letter locales, with transient' => array( + 'de, fr, el, bn, ky', + array( + 'de_DE', + 'de_AT', + 'de_CH', + 'de_CH_informal', + 'de_DE_formal', + 'fr_FR', + 'fr_BE', + 'fr_CA', + 'el', + 'bn_BD', + 'kir', + ), + true, + ), + 'Case-insensitive' => array( + 'DE-ch, FR', + array( + 'de_CH', + 'fr', + 'fr_FR', + ), + ), + 'Case-insensitive, with transient' => array( + 'DE-ch, FR', + array( + 'de_CH', + 'fr_FR', + 'fr_BE', + 'fr_CA', + ), + true, + ), + 'Script subtag' => array( + 'zh-Hant-TW', + array( 'zh_TW' ), + ), + 'Script subtag, with transient' => array( + 'zh-Hant-TW', + array( 'zh_TW' ), + true, + ), + // en-GB-oxendict is supported by Chrome, ca-valencia by Firefox. + 'Longer variants' => array( + 'en-GB-oxendict, de-DE, ca-valencia, ca', + array( + 'en_GB_oxendict', + 'de_DE', + 'ca_valencia', + 'ca', + 'ca_CA', + ), + ), + 'Longer variants, with transient' => array( + 'en-GB-oxendict, de-DE, ca-valencia, ca', + array( + 'de_DE', + 'ca', + ), + true, + ), + 'Multiple types, weighed' => array( + 'fr-BE, fr;q=0.7, en;q=0.6, de;q=0.8, es-ES;q=0.5', + array( + 'fr_BE', + 'de', + 'de_DE', + 'fr', + 'fr_FR', + ), + ), + 'Multiple types, weighed, with transient' => array( + 'fr-BE, fr;q=0.7, en;q=0.6, de;q=0.8, es-ES;q=0.5', + array( + 'fr_BE', + 'de_DE', + 'de_AT', + 'de_CH', + 'de_CH_informal', + 'de_DE_formal', + 'fr_FR', + 'fr_CA', + ), + true, + ), + 'Multiple types, weighed, with wildcard' => array( + 'fr-BE, fr;q=0.7, *;q=0.6, de;q=0.8, es-ES;q=0.5', + array( + 'fr_BE', + 'de', + 'de_DE', + 'fr', + 'fr_FR', + ), + ), + 'Multiple types, weighed, with wildcard, with transient' => array( + 'fr-BE, fr;q=0.7, *;q=0.6, de;q=0.8, es-ES;q=0.5', + array( + 'fr_BE', + 'de_DE', + 'de_AT', + 'de_CH', + 'de_CH_informal', + 'de_DE_formal', + 'fr_FR', + 'fr_CA', + ), + true, + ), + 'Equal weights keep original order' => array( + 'pt-BR;q=0.8, es-ES;q=0.8, de-DE;q=0.8', + array( + 'pt_BR', + 'es_ES', + 'de_DE', + ), + ), + 'Zero weight is not acceptable' => array( + 'fr;q=0, de-DE', + array( 'de_DE' ), + ), + 'Invalid weights are ignored' => array( + 'fr;q=2, es;q=abc, it;q=0.5555, de-DE;q=0.5', + array( 'de_DE' ), + ), + 'Other parameters are ignored' => array( + 'it;level=1;q=0.5, de-DE', + array( + 'de_DE', + 'it', + 'it_IT', + ), + ), + 'Invalid codes are ignored' => array( + 'x-