Changed lang configuration option

This commit is contained in:
Sergio Brighenti 2019-11-19 13:59:17 +01:00
parent 29dd38feb9
commit 3cd5dfbcec
11 changed files with 77 additions and 24 deletions

View file

@ -11,6 +11,7 @@ class AdminController extends Controller
{ {
/** /**
* @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
* @throws FileNotFoundException * @throws FileNotFoundException
@ -18,7 +19,7 @@ class AdminController extends Controller
* @throws \Twig\Error\RuntimeError * @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError * @throws \Twig\Error\SyntaxError
*/ */
public function system(Response $response): Response public function system(Request $request, Response $response): Response
{ {
$usersCount = $this->database->query('SELECT COUNT(*) AS `count` FROM `users`')->fetch()->count; $usersCount = $this->database->query('SELECT COUNT(*) AS `count` FROM `users`')->fetch()->count;
$mediasCount = $this->database->query('SELECT COUNT(*) AS `count` FROM `uploads`')->fetch()->count; $mediasCount = $this->database->query('SELECT COUNT(*) AS `count` FROM `uploads`')->fetch()->count;
@ -41,6 +42,7 @@ class AdminController extends Controller
'post_max_size' => ini_get('post_max_size'), 'post_max_size' => ini_get('post_max_size'),
'upload_max_filesize' => ini_get('upload_max_filesize'), 'upload_max_filesize' => ini_get('upload_max_filesize'),
'installed_lang' => $this->lang->getList(), 'installed_lang' => $this->lang->getList(),
'forced_lang' => $request->getAttribute('forced_lang')
]); ]);
} }
@ -78,15 +80,15 @@ class AdminController extends Controller
*/ */
public function applyLang(Request $request, Response $response): Response public function applyLang(Request $request, Response $response): Response
{ {
$config = require BASE_DIR.'config.php';
if (param($request, 'lang') !== 'auto') { if (param($request, 'lang') !== 'auto') {
$config['lang'] = param($request, 'lang'); if (!$this->database->query('SELECT `value` FROM `settings` WHERE `key` = \'lang\'')->fetch()) {
$this->database->query('INSERT INTO `settings`(`key`, `value`) VALUES (\'lang\', ?)', param($request, 'lang'));
} else { } else {
unset($config['lang']); $this->database->query('UPDATE `settings` SET `value`=? WHERE `key` = \'lang\'', param($request, 'lang'));
}
} else {
$this->database->query('DELETE FROM `settings` WHERE `key` = \'lang\'');
} }
file_put_contents(BASE_DIR.'config.php', '<?php'.PHP_EOL.'return '.var_export($config, true).';');
$this->session->alert(lang('lang_set', [param($request, 'lang')])); $this->session->alert(lang('lang_set', [param($request, 'lang')]));

View file

@ -5,6 +5,7 @@ namespace App\Controllers;
use App\Database\DB; use App\Database\DB;
use App\Web\Lang; use App\Web\Lang;
use App\Web\Session; use App\Web\Session;
use App\Web\View;
use DI\Container; use DI\Container;
use DI\DependencyException; use DI\DependencyException;
use DI\NotFoundException; use DI\NotFoundException;
@ -14,11 +15,10 @@ use Monolog\Logger;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Exception\HttpNotFoundException; use Slim\Exception\HttpNotFoundException;
use Slim\Exception\HttpUnauthorizedException; use Slim\Exception\HttpUnauthorizedException;
use Twig\Environment;
/** /**
* @property Session|null session * @property Session|null session
* @property Environment view * @property View view
* @property DB|null database * @property DB|null database
* @property Logger|null logger * @property Logger|null logger
* @property Filesystem|null storage * @property Filesystem|null storage

View file

@ -26,7 +26,7 @@ class ViewFactory
'auto_reload' => $config['debug'], 'auto_reload' => $config['debug'],
]); ]);
$request = ServerRequestCreatorFactory::create()->createServerRequestFromGlobals(); $request = ServerRequestCreatorFactory::determineServerRequestCreator()->createServerRequestFromGlobals();
$twig->addGlobal('config', $config); $twig->addGlobal('config', $config);
$twig->addGlobal('request', $request); $twig->addGlobal('request', $request);
@ -42,6 +42,7 @@ class ViewFactory
$twig->addFunction(new TwigFunction('mime2font', 'mime2font')); $twig->addFunction(new TwigFunction('mime2font', 'mime2font'));
$twig->addFunction(new TwigFunction('queryParams', 'queryParams')); $twig->addFunction(new TwigFunction('queryParams', 'queryParams'));
$twig->addFunction(new TwigFunction('isDisplayableImage', 'isDisplayableImage')); $twig->addFunction(new TwigFunction('isDisplayableImage', 'isDisplayableImage'));
$twig->addFunction(new TwigFunction('inPath', 'inPath'));
return new View($twig); return new View($twig);
} }
@ -57,7 +58,7 @@ class ViewFactory
'auto_reload' => $config['debug'], 'auto_reload' => $config['debug'],
]); ]);
$request = ServerRequestCreatorFactory::create()->createServerRequestFromGlobals(); $request = ServerRequestCreatorFactory::determineServerRequestCreator()->createServerRequestFromGlobals();
$twig->addGlobal('config', $config); $twig->addGlobal('config', $config);
$twig->addGlobal('request', $request); $twig->addGlobal('request', $request);

View file

@ -0,0 +1,29 @@
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
class LangMiddleware extends Middleware
{
/**
* @param Request $request
* @param RequestHandler $handler
* @return Response
*/
public function __invoke(Request $request, RequestHandler $handler)
{
$forcedLang = $this->database->query('SELECT `value` FROM `settings` WHERE `key` = \'lang\'')->fetch();
if ($forcedLang) {
$this->lang::setLang($forcedLang->value);
$request = $request->withAttribute('forced_lang', $forcedLang->value);
}
return $handler->handle($request);
}
}

View file

@ -72,6 +72,15 @@ class Lang
return self::$lang; return self::$lang;
} }
/**
* @param $lang
*/
public static function setLang($lang)
{
self::$lang = $lang;
}
/** /**
* @return array * @return array
*/ */

