3 namespace BookStack\Http\Middleware;
7 use Illuminate\Http\Request;
12 * Array of right-to-left locales.
14 protected $rtlLocales = ['ar', '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',
59 * Handle an incoming request.
61 * @param \Illuminate\Http\Request $request
62 * @param \Closure $next
66 public function handle($request, Closure $next)
68 $defaultLang = config('app.locale');
69 config()->set('app.default_locale', $defaultLang);
71 $locale = $this->getUserLocale($request, $defaultLang);
72 config()->set('app.lang', str_replace('_', '-', $this->getLocaleIso($locale)));
75 if (in_array($locale, $this->rtlLocales)) {
76 config()->set('app.rtl', true);
79 app()->setLocale($locale);
80 Carbon::setLocale($locale);
81 $this->setSystemDateLocale($locale);
83 return $next($request);
87 * Get the locale specifically for the currently logged in user if available.
89 protected function getUserLocale(Request $request, string $default): string
93 } catch (\Exception $exception) {
97 if ($user->isDefault() && config('app.auto_detect_locale')) {
98 return $this->autoDetectLocale($request, $default);
101 return setting()->getUser($user, 'language', $default);
105 * Autodetect the visitors locale by matching locales in their headers
106 * against the locales supported by BookStack.
108 protected function autoDetectLocale(Request $request, string $default): string
110 $availableLocales = config('app.locales');
111 foreach ($request->getLanguages() as $lang) {
112 if (in_array($lang, $availableLocales)) {
121 * Get the ISO version of a BookStack language name.
123 public function getLocaleIso(string $locale): string
125 return $this->localeMap[$locale] ?? $locale;
129 * Set the system date locale for localized date formatting.
130 * Will try both the standard locale name and the UTF8 variant.
132 protected function setSystemDateLocale(string $locale)
134 $systemLocale = $this->getLocaleIso($locale);
135 $set = setlocale(LC_TIME, $systemLocale);
136 if ($set === false) {
137 setlocale(LC_TIME, $systemLocale . '.utf8');