Skip to content

Commit

Permalink
Added option to disable public lang autodetect
Browse files Browse the repository at this point in the history
Also cleaned up localization middleware a little.
Closes #944
  • Loading branch information
ssddanbrown committed Aug 12, 2018
1 parent fcdb39e commit fcb93dc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 11 deletions.
33 changes: 23 additions & 10 deletions app/Http/Middleware/Localization.php
Expand Up @@ -2,6 +2,7 @@

use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;

class Localization
{
Expand All @@ -15,21 +16,33 @@ class Localization
public function handle($request, Closure $next)
{
$defaultLang = config('app.locale');
if (user()->isDefault()) {
$locale = $defaultLang;
$availableLocales = config('app.locales');
foreach ($request->getLanguages() as $lang) {
if (!in_array($lang, $availableLocales)) {
continue;
}
$locale = $lang;
break;
}

if (user()->isDefault() && config('app.auto_detect_locale')) {
$locale = $this->autoDetectLocale($request, $defaultLang);
} else {
$locale = setting()->getUser(user(), 'language', $defaultLang);
}

app()->setLocale($locale);
Carbon::setLocale($locale);
return $next($request);
}

/**
* Autodetect the visitors locale by matching locales in their headers
* against the locales supported by BookStack.
* @param Request $request
* @param string $default
* @return string
*/
protected function autoDetectLocale(Request $request, string $default)
{
$availableLocales = config('app.locales');
foreach ($request->getLanguages() as $lang) {
if (in_array($lang, $availableLocales)) {
return $lang;
}
}
return $default;
}
}
15 changes: 14 additions & 1 deletion config/app.php
Expand Up @@ -77,8 +77,21 @@
*/

'locale' => env('APP_LANG', 'en'),

'locales' => ['en', 'de', 'es', 'es_AR', 'fr', 'nl', 'pt_BR', 'sk', 'sv', 'ja', 'pl', 'it', 'ru', 'zh_CN', 'zh_TW'],

/*
|--------------------------------------------------------------------------
| Auto-detect the locale for public users
|--------------------------------------------------------------------------
|
| For public users their locale can be guessed by headers sent by their
| browser. This is usually set by users in their browser settings.
| If not found the default app locale will be used.
|
*/
'auto_detect_locale' => env('APP_AUTO_LANG_PUBLIC', true),

/*
|--------------------------------------------------------------------------
| Application Fallback Locale
Expand Down Expand Up @@ -245,7 +258,7 @@
'Activity' => BookStack\Services\Facades\Activity::class,
'Setting' => BookStack\Services\Facades\Setting::class,
'Views' => BookStack\Services\Facades\Views::class,
'Images' => \BookStack\Services\Facades\Images::class,
'Images' => BookStack\Services\Facades\Images::class,

],

Expand Down

0 comments on commit fcb93dc

Please sign in to comment.