View file

@ -352,8 +352,7 @@ if (!function_exists('queryParams')) {
*/ */
function queryParams(array $replace = []) function queryParams(array $replace = [])
{ {
$serverRequestCreator = ServerRequestCreatorFactory::create(); $request = ServerRequestCreatorFactory::determineServerRequestCreator()->createServerRequestFromGlobals();
$request = $serverRequestCreator->createServerRequestFromGlobals();
$params = array_replace_recursive($request->getQueryParams(), $replace); $params = array_replace_recursive($request->getQueryParams(), $replace);
@ -361,6 +360,20 @@ if (!function_exists('queryParams')) {
} }
} }
if (!function_exists('inPath')) {
/**
* Check if uri start with a path
* @param string $uri
* @param string $path
* @return bool
*/
function inPath(string $uri, string $path): bool
{
$path = parse_url(urlFor($path), PHP_URL_PATH);
return substr($uri, 0, strlen($uri)) === $path;
}
}
if (!function_exists('glob_recursive')) { if (!function_exists('glob_recursive')) {
/** /**
* Does not support flag GLOB_BRACE * Does not support flag GLOB_BRACE

View file

@ -4,6 +4,7 @@ use App\Exception\Handlers\AppErrorHandler;
use App\Exception\Handlers\Renderers\HtmlErrorRenderer; use App\Exception\Handlers\Renderers\HtmlErrorRenderer;
use App\Factories\ViewFactory; use App\Factories\ViewFactory;
use App\Middleware\InjectMiddleware; use App\Middleware\InjectMiddleware;
use App\Middleware\LangMiddleware;
use App\Middleware\RememberMiddleware; use App\Middleware\RememberMiddleware;
use App\Web\View; use App\Web\View;
use DI\Bridge\Slim\Bridge; use DI\Bridge\Slim\Bridge;
@ -67,6 +68,7 @@ if (!$config['debug']) {
} }
$app->add(InjectMiddleware::class); $app->add(InjectMiddleware::class);
$app->add(LangMiddleware::class);
$app->add(RememberMiddleware::class); $app->add(RememberMiddleware::class);
// Permanently redirect paths with a trailing slash to their non-trailing counterpart // Permanently redirect paths with a trailing slash to their non-trailing counterpart

View file

@ -91,11 +91,7 @@ return [
}), }),
'storage' => get(Filesystem::class), 'storage' => get(Filesystem::class),
Lang::class => factory(function (Container $container) { Lang::class => factory(function () {
$config = $container->get('config');
if (isset($config['lang'])) {
return Lang::build($config['lang'], BASE_DIR.'resources/lang/');
}
return Lang::build(Lang::recognize(), BASE_DIR.'resources/lang/'); return Lang::build(Lang::recognize(), BASE_DIR.'resources/lang/');
}), }),
'lang' => get(Lang::class), 'lang' => get(Lang::class),

View file

@ -204,6 +204,7 @@ $app->post('/', function (Request $request, Response $response, Filesystem $stor
// if is upgrading and existing installation, put it out maintenance // if is upgrading and existing installation, put it out maintenance
if ($installed) { if ($installed) {
unset($config['maintenance']); unset($config['maintenance']);
unset($config['lang']);
} }
// Finally write the config // Finally write the config

View file

@ -7,23 +7,23 @@
<div class="collapse navbar-collapse" id="navbarCollapse"> <div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto"> <ul class="navbar-nav mr-auto">
<li class="nav-item"> <li class="nav-item">
<a href="{{ route('home') }}" class="nav-link {{ request.uri.path starts with '/home' ? 'active' }}"><i class="fas fa-fw fa-home"></i> <a href="{{ route('home') }}" class="nav-link {{ inPath(request.uri.path, '/home') ? 'active' }}"><i class="fas fa-fw fa-home"></i>
{{ lang('home') }} {{ lang('home') }}
</a> </a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a href="{{ route('upload') }}" class="nav-link {{ request.uri.path starts with '/upload' ? 'active' }}"><i class="fas fa-fw fa-upload"></i> <a href="{{ route('upload') }}" class="nav-link {{ inPath(request.uri.path, '/upload') ? 'active' }}"><i class="fas fa-fw fa-upload"></i>
{{ lang('upload') }} {{ lang('upload') }}
</a> </a>
</li> </li>
{% if session.get('admin') %} {% if session.get('admin') %}
<li class="nav-item"> <li class="nav-item">
<a href="{{ route('user.index') }}" class="nav-link {{ request.uri.path starts with '/user' ? 'active' }}"><i class="fas fa-fw fa-users"></i> <a href="{{ route('user.index') }}" class="nav-link {{ inPath(request.uri.path, '/users') ? 'active' }}"><i class="fas fa-fw fa-users"></i>
{{ lang('users') }} {{ lang('users') }}
</a> </a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a href="{{ route('system') }}" class="nav-link {{ request.uri.path starts with '/system' ? 'active' }}"><i class="fas fa-fw fa-cog"></i> <a href="{{ route('system') }}" class="nav-link {{ inPath(request.uri.path, '/system') ? 'active' }}"><i class="fas fa-fw fa-cog"></i>
{{ lang('system') }} {{ lang('system') }}
</a> </a>
</li> </li>

View file

@ -86,9 +86,9 @@
<div class="form-group row"> <div class="form-group row">
<div class="col-sm-12"> <div class="col-sm-12">
<select class="form-control" id="lang" name="lang"> <select class="form-control" id="lang" name="lang">
<option value="auto" selected>({{ lang('auto_set') }})</option> <option value="auto">({{ lang('auto_set') }})</option>
{% for lang, name in installed_lang %} {% for lang, name in installed_lang %}
<option value="{{ lang }}">{{ name }}</option> <option value="{{ lang }}"{{ forced_lang == lang ? ' selected' }}>{{ name }}</option>
{% endfor %} {% endfor %}
</select> </select>
<small>{{ lang('default_lang_behavior') }}</small> <small>{{ lang('default_lang_behavior') }}</small>