Locales: Performed cleanup and alignment of locale handling

- Reduced app settings down to what's required.
- Used new view-shared $locale object instead of using globals via
  config.
- Aligned language used to default on "locale" instead of mixing
  locale/language.

For #4501
This commit is contained in:
Dan Brown 2023-09-17 13:29:06 +01:00
parent b292cf7090
commit ac9a65945f
No known key found for this signature in database
GPG Key ID: 46D9F943C24A2EF9
14 changed files with 116 additions and 80 deletions

View File

@ -83,10 +83,10 @@ return [
'timezone' => env('APP_TIMEZONE', 'UTC'), 'timezone' => env('APP_TIMEZONE', 'UTC'),
// Default locale to use // Default locale to use
// A default variant is also stored since Laravel can overwrite
// app.locale when dynamically setting the locale in-app.
'locale' => env('APP_LANG', 'en'), 'locale' => env('APP_LANG', 'en'),
'default_locale' => env('APP_LANG', 'en'),
// Locales available
'locales' => ['en', 'ar', 'bg', 'bs', 'ca', 'cs', 'cy', 'da', 'de', 'de_informal', 'el', 'es', 'es_AR', 'et', 'eu', 'fa', 'fr', 'he', 'hr', 'hu', 'id', 'it', 'ja', 'ka', 'ko', 'lt', 'lv', 'nl', 'nb', 'pt', 'pt_BR', 'sk', 'sl', 'sv', 'pl', 'ro', 'ru', 'tr', 'uk', 'uz', 'vi', 'zh_CN', 'zh_TW'],
// Application Fallback Locale // Application Fallback Locale
'fallback_locale' => 'en', 'fallback_locale' => 'en',
@ -94,9 +94,6 @@ return [
// Faker Locale // Faker Locale
'faker_locale' => 'en_GB', 'faker_locale' => 'en_GB',
// Enable right-to-left text control.
'rtl' => false,
// Auto-detect the locale for public users // Auto-detect the locale for public users
// For public users their locale can be guessed by headers sent by their // For public users their locale can be guessed by headers sent by their
// browser. This is usually set by users in their browser settings. // browser. This is usually set by users in their browser settings.

View File

@ -2,17 +2,14 @@
namespace BookStack\Http\Middleware; namespace BookStack\Http\Middleware;
use BookStack\Translation\LanguageManager; use BookStack\Translation\LocaleManager;
use Carbon\Carbon;
use Closure; use Closure;
class Localization class Localization
{ {
protected LanguageManager $languageManager; public function __construct(
protected LocaleManager $localeManager
public function __construct(LanguageManager $languageManager) ) {
{
$this->languageManager = $languageManager;
} }
/** /**
@ -25,22 +22,12 @@ class Localization
*/ */
public function handle($request, Closure $next) public function handle($request, Closure $next)
{ {
// Get and record the default language in the config // Share details of the user's locale for use in views
$defaultLang = config('app.locale'); $userLocale = $this->localeManager->getForUser(user());
config()->set('app.default_locale', $defaultLang); view()->share('locale', $userLocale);
// Get the user's language and record that in the config for use in views // Set locale for system components
$userLang = $this->languageManager->getUserLanguage($request, $defaultLang); $this->localeManager->setAppLocale($userLocale);
config()->set('app.lang', str_replace('_', '-', $this->languageManager->getIsoName($userLang)));
// Set text direction
if ($this->languageManager->isRTL($userLang)) {
config()->set('app.rtl', true);
}
app()->setLocale($userLang);
Carbon::setLocale($userLang);
$this->languageManager->setPhpDateTimeLocale($userLang);
return $next($request); return $next($request);
} }

View File

@ -0,0 +1,45 @@
<?php
namespace BookStack\Translation;
class LocaleDefinition
{
public function __construct(
protected string $appName,
protected string $isoName,
protected bool $isRtl
) {
}
/**
* Provide the BookStack-specific locale name.
*/
public function appLocale(): string
{
return $this->appName;
}
/**
* Provide the ISO-aligned locale name.
*/
public function isoLocale(): string
{
return $this->isoName;
}
/**
* Returns a string suitable for the HTML "lang" attribute.
*/
public function htmlLang(): string
{
return str_replace('_', '-', $this->isoName);
}
/**
* Returns a string suitable for the HTML "dir" attribute.
*/
public function htmlDirection(): string
{
return $this->isRtl ? 'rtl' : 'ltr';
}
}

View File

@ -3,17 +3,18 @@
namespace BookStack\Translation; namespace BookStack\Translation;
use BookStack\Users\Models\User; use BookStack\Users\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request; use Illuminate\Http\Request;
class LanguageManager class LocaleManager
{ {
/** /**
* Array of right-to-left language options. * Array of right-to-left locale options.
*/ */
protected array $rtlLanguages = ['ar', 'fa', 'he']; protected array $rtlLocales = ['ar', 'fa', 'he'];
/** /**
* Map of BookStack language names to best-estimate ISO and windows locale names. * Map of BookStack locale names to best-estimate ISO and windows locale names.
* Locales can often be found by running `locale -a` on a linux system. * Locales can often be found by running `locale -a` on a linux system.
* Windows locales can be found at: * Windows locales can be found at:
* https://docs.microsoft.com/en-us/cpp/c-runtime-library/language-strings?view=msvc-170. * https://docs.microsoft.com/en-us/cpp/c-runtime-library/language-strings?view=msvc-170.
@ -29,8 +30,8 @@ class LanguageManager
'da' => ['iso' => 'da_DK', 'windows' => 'Danish'], 'da' => ['iso' => 'da_DK', 'windows' => 'Danish'],
'de' => ['iso' => 'de_DE', 'windows' => 'German'], 'de' => ['iso' => 'de_DE', 'windows' => 'German'],
'de_informal' => ['iso' => 'de_DE', 'windows' => 'German'], 'de_informal' => ['iso' => 'de_DE', 'windows' => 'German'],
'en' => ['iso' => 'en_GB', 'windows' => 'English'],
'el' => ['iso' => 'el_GR', 'windows' => 'Greek'], 'el' => ['iso' => 'el_GR', 'windows' => 'Greek'],
'en' => ['iso' => 'en_GB', 'windows' => 'English'],
'es' => ['iso' => 'es_ES', 'windows' => 'Spanish'], 'es' => ['iso' => 'es_ES', 'windows' => 'Spanish'],
'es_AR' => ['iso' => 'es_AR', 'windows' => 'Spanish'], 'es_AR' => ['iso' => 'es_AR', 'windows' => 'Spanish'],
'et' => ['iso' => 'et_EE', 'windows' => 'Estonian'], 'et' => ['iso' => 'et_EE', 'windows' => 'Estonian'],
@ -46,8 +47,8 @@ class LanguageManager
'ko' => ['iso' => 'ko_KR', 'windows' => 'Korean'], 'ko' => ['iso' => 'ko_KR', 'windows' => 'Korean'],
'lt' => ['iso' => 'lt_LT', 'windows' => 'Lithuanian'], 'lt' => ['iso' => 'lt_LT', 'windows' => 'Lithuanian'],
'lv' => ['iso' => 'lv_LV', 'windows' => 'Latvian'], 'lv' => ['iso' => 'lv_LV', 'windows' => 'Latvian'],
'nl' => ['iso' => 'nl_NL', 'windows' => 'Dutch'],
'nb' => ['iso' => 'nb_NO', 'windows' => 'Norwegian (Bokmal)'], 'nb' => ['iso' => 'nb_NO', 'windows' => 'Norwegian (Bokmal)'],
'nl' => ['iso' => 'nl_NL', 'windows' => 'Dutch'],
'pl' => ['iso' => 'pl_PL', 'windows' => 'Polish'], 'pl' => ['iso' => 'pl_PL', 'windows' => 'Polish'],
'pt' => ['iso' => 'pt_PT', 'windows' => 'Portuguese'], 'pt' => ['iso' => 'pt_PT', 'windows' => 'Portuguese'],
'pt_BR' => ['iso' => 'pt_BR', 'windows' => 'Portuguese'], 'pt_BR' => ['iso' => 'pt_BR', 'windows' => 'Portuguese'],
@ -56,47 +57,40 @@ class LanguageManager
'sk' => ['iso' => 'sk_SK', 'windows' => 'Slovak'], 'sk' => ['iso' => 'sk_SK', 'windows' => 'Slovak'],
'sl' => ['iso' => 'sl_SI', 'windows' => 'Slovenian'], 'sl' => ['iso' => 'sl_SI', 'windows' => 'Slovenian'],
'sv' => ['iso' => 'sv_SE', 'windows' => 'Swedish'], 'sv' => ['iso' => 'sv_SE', 'windows' => 'Swedish'],
'tr' => ['iso' => 'tr_TR', 'windows' => 'Turkish'],
'uk' => ['iso' => 'uk_UA', 'windows' => 'Ukrainian'], 'uk' => ['iso' => 'uk_UA', 'windows' => 'Ukrainian'],
'uz' => ['iso' => 'uz_UZ', 'windows' => 'Uzbek'], 'uz' => ['iso' => 'uz_UZ', 'windows' => 'Uzbek'],
'vi' => ['iso' => 'vi_VN', 'windows' => 'Vietnamese'], 'vi' => ['iso' => 'vi_VN', 'windows' => 'Vietnamese'],
'zh_CN' => ['iso' => 'zh_CN', 'windows' => 'Chinese (Simplified)'], 'zh_CN' => ['iso' => 'zh_CN', 'windows' => 'Chinese (Simplified)'],
'zh_TW' => ['iso' => 'zh_TW', 'windows' => 'Chinese (Traditional)'], 'zh_TW' => ['iso' => 'zh_TW', 'windows' => 'Chinese (Traditional)'],
'tr' => ['iso' => 'tr_TR', 'windows' => 'Turkish'],
]; ];
/** /**
* Get the language specifically for the currently logged-in user if available. * Get the BookStack locale string for the given user.
*/ */
public function getUserLanguage(Request $request, string $default): string protected function getLocaleForUser(User $user): string
{ {
try { $default = config('app.default_locale');
$user = user();
} catch (\Exception $exception) {
return $default;
}
if ($user->isGuest() && config('app.auto_detect_locale')) { if ($user->isGuest() && config('app.auto_detect_locale')) {
return $this->autoDetectLocale($request, $default); return $this->autoDetectLocale(request(), $default);
} }
return setting()->getUser($user, 'language', $default); return setting()->getUser($user, 'language', $default);
} }
/** /**
* Get the language for the given user. * Get a locale definition for the current user.
*/ */
public function getLanguageForUser(User $user): string public function getForUser(User $user): LocaleDefinition
{ {
$default = config('app.locale'); $localeString = $this->getLocaleForUser($user);
return setting()->getUser($user, 'language', $default);
}
/** return new LocaleDefinition(
* Check if the given BookStack language value is a right-to-left language. $localeString,
*/ $this->getIsoName($localeString),
public function isRTL(string $language): bool in_array($localeString, $this->rtlLocales),
{ );
return in_array($language, $this->rtlLanguages);
} }
/** /**
@ -105,7 +99,8 @@ class LanguageManager
*/ */
protected function autoDetectLocale(Request $request, string $default): string protected function autoDetectLocale(Request $request, string $default): string
{ {
$availableLocales = config('app.locales'); $availableLocales = array_keys($this->localeMap);
foreach ($request->getLanguages() as $lang) { foreach ($request->getLanguages() as $lang) {
if (in_array($lang, $availableLocales)) { if (in_array($lang, $availableLocales)) {
return $lang; return $lang;
@ -116,29 +111,40 @@ class LanguageManager
} }
/** /**
* Get the ISO version of a BookStack language name. * Get the ISO version of a BookStack locale.
*/ */
public function getIsoName(string $language): string protected function getIsoName(string $locale): string
{ {
return $this->localeMap[$language]['iso'] ?? $language; return $this->localeMap[$locale]['iso'] ?? $locale;
}
/**
* Sets the active locale for system level components.
*/
public function setAppLocale(LocaleDefinition $locale): void
{
app()->setLocale($locale->appLocale());
Carbon::setLocale($locale->isoLocale());
$this->setPhpDateTimeLocale($locale);
} }
/** /**
* Set the system date locale for localized date formatting. * Set the system date locale for localized date formatting.
* Will try both the standard locale name and the UTF8 variant. * Will try both the standard locale name and the UTF8 variant.
*/ */
public function setPhpDateTimeLocale(string $language): void public function setPhpDateTimeLocale(LocaleDefinition $locale): void
{ {
$isoLang = $this->localeMap[$language]['iso'] ?? ''; $appLocale = $locale->appLocale();
$isoLangPrefix = explode('_', $isoLang)[0]; $isoLocale = $this->localeMap[$appLocale]['iso'] ?? '';
$isoLocalePrefix = explode('_', $isoLocale)[0];
$locales = array_values(array_filter([ $locales = array_values(array_filter([
$isoLang ? $isoLang . '.utf8' : false, $isoLocale ? $isoLocale . '.utf8' : false,
$isoLang ?: false, $isoLocale ?: false,
$isoLang ? str_replace('_', '-', $isoLang) : false, $isoLocale ? str_replace('_', '-', $isoLocale) : false,
$isoLang ? $isoLangPrefix . '.UTF-8' : false, $isoLocale ? $isoLocalePrefix . '.UTF-8' : false,
$this->localeMap[$language]['windows'] ?? false, $this->localeMap[$appLocale]['windows'] ?? false,
$language, $appLocale,
])); ]));
if (!empty($locales)) { if (!empty($locales)) {

View File

@ -12,7 +12,7 @@ use BookStack\Api\ApiToken;
use BookStack\App\Model; use BookStack\App\Model;
use BookStack\App\Sluggable; use BookStack\App\Sluggable;
use BookStack\Entities\Tools\SlugGenerator; use BookStack\Entities\Tools\SlugGenerator;
use BookStack\Translation\LanguageManager; use BookStack\Translation\LocaleManager;
use BookStack\Uploads\Image; use BookStack\Uploads\Image;
use Carbon\Carbon; use Carbon\Carbon;
use Exception; use Exception;
@ -346,7 +346,7 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon
*/ */
public function getLanguage(): string public function getLanguage(): string
{ {
return app()->make(LanguageManager::class)->getLanguageForUser($this); return app()->make(LocaleManager::class)->getForUser($this)->appLocale();
} }
/** /**

View File

@ -1,6 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="{{ config('app.lang') }}" <html lang="{{ $locale->htmlLang() }}"
dir="{{ config('app.rtl') ? 'rtl' : 'ltr' }}" dir="{{ $locale->htmlDirection() }}"
class="{{ setting()->getForCurrentUser('dark-mode-enabled') ? 'dark-mode ' : '' }}"> class="{{ setting()->getForCurrentUser('dark-mode-enabled') ? 'dark-mode ' : '' }}">
<head> <head>
<title>{{ isset($pageTitle) ? $pageTitle . ' | ' : '' }}{{ setting('app-name') }}</title> <title>{{ isset($pageTitle) ? $pageTitle . ' | ' : '' }}{{ setting('app-name') }}</title>

View File

@ -1,5 +1,5 @@
<!doctype html> <!doctype html>
<html lang="{{ config('app.lang') }}"> <html lang="{{ $locale->htmlLang() }}">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>@yield('title')</title> <title>@yield('title')</title>

View File

@ -1,6 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="{{ config('app.lang') }}" <html lang="{{ $locale->htmlLang() }}"
dir="{{ config('app.rtl') ? 'rtl' : 'ltr' }}" dir="{{ $locale->htmlDirection() }}"
class="@yield('document-class')"> class="@yield('document-class')">
<head> <head>
<title>{{ isset($pageTitle) ? $pageTitle . ' | ' : '' }}{{ setting('app-name') }}</title> <title>{{ isset($pageTitle) ? $pageTitle . ' | ' : '' }}{{ setting('app-name') }}</title>

View File

@ -1,6 +1,6 @@
<div id="markdown-editor" component="markdown-editor" <div id="markdown-editor" component="markdown-editor"
option:markdown-editor:page-id="{{ $model->id ?? 0 }}" option:markdown-editor:page-id="{{ $model->id ?? 0 }}"
option:markdown-editor:text-direction="{{ config('app.rtl') ? 'rtl' : 'ltr' }}" option:markdown-editor:text-direction="{{ $locale->htmlDirection() }}"
option:markdown-editor:image-upload-error-text="{{ trans('errors.image_upload_error') }}" option:markdown-editor:image-upload-error-text="{{ trans('errors.image_upload_error') }}"
option:markdown-editor:server-upload-limit-text="{{ trans('errors.server_upload_limit') }}" option:markdown-editor:server-upload-limit-text="{{ trans('errors.server_upload_limit') }}"
class="flex-fill flex code-fill"> class="flex-fill flex code-fill">

View File

@ -3,9 +3,9 @@
@endpush @endpush
<div component="wysiwyg-editor" <div component="wysiwyg-editor"
option:wysiwyg-editor:language="{{ config('app.lang') }}" option:wysiwyg-editor:language="{{ $locale->htmlLang() }}"
option:wysiwyg-editor:page-id="{{ $model->id ?? 0 }}" option:wysiwyg-editor:page-id="{{ $model->id ?? 0 }}"
option:wysiwyg-editor:text-direction="{{ config('app.rtl') ? 'rtl' : 'ltr' }}" option:wysiwyg-editor:text-direction="{{ $locale->htmlDirection() }}"
option:wysiwyg-editor:image-upload-error-text="{{ trans('errors.image_upload_error') }}" option:wysiwyg-editor:image-upload-error-text="{{ trans('errors.image_upload_error') }}"
option:wysiwyg-editor:server-upload-limit-text="{{ trans('errors.server_upload_limit') }}" option:wysiwyg-editor:server-upload-limit-text="{{ trans('errors.server_upload_limit') }}"
class="flex-fill flex"> class="flex-fill flex">

View File

@ -14,7 +14,7 @@
<div class="setting-list"> <div class="setting-list">
@include('users.parts.form') @include('users.parts.form')
@include('users.parts.language-option-row', ['value' => old('setting.language') ?? config('app.default_locale')]) @include('users.parts.language-option-row', ['value' => old('setting.language') ?? config('app.locale')])
</div> </div>
<div class="form-group text-right"> <div class="form-group text-right">

View File

@ -33,7 +33,7 @@
</div> </div>
</div> </div>
@include('users.parts.language-option-row', ['value' => setting()->getUser($user, 'language', config('app.default_locale'))]) @include('users.parts.language-option-row', ['value' => $user->getLanguage())])
</div> </div>
<div class="text-right"> <div class="text-right">

View File

@ -1,5 +1,5 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="{{ config('app.lang') }}"> <html lang="{{ $locale->htmlLang() }}">
<head> <head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

View File

@ -78,6 +78,7 @@ class LanguageTest extends TestCase
public function test_rtl_config_set_if_lang_is_rtl() public function test_rtl_config_set_if_lang_is_rtl()
{ {
$this->asEditor(); $this->asEditor();
// TODO - Alter
$this->assertFalse(config('app.rtl'), 'App RTL config should be false by default'); $this->assertFalse(config('app.rtl'), 'App RTL config should be false by default');
setting()->putUser($this->users->editor(), 'language', 'ar'); setting()->putUser($this->users->editor(), 'language', 'ar');
$this->get('/'); $this->get('/');