3 namespace BookStack\Http\Middleware;
7 use Illuminate\Http\Request;
12 * Array of right-to-left locales.
14 protected $rtlLocales = ['ar', 'fa', 'he'];
17 * Map of BookStack locale names to best-estimate system locale names.
18 * Locales can often be found by running `locale -a` on a linux system.
20 protected $localeMap = [
27 'de_informal' => 'de_DE',
60 * Handle an incoming request.
62 * @param \Illuminate\Http\Request $request
63 * @param \Closure $next
67 public function handle($request, Closure $next)
69 $defaultLang = config('app.locale');
70 config()->set('app.default_locale', $defaultLang);
72 $locale = $this->getUserLocale($request, $defaultLang);
73 config()->set('app.lang', str_replace('_', '-', $this->getLocaleIso($locale)));
76 if (in_array($locale, $this->rtlLocales)) {
77 config()->set('app.rtl', true);
80 app()->setLocale($locale);
81 Carbon::setLocale($locale);
82 $this->setSystemDateLocale($locale);
84 return $next($request);
88 * Get the locale specifically for the currently logged in user if available.
90 protected function getUserLocale(Request $request, string $default): string
94 } catch (\Exception $exception) {
98 if ($user->isDefault() && config('app.auto_detect_locale')) {
99 return $this->autoDetectLocale($request, $default);
102 return setting()->getUser($user, 'language', $default);
106 * Autodetect the visitors locale by matching locales in their headers
107 * against the locales supported by BookStack.
109 protected function autoDetectLocale(Request $request, string $default): string
111 $availableLocales = config('app.locales');
112 foreach ($request->getLanguages() as $lang) {
113 if (in_array($lang, $availableLocales)) {
122 * Get the ISO version of a BookStack language name.
124 public function getLocaleIso(string $locale): string
126 return $this->localeMap[$locale] ?? $locale;
130 * Set the system date locale for localized date formatting.
131 * Will try both the standard locale name and the UTF8 variant.
133 protected function setSystemDateLocale(string $locale)
135 $systemLocale = $this->getLocaleIso($locale);
136 $set = setlocale(LC_TIME, $systemLocale);
137 if ($set === false) {
138 setlocale(LC_TIME, $systemLocale . '.utf8');