1 <?php namespace BookStack\Http\Middleware;
5 use Illuminate\Http\Request;
11 * Array of right-to-left locales
14 protected $rtlLocales = ['ar'];
17 * Map of BookStack locale names to best-estimate system locale names.
20 protected $localeMap = [
24 'de_informal' => 'de_DE',
45 * Handle an incoming request.
47 * @param \Illuminate\Http\Request $request
48 * @param \Closure $next
51 public function handle($request, Closure $next)
53 $defaultLang = config('app.locale');
54 config()->set('app.default_locale', $defaultLang);
56 if (user()->isDefault() && config('app.auto_detect_locale')) {
57 $locale = $this->autoDetectLocale($request, $defaultLang);
59 $locale = setting()->getUser(user(), 'language', $defaultLang);
62 config()->set('app.lang', str_replace('_', '-', $this->getLocaleIso($locale)));
65 if (in_array($locale, $this->rtlLocales)) {
66 config()->set('app.rtl', true);
69 app()->setLocale($locale);
70 Carbon::setLocale($locale);
71 $this->setSystemDateLocale($locale);
72 return $next($request);
76 * Autodetect the visitors locale by matching locales in their headers
77 * against the locales supported by BookStack.
78 * @param Request $request
79 * @param string $default
82 protected function autoDetectLocale(Request $request, string $default)
84 $availableLocales = config('app.locales');
85 foreach ($request->getLanguages() as $lang) {
86 if (in_array($lang, $availableLocales)) {
94 * Get the ISO version of a BookStack language name
95 * @param string $locale
98 public function getLocaleIso(string $locale)
100 return $this->localeMap[$locale] ?? $locale;
104 * Set the system date locale for localized date formatting.
105 * Will try both the standard locale name and the UTF8 variant.
106 * @param string $locale
108 protected function setSystemDateLocale(string $locale)
110 $systemLocale = $this->getLocaleIso($locale);
111 $set = setlocale(LC_TIME, $systemLocale);
112 if ($set === false) {
113 setlocale(LC_TIME, $systemLocale . '.utf8');