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',
58 * Handle an incoming request.
60 * @param \Illuminate\Http\Request $request
61 * @param \Closure $next
65 public function handle($request, Closure $next)
67 $defaultLang = config('app.locale');
68 config()->set('app.default_locale', $defaultLang);
70 $locale = $this->getUserLocale($request, $defaultLang);
71 config()->set('app.lang', str_replace('_', '-', $this->getLocaleIso($locale)));
74 if (in_array($locale, $this->rtlLocales)) {
75 config()->set('app.rtl', true);
78 app()->setLocale($locale);
79 Carbon::setLocale($locale);
80 $this->setSystemDateLocale($locale);
82 return $next($request);
86 * Get the locale specifically for the currently logged in user if available.
88 protected function getUserLocale(Request $request, string $default): string
92 } catch (\Exception $exception) {
96 if ($user->isDefault() && config('app.auto_detect_locale')) {
97 return $this->autoDetectLocale($request, $default);
100 return setting()->getUser($user, 'language', $default);
104 * Autodetect the visitors locale by matching locales in their headers
105 * against the locales supported by BookStack.
107 protected function autoDetectLocale(Request $request, string $default): string
109 $availableLocales = config('app.locales');
110 foreach ($request->getLanguages() as $lang) {
111 if (in_array($lang, $availableLocales)) {
120 * Get the ISO version of a BookStack language name.
122 public function getLocaleIso(string $locale): string
124 return $this->localeMap[$locale] ?? $locale;
128 * Set the system date locale for localized date formatting.
129 * Will try both the standard locale name and the UTF8 variant.
131 protected function setSystemDateLocale(string $locale)
133 $systemLocale = $this->getLocaleIso($locale);
134 $set = setlocale(LC_TIME, $systemLocale);
135 if ($set === false) {
136 setlocale(LC_TIME, $systemLocale . '.utf8');