Apply fixes from StyleCI

[ci skip] [skip ci]
This commit is contained in:
Sergio Brighenti 2020-04-04 10:36:59 +00:00 committed by StyleCI Bot
parent 98db104d7f
commit 07ccdefbde
23 changed files with 2275 additions and 2310 deletions

View file

@ -2,7 +2,6 @@
namespace App\Controllers; namespace App\Controllers;
use League\Flysystem\FileNotFoundException; use League\Flysystem\FileNotFoundException;
use Slim\Http\Request; use Slim\Http\Request;
use Slim\Http\Response; use Slim\Http\Response;
@ -10,84 +9,84 @@ use Slim\Http\Response;
class AdminController extends Controller class AdminController extends Controller
{ {
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
* @throws FileNotFoundException * @throws FileNotFoundException
*/ */
public function system(Request $request, 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;
$orphanFilesCount = $this->database->query('SELECT COUNT(*) AS `count` FROM `uploads` WHERE `user_id` IS NULL')->fetch()->count; $orphanFilesCount = $this->database->query('SELECT COUNT(*) AS `count` FROM `uploads` WHERE `user_id` IS NULL')->fetch()->count;
$medias = $this->database->query('SELECT `uploads`.`storage_path` FROM `uploads`')->fetchAll(); $medias = $this->database->query('SELECT `uploads`.`storage_path` FROM `uploads`')->fetchAll();
$totalSize = 0; $totalSize = 0;
$filesystem = $this->storage; $filesystem = $this->storage;
foreach ($medias as $media) { foreach ($medias as $media) {
$totalSize += $filesystem->getSize($media->storage_path); $totalSize += $filesystem->getSize($media->storage_path);
} }
return $this->view->render($response, 'dashboard/system.twig', [ return $this->view->render($response, 'dashboard/system.twig', [
'usersCount' => $usersCount, 'usersCount' => $usersCount,
'mediasCount' => $mediasCount, 'mediasCount' => $mediasCount,
'orphanFilesCount' => $orphanFilesCount, 'orphanFilesCount' => $orphanFilesCount,
'totalSize' => humanFileSize($totalSize), 'totalSize' => humanFileSize($totalSize),
'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(),
]); ]);
} }
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
*/ */
public function deleteOrphanFiles(Request $request, Response $response): Response public function deleteOrphanFiles(Request $request, Response $response): Response
{ {
$orphans = $this->database->query('SELECT * FROM `uploads` WHERE `user_id` IS NULL')->fetchAll(); $orphans = $this->database->query('SELECT * FROM `uploads` WHERE `user_id` IS NULL')->fetchAll();
$filesystem = $this->storage; $filesystem = $this->storage;
$deleted = 0; $deleted = 0;
foreach ($orphans as $orphan) { foreach ($orphans as $orphan) {
try { try {
$filesystem->delete($orphan->storage_path); $filesystem->delete($orphan->storage_path);
$deleted++; $deleted++;
} catch (FileNotFoundException $e) { } catch (FileNotFoundException $e) {
} }
} }
$this->database->query('DELETE FROM `uploads` WHERE `user_id` IS NULL'); $this->database->query('DELETE FROM `uploads` WHERE `user_id` IS NULL');
$this->session->alert(lang('deleted_orphans', [$deleted])); $this->session->alert(lang('deleted_orphans', [$deleted]));
return redirect($response, 'system'); return redirect($response, 'system');
} }
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
*/ */
public function applyLang(Request $request, Response $response): Response public function applyLang(Request $request, Response $response): Response
{ {
$config = require BASE_DIR . 'config.php'; $config = require BASE_DIR . 'config.php';
if ($request->getParam('lang') !== 'auto') { if ($request->getParam('lang') !== 'auto') {
$config['lang'] = $request->getParam('lang'); $config['lang'] = $request->getParam('lang');
} else { } else {
unset($config['lang']); unset($config['lang']);
} }
file_put_contents(BASE_DIR . 'config.php', '<?php' . PHP_EOL . 'return ' . var_export($config, true) . ';'); file_put_contents(BASE_DIR . 'config.php', '<?php' . PHP_EOL . 'return ' . var_export($config, true) . ';');
$this->session->alert(lang('lang_set', [$request->getParam('lang')])); $this->session->alert(lang('lang_set', [$request->getParam('lang')]));
return redirect($response, 'system'); return redirect($response, 'system');
} }
} }

View file

@ -22,46 +22,46 @@ use Slim\Container;
abstract class Controller abstract class Controller
{ {
/** @var Container */ /** @var Container */
protected $container; protected $container;
public function __construct(Container $container) public function __construct(Container $container)
{ {
$this->container = $container; $this->container = $container;
} }
/** /**
* @param $name * @param $name
* @return mixed|null * @return mixed|null
* @throws \Interop\Container\Exception\ContainerException * @throws \Interop\Container\Exception\ContainerException
*/ */
public function __get($name) public function __get($name)
{ {
if ($this->container->has($name)) { if ($this->container->has($name)) {
return $this->container->get($name); return $this->container->get($name);
} }
return null; return null;
} }
/** /**
* @param $id * @param $id
* @return int * @return int
*/ */
protected function getUsedSpaceByUser($id): int protected function getUsedSpaceByUser($id): int
{ {
$medias = $this->database->query('SELECT `uploads`.`storage_path` FROM `uploads` WHERE `user_id` = ?', $id); $medias = $this->database->query('SELECT `uploads`.`storage_path` FROM `uploads` WHERE `user_id` = ?', $id);
$totalSize = 0; $totalSize = 0;
$filesystem = $this->storage; $filesystem = $this->storage;
foreach ($medias as $media) { foreach ($medias as $media) {
try { try {
$totalSize += $filesystem->getSize($media->storage_path); $totalSize += $filesystem->getSize($media->storage_path);
} catch (FileNotFoundException $e) { } catch (FileNotFoundException $e) {
$this->logger->error('Error calculating file size', ['exception' => $e]); $this->logger->error('Error calculating file size', ['exception' => $e]);
} }
} }
return $totalSize; return $totalSize;
} }
} }

View file

@ -9,72 +9,72 @@ use Slim\Http\Response;
class DashboardController extends Controller class DashboardController extends Controller
{ {
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
*/ */
public function redirects(Request $request, Response $response): Response public function redirects(Request $request, Response $response): Response
{ {
if ($request->getParam('afterInstall') !== null && !is_dir(BASE_DIR . 'install')) { if ($request->getParam('afterInstall') !== null && !is_dir(BASE_DIR . 'install')) {
$this->session->alert(lang('installed'), 'success'); $this->session->alert(lang('installed'), 'success');
} }
return redirect($response, 'home'); return redirect($response, 'home');
} }
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @param $args * @param $args
* @return Response * @return Response
*/ */
public function home(Request $request, Response $response, $args): Response public function home(Request $request, Response $response, $args): Response
{ {
$page = isset($args['page']) ? (int)$args['page'] : 0; $page = isset($args['page']) ? (int)$args['page'] : 0;
$page = max(0, --$page); $page = max(0, --$page);
$query = new MediaQuery($this->database, $this->session->get('admin', false), $this->storage); $query = new MediaQuery($this->database, $this->session->get('admin', false), $this->storage);
switch ($request->getParam('sort', 'time')) { switch ($request->getParam('sort', 'time')) {
case 'size': case 'size':
$order = MediaQuery::ORDER_SIZE; $order = MediaQuery::ORDER_SIZE;
break; break;
case 'name': case 'name':
$order = MediaQuery::ORDER_NAME; $order = MediaQuery::ORDER_NAME;
break; break;
default: default:
case 'time': case 'time':
$order = MediaQuery::ORDER_TIME; $order = MediaQuery::ORDER_TIME;
break; break;
} }
$query->orderBy($order, $request->getParam('order', 'DESC')) $query->orderBy($order, $request->getParam('order', 'DESC'))
->withUserId($this->session->get('user_id')) ->withUserId($this->session->get('user_id'))
->search($request->getParam('search', null)) ->search($request->getParam('search', null))
->run($page); ->run($page);
return $this->view->render( return $this->view->render(
$response, $response,
($this->session->get('admin', false) && $this->session->get('gallery_view', true)) ? 'dashboard/admin.twig' : 'dashboard/home.twig', ($this->session->get('admin', false) && $this->session->get('gallery_view', true)) ? 'dashboard/admin.twig' : 'dashboard/home.twig',
[ [
'medias' => $query->getMedia(), 'medias' => $query->getMedia(),
'next' => $page < floor($query->getPages()), 'next' => $page < floor($query->getPages()),
'previous' => $page >= 1, 'previous' => $page >= 1,
'current_page' => ++$page, 'current_page' => ++$page,
] ]
); );
} }
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @param $args * @param $args
* @return Response * @return Response
*/ */
public function switchView(Request $request, Response $response, $args): Response public function switchView(Request $request, Response $response, $args): Response
{ {
$this->session->set('gallery_view', !$this->session->get('gallery_view', true)); $this->session->set('gallery_view', !$this->session->get('gallery_view', true));
return redirect($response, 'home'); return redirect($response, 'home');
} }
} }

View file

@ -2,78 +2,75 @@
namespace App\Controllers; namespace App\Controllers;
use Slim\Http\Request; use Slim\Http\Request;
use Slim\Http\Response; use Slim\Http\Response;
class LoginController extends Controller class LoginController extends Controller
{ {
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
*/ */
public function show(Request $request, Response $response): Response public function show(Request $request, Response $response): Response
{ {
if ($this->session->get('logged', false)) { if ($this->session->get('logged', false)) {
return redirect($response, 'home'); return redirect($response, 'home');
} }
return $this->view->render($response, 'auth/login.twig'); return $this->view->render($response, 'auth/login.twig');
} }
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
*/ */
public function login(Request $request, Response $response): Response public function login(Request $request, Response $response): Response
{ {
$result = $this->database->query('SELECT `id`, `email`, `username`, `password`,`is_admin`, `active` FROM `users` WHERE `username` = ? OR `email` = ? LIMIT 1', [$request->getParam('username'), $request->getParam('username')])->fetch();
$result = $this->database->query('SELECT `id`, `email`, `username`, `password`,`is_admin`, `active` FROM `users` WHERE `username` = ? OR `email` = ? LIMIT 1', [$request->getParam('username'), $request->getParam('username')])->fetch(); if (!$result || !password_verify($request->getParam('password'), $result->password)) {
$this->session->alert(lang('bad_login'), 'danger');
return redirect($response, 'login');
}
if (!$result || !password_verify($request->getParam('password'), $result->password)) { if (isset($this->settings['maintenance']) && $this->settings['maintenance'] && !$result->is_admin) {
$this->session->alert(lang('bad_login'), 'danger'); $this->session->alert(lang('maintenance_in_progress'), 'info');
return redirect($response, 'login'); return redirect($response, 'login');
} }
if (isset($this->settings['maintenance']) && $this->settings['maintenance'] && !$result->is_admin) { if (!$result->active) {
$this->session->alert(lang('maintenance_in_progress'), 'info'); $this->session->alert(lang('account_disabled'), 'danger');
return redirect($response, 'login'); return redirect($response, 'login');
} }
if (!$result->active) { $this->session->set('logged', true);
$this->session->alert(lang('account_disabled'), 'danger'); $this->session->set('user_id', $result->id);
return redirect($response, 'login'); $this->session->set('username', $result->username);
} $this->session->set('admin', $result->is_admin);
$this->session->set('used_space', humanFileSize($this->getUsedSpaceByUser($result->id)));
$this->session->set('logged', true); $this->session->alert(lang('welcome', [$result->username]), 'info');
$this->session->set('user_id', $result->id); $this->logger->info("User $result->username logged in.");
$this->session->set('username', $result->username);
$this->session->set('admin', $result->is_admin);
$this->session->set('used_space', humanFileSize($this->getUsedSpaceByUser($result->id)));
$this->session->alert(lang('welcome', [$result->username]), 'info'); if ($this->session->has('redirectTo')) {
$this->logger->info("User $result->username logged in."); return $response->withRedirect($this->session->get('redirectTo'));
}
if ($this->session->has('redirectTo')) { return redirect($response, 'home');
return $response->withRedirect($this->session->get('redirectTo')); }
}
return redirect($response, 'home');
}
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function logout(Request $request, Response $response): Response
{
$this->session->clear();
$this->session->set('logged', false);
$this->session->alert(lang('goodbye'), 'warning');
return redirect($response, 'login.show');
}
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function logout(Request $request, Response $response): Response
{
$this->session->clear();
$this->session->set('logged', false);
$this->session->alert(lang('goodbye'), 'warning');
return redirect($response, 'login.show');
}
} }

View file

@ -7,35 +7,34 @@ use Slim\Http\Response;
class ThemeController extends Controller class ThemeController extends Controller
{ {
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
*/ */
public function getThemes(Request $request, Response $response): Response public function getThemes(Request $request, Response $response): Response
{ {
$apiJson = json_decode(file_get_contents('https://bootswatch.com/api/4.json')); $apiJson = json_decode(file_get_contents('https://bootswatch.com/api/4.json'));
$out = []; $out = [];
$out['Default - Bootstrap 4 default theme'] = 'https://bootswatch.com/_vendor/bootstrap/dist/css/bootstrap.min.css'; $out['Default - Bootstrap 4 default theme'] = 'https://bootswatch.com/_vendor/bootstrap/dist/css/bootstrap.min.css';
foreach ($apiJson->themes as $theme) { foreach ($apiJson->themes as $theme) {
$out["{$theme->name} - {$theme->description}"] = $theme->cssMin; $out["{$theme->name} - {$theme->description}"] = $theme->cssMin;
} }
return $response->withJson($out); return $response->withJson($out);
} }
public function applyTheme(Request $request, Response $response): Response public function applyTheme(Request $request, Response $response): Response
{ {
if (!is_writable(BASE_DIR . 'static/bootstrap/css/bootstrap.min.css')) { if (!is_writable(BASE_DIR . 'static/bootstrap/css/bootstrap.min.css')) {
$this->session->alert(lang('cannot_write_file'), 'danger'); $this->session->alert(lang('cannot_write_file'), 'danger');
return redirect($response, 'system'); return redirect($response, 'system');
} }
file_put_contents(BASE_DIR . 'static/bootstrap/css/bootstrap.min.css', file_get_contents($request->getParam('css')));
return redirect($response, 'system');
}
file_put_contents(BASE_DIR . 'static/bootstrap/css/bootstrap.min.css', file_get_contents($request->getParam('css')));
return redirect($response, 'system');
}
} }

View file

@ -2,7 +2,6 @@
namespace App\Controllers; namespace App\Controllers;
use Slim\Http\Request; use Slim\Http\Request;
use Slim\Http\Response; use Slim\Http\Response;
use ZipArchive; use ZipArchive;
@ -147,5 +146,4 @@ class UpgradeController extends Controller
return json_decode($data); return json_decode($data);
} }
} }

View file

@ -15,398 +15,392 @@ use Slim\Http\Stream;
class UploadController extends Controller class UploadController extends Controller
{ {
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
* @throws FileExistsException * @throws FileExistsException
*/ */
public function upload(Request $request, Response $response): Response public function upload(Request $request, Response $response): Response
{ {
$json = [
$json = [ 'message' => null,
'message' => null, 'version' => PLATFORM_VERSION,
'version' => PLATFORM_VERSION, ];
];
if ($this->settings['maintenance']) {
if ($this->settings['maintenance']) { $json['message'] = 'Endpoint under maintenance.';
$json['message'] = 'Endpoint under maintenance.'; return $response->withJson($json, 503);
return $response->withJson($json, 503); }
}
if ($request->getServerParam('CONTENT_LENGTH') > stringToBytes(ini_get('post_max_size'))) {
if ($request->getServerParam('CONTENT_LENGTH') > stringToBytes(ini_get('post_max_size'))) { $json['message'] = 'File too large (post_max_size too low?).';
$json['message'] = 'File too large (post_max_size too low?).'; return $response->withJson($json, 400);
return $response->withJson($json, 400); }
}
if (isset($request->getUploadedFiles()['upload']) && $request->getUploadedFiles()['upload']->getError() === UPLOAD_ERR_INI_SIZE) {
if (isset($request->getUploadedFiles()['upload']) && $request->getUploadedFiles()['upload']->getError() === UPLOAD_ERR_INI_SIZE) { $json['message'] = 'File too large (upload_max_filesize too low?).';
$json['message'] = 'File too large (upload_max_filesize too low?).'; return $response->withJson($json, 400);
return $response->withJson($json, 400); }
}
if ($request->getParam('token') === null) {
if ($request->getParam('token') === null) { $json['message'] = 'Token not specified.';
$json['message'] = 'Token not specified.'; return $response->withJson($json, 400);
return $response->withJson($json, 400); }
}
$user = $this->database->query('SELECT * FROM `users` WHERE `token` = ? LIMIT 1', $request->getParam('token'))->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `token` = ? LIMIT 1', $request->getParam('token'))->fetch();
if (!$user) {
if (!$user) { $json['message'] = 'Token specified not found.';
$json['message'] = 'Token specified not found.'; return $response->withJson($json, 404);
return $response->withJson($json, 404); }
}
if (!$user->active) {
if (!$user->active) { $json['message'] = 'Account disabled.';
$json['message'] = 'Account disabled.'; return $response->withJson($json, 401);
return $response->withJson($json, 401); }
}
do {
do { $code = humanRandomString();
$code = humanRandomString(); } while ($this->database->query('SELECT COUNT(*) AS `count` FROM `uploads` WHERE `code` = ?', $code)->fetch()->count > 0);
} while ($this->database->query('SELECT COUNT(*) AS `count` FROM `uploads` WHERE `code` = ?', $code)->fetch()->count > 0);
/** @var \Psr\Http\Message\UploadedFileInterface $file */
/** @var \Psr\Http\Message\UploadedFileInterface $file */ $file = $request->getUploadedFiles()['upload'];
$file = $request->getUploadedFiles()['upload'];
$fileInfo = pathinfo($file->getClientFilename());
$fileInfo = pathinfo($file->getClientFilename()); $storagePath = "$user->user_code/$code.$fileInfo[extension]";
$storagePath = "$user->user_code/$code.$fileInfo[extension]";
$this->storage->writeStream($storagePath, $file->getStream()->detach());
$this->storage->writeStream($storagePath, $file->getStream()->detach());
$this->database->query('INSERT INTO `uploads`(`user_id`, `code`, `filename`, `storage_path`) VALUES (?, ?, ?, ?)', [
$this->database->query('INSERT INTO `uploads`(`user_id`, `code`, `filename`, `storage_path`) VALUES (?, ?, ?, ?)', [ $user->id,
$user->id, $code,
$code, $file->getClientFilename(),
$file->getClientFilename(), $storagePath,
$storagePath, ]);
]);
$json['message'] = 'OK.';
$json['message'] = 'OK.'; $json['url'] = urlFor("/$user->user_code/$code.$fileInfo[extension]");
$json['url'] = urlFor("/$user->user_code/$code.$fileInfo[extension]");
$this->logger->info("User $user->username uploaded new media.", [$this->database->raw()->lastInsertId()]);
$this->logger->info("User $user->username uploaded new media.", [$this->database->raw()->lastInsertId()]);
return $response->withJson($json, 201);
return $response->withJson($json, 201); }
}
/**
/** * @param Request $request
* @param Request $request * @param Response $response
* @param Response $response * @param $args
* @param $args * @return Response
* @return Response * @throws FileNotFoundException
* @throws FileNotFoundException * @throws NotFoundException
* @throws NotFoundException */
*/ public function show(Request $request, Response $response, $args): Response
public function show(Request $request, Response $response, $args): Response {
{ $media = $this->getMedia($args['userCode'], $args['mediaCode']);
$media = $this->getMedia($args['userCode'], $args['mediaCode']);
if (!$media || (!$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false))) {
if (!$media || (!$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false))) { throw new NotFoundException($request, $response);
throw new NotFoundException($request, $response); }
}
$filesystem = $this->storage;
$filesystem = $this->storage;
if (isBot($request->getHeaderLine('User-Agent'))) {
if (isBot($request->getHeaderLine('User-Agent'))) { return $this->streamMedia($request, $response, $filesystem, $media);
return $this->streamMedia($request, $response, $filesystem, $media); } else {
} else { try {
try { $media->mimetype = $filesystem->getMimetype($media->storage_path);
$media->mimetype = $filesystem->getMimetype($media->storage_path); $size = $filesystem->getSize($media->storage_path);
$size = $filesystem->getSize($media->storage_path);
$type = explode('/', $media->mimetype)[0];
$type = explode('/', $media->mimetype)[0]; if ($type === 'image' && !isDisplayableImage($media->mimetype)) {
if ($type === 'image' && !isDisplayableImage($media->mimetype)) { $type = 'application';
$type = 'application'; $media->mimetype = 'application/octet-stream';
$media->mimetype = 'application/octet-stream'; }
} if ($type === 'text') {
if ($type === 'text') { if ($size <= (200 * 1024)) { // less than 200 KB
if ($size <= (200 * 1024)) { // less than 200 KB $media->text = $filesystem->read($media->storage_path);
$media->text = $filesystem->read($media->storage_path); } else {
} else { $type = 'application';
$type = 'application'; $media->mimetype = 'application/octet-stream';
$media->mimetype = 'application/octet-stream'; }
} }
} $media->size = humanFileSize($size);
$media->size = humanFileSize($size); } catch (FileNotFoundException $e) {
throw new NotFoundException($request, $response);
} catch (FileNotFoundException $e) { }
throw new NotFoundException($request, $response);
} return $this->view->render($response, 'upload/public.twig', [
'delete_token' => isset($args['token']) ? $args['token'] : null,
return $this->view->render($response, 'upload/public.twig', [ 'media' => $media,
'delete_token' => isset($args['token']) ? $args['token'] : null, 'type' => $type,
'media' => $media, 'extension' => pathinfo($media->filename, PATHINFO_EXTENSION),
'type' => $type, ]);
'extension' => pathinfo($media->filename, PATHINFO_EXTENSION), }
]); }
}
} /**
* @param Request $request
/** * @param Response $response
* @param Request $request * @param $args
* @param Response $response * @return Response
* @param $args * @throws NotFoundException
* @return Response * @throws UnauthorizedException
* @throws NotFoundException */
* @throws UnauthorizedException public function deleteByToken(Request $request, Response $response, $args): Response
*/ {
public function deleteByToken(Request $request, Response $response, $args): Response $media = $this->getMedia($args['userCode'], $args['mediaCode']);
{
$media = $this->getMedia($args['userCode'], $args['mediaCode']); if (!$media) {
throw new NotFoundException($request, $response);
if (!$media) { }
throw new NotFoundException($request, $response);
} $user = $this->database->query('SELECT `id`, `active` FROM `users` WHERE `token` = ? LIMIT 1', $args['token'])->fetch();
$user = $this->database->query('SELECT `id`, `active` FROM `users` WHERE `token` = ? LIMIT 1', $args['token'])->fetch(); if (!$user) {
$this->session->alert(lang('token_not_found'), 'danger');
if (!$user) { return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
$this->session->alert(lang('token_not_found'), 'danger'); }
return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
} if (!$user->active) {
$this->session->alert(lang('account_disabled'), 'danger');
if (!$user->active) { return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
$this->session->alert(lang('account_disabled'), 'danger'); }
return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
} if ($this->session->get('admin', false) || $user->id === $media->user_id) {
try {
if ($this->session->get('admin', false) || $user->id === $media->user_id) { $this->storage->delete($media->storage_path);
} catch (FileNotFoundException $e) {
try { throw new NotFoundException($request, $response);
$this->storage->delete($media->storage_path); } finally {
} catch (FileNotFoundException $e) { $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $media->mediaId);
throw new NotFoundException($request, $response); $this->logger->info('User ' . $user->username . ' deleted a media via token.', [$media->mediaId]);
} finally { }
$this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $media->mediaId); } else {
$this->logger->info('User ' . $user->username . ' deleted a media via token.', [$media->mediaId]); throw new UnauthorizedException();
} }
} else {
throw new UnauthorizedException(); return redirect($response, 'home');
} }
return redirect($response, 'home'); /**
} * @param Request $request
* @param Response $response
/** * @param $args
* @param Request $request * @return Response
* @param Response $response * @throws NotFoundException
* @param $args * @throws FileNotFoundException
* @return Response */
* @throws NotFoundException public function getRawById(Request $request, Response $response, $args): Response
* @throws FileNotFoundException {
*/ $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
public function getRawById(Request $request, Response $response, $args): Response
{ if (!$media) {
throw new NotFoundException($request, $response);
$media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch(); }
if (!$media) { return $this->streamMedia($request, $response, $this->storage, $media);
throw new NotFoundException($request, $response); }
}
/**
return $this->streamMedia($request, $response, $this->storage, $media); * @param Request $request
} * @param Response $response
* @param $args
/** * @return Response
* @param Request $request * @throws NotFoundException
* @param Response $response * @throws FileNotFoundException
* @param $args */
* @return Response public function showRaw(Request $request, Response $response, $args): Response
* @throws NotFoundException {
* @throws FileNotFoundException $media = $this->getMedia($args['userCode'], $args['mediaCode']);
*/
public function showRaw(Request $request, Response $response, $args): Response if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) {
{ throw new NotFoundException($request, $response);
$media = $this->getMedia($args['userCode'], $args['mediaCode']); }
return $this->streamMedia($request, $response, $this->storage, $media);
if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) { }
throw new NotFoundException($request, $response);
}
return $this->streamMedia($request, $response, $this->storage, $media); /**
} * @param Request $request
* @param Response $response
* @param $args
/** * @return Response
* @param Request $request * @throws NotFoundException
* @param Response $response * @throws FileNotFoundException
* @param $args */
* @return Response public function download(Request $request, Response $response, $args): Response
* @throws NotFoundException {
* @throws FileNotFoundException $media = $this->getMedia($args['userCode'], $args['mediaCode']);
*/
public function download(Request $request, Response $response, $args): Response if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) {
{ throw new NotFoundException($request, $response);
$media = $this->getMedia($args['userCode'], $args['mediaCode']); }
return $this->streamMedia($request, $response, $this->storage, $media, 'attachment');
if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) { }
throw new NotFoundException($request, $response);
} /**
return $this->streamMedia($request, $response, $this->storage, $media, 'attachment'); * @param Request $request
} * @param Response $response
* @param $args
/** * @return Response
* @param Request $request * @throws NotFoundException
* @param Response $response */
* @param $args public function togglePublish(Request $request, Response $response, $args): Response
* @return Response {
* @throws NotFoundException if ($this->session->get('admin')) {
*/ $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
public function togglePublish(Request $request, Response $response, $args): Response } else {
{ $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? AND `user_id` = ? LIMIT 1', [$args['id'], $this->session->get('user_id')])->fetch();
if ($this->session->get('admin')) { }
$media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
} else { if (!$media) {
$media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? AND `user_id` = ? LIMIT 1', [$args['id'], $this->session->get('user_id')])->fetch(); throw new NotFoundException($request, $response);
} }
if (!$media) { $this->database->query('UPDATE `uploads` SET `published`=? WHERE `id`=?', [$media->published ? 0 : 1, $media->id]);
throw new NotFoundException($request, $response);
} return $response->withStatus(200);
}
$this->database->query('UPDATE `uploads` SET `published`=? WHERE `id`=?', [$media->published ? 0 : 1, $media->id]);
/**
return $response->withStatus(200); * @param Request $request
} * @param Response $response
* @param $args
/** * @return Response
* @param Request $request * @throws NotFoundException
* @param Response $response * @throws UnauthorizedException
* @param $args */
* @return Response public function delete(Request $request, Response $response, $args): Response
* @throws NotFoundException {
* @throws UnauthorizedException $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
*/
public function delete(Request $request, Response $response, $args): Response if (!$media) {
{ throw new NotFoundException($request, $response);
$media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch(); }
if (!$media) { if ($this->session->get('admin', false) || $media->user_id === $this->session->get('user_id')) {
throw new NotFoundException($request, $response); try {
} $this->storage->delete($media->storage_path);
} catch (FileNotFoundException $e) {
if ($this->session->get('admin', false) || $media->user_id === $this->session->get('user_id')) { throw new NotFoundException($request, $response);
} finally {
try { $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $args['id']);
$this->storage->delete($media->storage_path); $this->logger->info('User ' . $this->session->get('username') . ' deleted a media.', [$args['id']]);
} catch (FileNotFoundException $e) { $this->session->set('used_space', humanFileSize($this->getUsedSpaceByUser($this->session->get('user_id'))));
throw new NotFoundException($request, $response); }
} finally { } else {
$this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $args['id']); throw new UnauthorizedException();
$this->logger->info('User ' . $this->session->get('username') . ' deleted a media.', [$args['id']]); }
$this->session->set('used_space', humanFileSize($this->getUsedSpaceByUser($this->session->get('user_id'))));
} return $response->withStatus(200);
} else { }
throw new UnauthorizedException();
} /**
* @param $userCode
return $response->withStatus(200); * @param $mediaCode
} * @return mixed
*/
/** protected function getMedia($userCode, $mediaCode)
* @param $userCode {
* @param $mediaCode $mediaCode = pathinfo($mediaCode)['filename'];
* @return mixed
*/ $media = $this->database->query('SELECT `uploads`.*, `users`.*, `users`.`id` AS `userId`, `uploads`.`id` AS `mediaId` FROM `uploads` INNER JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `user_code` = ? AND `uploads`.`code` = ? LIMIT 1', [
protected function getMedia($userCode, $mediaCode) $userCode,
{ $mediaCode,
$mediaCode = pathinfo($mediaCode)['filename']; ])->fetch();
$media = $this->database->query('SELECT `uploads`.*, `users`.*, `users`.`id` AS `userId`, `uploads`.`id` AS `mediaId` FROM `uploads` INNER JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `user_code` = ? AND `uploads`.`code` = ? LIMIT 1', [ return $media;
$userCode, }
$mediaCode,
])->fetch(); /**
* @param Request $request
return $media; * @param Response $response
} * @param Filesystem $storage
* @param $media
/** * @param string $disposition
* @param Request $request * @return Response
* @param Response $response * @throws FileNotFoundException
* @param Filesystem $storage */
* @param $media protected function streamMedia(Request $request, Response $response, Filesystem $storage, $media, string $disposition = 'inline'): Response
* @param string $disposition {
* @return Response set_time_limit(0);
* @throws FileNotFoundException $mime = $storage->getMimetype($media->storage_path);
*/
protected function streamMedia(Request $request, Response $response, Filesystem $storage, $media, string $disposition = 'inline'): Response if ($request->getParam('width') !== null && explode('/', $mime)[0] === 'image') {
{ $image = Image::make($storage->readStream($media->storage_path))
set_time_limit(0); ->resizeCanvas(
$mime = $storage->getMimetype($media->storage_path); $request->getParam('width'),
$request->getParam('height'),
if ($request->getParam('width') !== null && explode('/', $mime)[0] === 'image') { 'center')
->encode('png');
$image = Image::make($storage->readStream($media->storage_path))
->resizeCanvas( return $response
$request->getParam('width'), ->withHeader('Content-Type', 'image/png')
$request->getParam('height'), ->withHeader('Content-Disposition', $disposition . ';filename="scaled-' . pathinfo($media->filename)['filename'] . '.png"')
'center') ->write($image);
->encode('png'); } else {
$stream = new Stream($storage->readStream($media->storage_path));
return $response
->withHeader('Content-Type', 'image/png') if (!in_array(explode('/', $mime)[0], ['image', 'video', 'audio']) || $disposition === 'attachment') {
->withHeader('Content-Disposition', $disposition . ';filename="scaled-' . pathinfo($media->filename)['filename'] . '.png"') return $response->withHeader('Content-Type', $mime)
->write($image); ->withHeader('Content-Disposition', $disposition . '; filename="' . $media->filename . '"')
} else { ->withHeader('Content-Length', $stream->getSize())
$stream = new Stream($storage->readStream($media->storage_path)); ->withBody($stream);
}
if (!in_array(explode('/', $mime)[0], ['image', 'video', 'audio']) || $disposition === 'attachment') {
return $response->withHeader('Content-Type', $mime) $end = $stream->getSize() - 1;
->withHeader('Content-Disposition', $disposition . '; filename="' . $media->filename . '"')
->withHeader('Content-Length', $stream->getSize()) if ($request->getServerParam('HTTP_RANGE') !== null) {
->withBody($stream); list(, $range) = explode('=', $request->getServerParam('HTTP_RANGE'), 2);
}
if (strpos($range, ',') !== false) {
$end = $stream->getSize() - 1; return $response->withHeader('Content-Type', $mime)
->withHeader('Content-Disposition', $disposition . '; filename="' . $media->filename . '"')
if ($request->getServerParam('HTTP_RANGE') !== null) { ->withHeader('Content-Length', $stream->getSize())
list(, $range) = explode('=', $request->getServerParam('HTTP_RANGE'), 2); ->withHeader('Accept-Ranges', 'bytes')
->withHeader('Content-Range', "0,{$stream->getSize()}")
if (strpos($range, ',') !== false) { ->withStatus(416)
return $response->withHeader('Content-Type', $mime) ->withBody($stream);
->withHeader('Content-Disposition', $disposition . '; filename="' . $media->filename . '"') }
->withHeader('Content-Length', $stream->getSize())
->withHeader('Accept-Ranges', 'bytes') if ($range === '-') {
->withHeader('Content-Range', "0,{$stream->getSize()}") $start = $stream->getSize() - (int)substr($range, 1);
->withStatus(416) } else {
->withBody($stream); $range = explode('-', $range);
} $start = (int)$range[0];
$end = (isset($range[1]) && is_numeric($range[1])) ? (int)$range[1] : $stream->getSize();
if ($range === '-') { }
$start = $stream->getSize() - (int)substr($range, 1);
} else { $end = ($end > $stream->getSize() - 1) ? $stream->getSize() - 1 : $end;
$range = explode('-', $range); $stream->seek($start);
$start = (int)$range[0];
$end = (isset($range[1]) && is_numeric($range[1])) ? (int)$range[1] : $stream->getSize(); header("Content-Type: $mime");
} header('Content-Length: ' . ($end - $start + 1));
header('Accept-Ranges: bytes');
$end = ($end > $stream->getSize() - 1) ? $stream->getSize() - 1 : $end; header("Content-Range: bytes $start-$end/{$stream->getSize()}");
$stream->seek($start);
http_response_code(206);
header("Content-Type: $mime"); ob_end_clean();
header('Content-Length: ' . ($end - $start + 1));
header('Accept-Ranges: bytes'); $buffer = 16348;
header("Content-Range: bytes $start-$end/{$stream->getSize()}"); $readed = $start;
while ($readed < $end) {
http_response_code(206); if ($readed + $buffer > $end) {
ob_end_clean(); $buffer = $end - $readed + 1;
}
$buffer = 16348; echo $stream->read($buffer);
$readed = $start; $readed += $buffer;
while ($readed < $end) { }
if ($readed + $buffer > $end) {
$buffer = $end - $readed + 1; exit(0);
} }
echo $stream->read($buffer);
$readed += $buffer; return $response->withHeader('Content-Type', $mime)
} ->withHeader('Content-Length', $stream->getSize())
->withHeader('Accept-Ranges', 'bytes')
exit(0); ->withStatus(200)
} ->withBody($stream);
}
return $response->withHeader('Content-Type', $mime) }
->withHeader('Content-Length', $stream->getSize())
->withHeader('Accept-Ranges', 'bytes')
->withStatus(200)
->withBody($stream);
}
}
} }

View file

@ -2,7 +2,6 @@
namespace App\Controllers; namespace App\Controllers;
use App\Exceptions\UnauthorizedException; use App\Exceptions\UnauthorizedException;
use Slim\Exception\NotFoundException; use Slim\Exception\NotFoundException;
use Slim\Http\Request; use Slim\Http\Request;
@ -10,412 +9,411 @@ use Slim\Http\Response;
class UserController extends Controller class UserController extends Controller
{ {
const PER_PAGE = 15; const PER_PAGE = 15;
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @param $args * @param $args
* @return Response * @return Response
*/ */
public function index(Request $request, Response $response, $args): Response public function index(Request $request, Response $response, $args): Response
{ {
$page = isset($args['page']) ? (int)$args['page'] : 0; $page = isset($args['page']) ? (int)$args['page'] : 0;
$page = max(0, --$page); $page = max(0, --$page);
$users = $this->database->query('SELECT * FROM `users` LIMIT ? OFFSET ?', [self::PER_PAGE, $page * self::PER_PAGE])->fetchAll(); $users = $this->database->query('SELECT * FROM `users` LIMIT ? OFFSET ?', [self::PER_PAGE, $page * self::PER_PAGE])->fetchAll();
$pages = $this->database->query('SELECT COUNT(*) AS `count` FROM `users`')->fetch()->count / self::PER_PAGE; $pages = $this->database->query('SELECT COUNT(*) AS `count` FROM `users`')->fetch()->count / self::PER_PAGE;
return $this->view->render($response, return $this->view->render($response,
'user/index.twig', 'user/index.twig',
[ [
'users' => $users, 'users' => $users,
'next' => $page < floor($pages), 'next' => $page < floor($pages),
'previous' => $page >= 1, 'previous' => $page >= 1,
'current_page' => ++$page, 'current_page' => ++$page,
] ]
); );
} }
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
*/ */
public function create(Request $request, Response $response): Response public function create(Request $request, Response $response): Response
{ {
return $this->view->render($response, 'user/create.twig'); return $this->view->render($response, 'user/create.twig');
} }
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @return Response * @return Response
*/ */
public function store(Request $request, Response $response): Response public function store(Request $request, Response $response): Response
{ {
if ($request->getParam('email') === null) { if ($request->getParam('email') === null) {
$this->session->alert(lang('email_required'), 'danger'); $this->session->alert(lang('email_required'), 'danger');
return redirect($response, 'user.create'); return redirect($response, 'user.create');
} }
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ?', $request->getParam('email'))->fetch()->count > 0) { if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ?', $request->getParam('email'))->fetch()->count > 0) {
$this->session->alert(lang('email_taken'), 'danger'); $this->session->alert(lang('email_taken'), 'danger');
return redirect($response, 'user.create'); return redirect($response, 'user.create');
} }
if ($request->getParam('username') === null) { if ($request->getParam('username') === null) {
$this->session->alert(lang('username_required'), 'danger'); $this->session->alert(lang('username_required'), 'danger');
return redirect($response, 'user.create'); return redirect($response, 'user.create');
} }
if ($request->getParam('password') === null) { if ($request->getParam('password') === null) {
$this->session->alert(lang('password_required'), 'danger'); $this->session->alert(lang('password_required'), 'danger');
return redirect($response, 'user.create'); return redirect($response, 'user.create');
} }
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ?', $request->getParam('username'))->fetch()->count > 0) { if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ?', $request->getParam('username'))->fetch()->count > 0) {
$this->session->alert(lang('username_taken'), 'danger'); $this->session->alert(lang('username_taken'), 'danger');
return redirect($response, 'user.create'); return redirect($response, 'user.create');
} }
do { do {
$userCode = humanRandomString(5); $userCode = humanRandomString(5);
} while ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `user_code` = ?', $userCode)->fetch()->count > 0); } while ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `user_code` = ?', $userCode)->fetch()->count > 0);
$token = $this->generateNewToken(); $token = $this->generateNewToken();
$this->database->query('INSERT INTO `users`(`email`, `username`, `password`, `is_admin`, `active`, `user_code`, `token`) VALUES (?, ?, ?, ?, ?, ?, ?)', [ $this->database->query('INSERT INTO `users`(`email`, `username`, `password`, `is_admin`, `active`, `user_code`, `token`) VALUES (?, ?, ?, ?, ?, ?, ?)', [
$request->getParam('email'), $request->getParam('email'),
$request->getParam('username'), $request->getParam('username'),
password_hash($request->getParam('password'), PASSWORD_DEFAULT), password_hash($request->getParam('password'), PASSWORD_DEFAULT),
$request->getParam('is_admin') !== null ? 1 : 0, $request->getParam('is_admin') !== null ? 1 : 0,
$request->getParam('is_active') !== null ? 1 : 0, $request->getParam('is_active') !== null ? 1 : 0,
$userCode, $userCode,
$token, $token,
]); ]);
$this->session->alert(lang('user_created', [$request->getParam('username')]), 'success'); $this->session->alert(lang('user_created', [$request->getParam('username')]), 'success');
$this->logger->info('User ' . $this->session->get('username') . ' created a new user.', [array_diff_key($request->getParams(), array_flip(['password']))]); $this->logger->info('User ' . $this->session->get('username') . ' created a new user.', [array_diff_key($request->getParams(), array_flip(['password']))]);
return redirect($response, 'user.index'); return redirect($response, 'user.index');
} }
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @param $args * @param $args
* @return Response * @return Response
* @throws NotFoundException * @throws NotFoundException
*/ */
public function edit(Request $request, Response $response, $args): Response public function edit(Request $request, Response $response, $args): Response
{ {
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch(); $user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
if (!$user) { if (!$user) {
throw new NotFoundException($request, $response); throw new NotFoundException($request, $response);
} }
return $this->view->render($response, 'user/edit.twig', [ return $this->view->render($response, 'user/edit.twig', [
'profile' => false, 'profile' => false,
'user' => $user, 'user' => $user,
]); ]);
} }
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @param $args * @param $args
* @return Response * @return Response
* @throws NotFoundException * @throws NotFoundException
*/ */
public function update(Request $request, Response $response, $args): Response public function update(Request $request, Response $response, $args): Response
{ {
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch(); $user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
if (!$user) { if (!$user) {
throw new NotFoundException($request, $response); throw new NotFoundException($request, $response);
} }
if ($request->getParam('email') === null) { if ($request->getParam('email') === null) {
$this->session->alert(lang('email_required'), 'danger'); $this->session->alert(lang('email_required'), 'danger');
return redirect($response, 'user.edit', ['id' => $args['id']]); return redirect($response, 'user.edit', ['id' => $args['id']]);
} }
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ? AND `email` <> ?', [$request->getParam('email'), $user->email])->fetch()->count > 0) { if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ? AND `email` <> ?', [$request->getParam('email'), $user->email])->fetch()->count > 0) {
$this->session->alert(lang('email_taken'), 'danger'); $this->session->alert(lang('email_taken'), 'danger');
return redirect($response, 'user.edit', ['id' => $args['id']]); return redirect($response, 'user.edit', ['id' => $args['id']]);
} }
if ($request->getParam('username') === null) { if ($request->getParam('username') === null) {
$this->session->alert(lang('username_required'), 'danger'); $this->session->alert(lang('username_required'), 'danger');
return redirect($response, 'user.edit', ['id' => $args['id']]); return redirect($response, 'user.edit', ['id' => $args['id']]);
} }
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ? AND `username` <> ?', [$request->getParam('username'), $user->username])->fetch()->count > 0) { if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ? AND `username` <> ?', [$request->getParam('username'), $user->username])->fetch()->count > 0) {
$this->session->alert(lang('username_taken'), 'danger'); $this->session->alert(lang('username_taken'), 'danger');
return redirect($response, 'user.edit', ['id' => $args['id']]); return redirect($response, 'user.edit', ['id' => $args['id']]);
} }
if ($user->id === $this->session->get('user_id') && $request->getParam('is_admin') === null) { if ($user->id === $this->session->get('user_id') && $request->getParam('is_admin') === null) {
$this->session->alert(lang('cannot_demote'), 'danger'); $this->session->alert(lang('cannot_demote'), 'danger');
return redirect($response, 'user.edit', ['id' => $args['id']]); return redirect($response, 'user.edit', ['id' => $args['id']]);
} }
if ($request->getParam('password') !== null && !empty($request->getParam('password'))) { if ($request->getParam('password') !== null && !empty($request->getParam('password'))) {
$this->database->query('UPDATE `users` SET `email`=?, `username`=?, `password`=?, `is_admin`=?, `active`=? WHERE `id` = ?', [ $this->database->query('UPDATE `users` SET `email`=?, `username`=?, `password`=?, `is_admin`=?, `active`=? WHERE `id` = ?', [
$request->getParam('email'), $request->getParam('email'),
$request->getParam('username'), $request->getParam('username'),
password_hash($request->getParam('password'), PASSWORD_DEFAULT), password_hash($request->getParam('password'), PASSWORD_DEFAULT),
$request->getParam('is_admin') !== null ? 1 : 0, $request->getParam('is_admin') !== null ? 1 : 0,
$request->getParam('is_active') !== null ? 1 : 0, $request->getParam('is_active') !== null ? 1 : 0,
$user->id, $user->id,
]); ]);
} else { } else {
$this->database->query('UPDATE `users` SET `email`=?, `username`=?, `is_admin`=?, `active`=? WHERE `id` = ?', [ $this->database->query('UPDATE `users` SET `email`=?, `username`=?, `is_admin`=?, `active`=? WHERE `id` = ?', [
$request->getParam('email'), $request->getParam('email'),
$request->getParam('username'), $request->getParam('username'),
$request->getParam('is_admin') !== null ? 1 : 0, $request->getParam('is_admin') !== null ? 1 : 0,
$request->getParam('is_active') !== null ? 1 : 0, $request->getParam('is_active') !== null ? 1 : 0,
$user->id, $user->id,
]); ]);
} }
$this->session->alert(lang('user_updated', [$request->getParam('username')]), 'success'); $this->session->alert(lang('user_updated', [$request->getParam('username')]), 'success');
$this->logger->info('User ' . $this->session->get('username') . " updated $user->id.", [ $this->logger->info('User ' . $this->session->get('username') . " updated $user->id.", [
array_diff_key((array)$user, array_flip(['password'])), array_diff_key((array)$user, array_flip(['password'])),
array_diff_key($request->getParams(), array_flip(['password'])), array_diff_key($request->getParams(), array_flip(['password'])),
]); ]);
return redirect($response, 'user.index'); return redirect($response, 'user.index');
}
}
/**
/** * @param Request $request
* @param Request $request * @param Response $response
* @param Response $response * @param $args
* @param $args * @return Response
* @return Response * @throws NotFoundException
* @throws NotFoundException */
*/ public function delete(Request $request, Response $response, $args): Response
public function delete(Request $request, Response $response, $args): Response {
{ $user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
if (!$user) {
if (!$user) { throw new NotFoundException($request, $response);
throw new NotFoundException($request, $response); }
}
if ($user->id === $this->session->get('user_id')) {
if ($user->id === $this->session->get('user_id')) { $this->session->alert(lang('cannot_delete'), 'danger');
$this->session->alert(lang('cannot_delete'), 'danger'); return redirect($response, 'user.index');
return redirect($response, 'user.index'); }
}
$this->database->query('DELETE FROM `users` WHERE `id` = ?', $user->id);
$this->database->query('DELETE FROM `users` WHERE `id` = ?', $user->id);
$this->session->alert(lang('user_deleted'), 'success');
$this->session->alert(lang('user_deleted'), 'success'); $this->logger->info('User ' . $this->session->get('username') . " deleted $user->id.");
$this->logger->info('User ' . $this->session->get('username') . " deleted $user->id.");
return redirect($response, 'user.index');
return redirect($response, 'user.index'); }
}
/**
/** * @param Request $request
* @param Request $request * @param Response $response
* @param Response $response * @return Response
* @return Response * @throws NotFoundException
* @throws NotFoundException * @throws UnauthorizedException
* @throws UnauthorizedException */
*/ public function profile(Request $request, Response $response): Response
public function profile(Request $request, Response $response): Response {
{ $user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $this->session->get('user_id'))->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $this->session->get('user_id'))->fetch();
if (!$user) {
if (!$user) { throw new NotFoundException($request, $response);
throw new NotFoundException($request, $response); }
}
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) { throw new UnauthorizedException();
throw new UnauthorizedException(); }
}
return $this->view->render($response, 'user/edit.twig', [
return $this->view->render($response, 'user/edit.twig', [ 'profile' => true,
'profile' => true, 'user' => $user,
'user' => $user, ]);
]); }
}
/**
/** * @param Request $request
* @param Request $request * @param Response $response
* @param Response $response * @param $args
* @param $args * @return Response
* @return Response * @throws NotFoundException
* @throws NotFoundException * @throws UnauthorizedException
* @throws UnauthorizedException */
*/ public function profileEdit(Request $request, Response $response, $args): Response
public function profileEdit(Request $request, Response $response, $args): Response {
{ $user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
if (!$user) {
if (!$user) { throw new NotFoundException($request, $response);
throw new NotFoundException($request, $response); }
}
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) { throw new UnauthorizedException();
throw new UnauthorizedException(); }
}
if ($request->getParam('email') === null) {
if ($request->getParam('email') === null) { $this->session->alert(lang('email_required'), 'danger');
$this->session->alert(lang('email_required'), 'danger'); return redirect($response, 'profile');
return redirect($response, 'profile'); }
}
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ? AND `email` <> ?', [$request->getParam('email'), $user->email])->fetch()->count > 0) {
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ? AND `email` <> ?', [$request->getParam('email'), $user->email])->fetch()->count > 0) { $this->session->alert(lang('email_taken'), 'danger');
$this->session->alert(lang('email_taken'), 'danger'); return redirect($response, 'profile');
return redirect($response, 'profile'); }
}
if ($request->getParam('password') !== null && !empty($request->getParam('password'))) {
if ($request->getParam('password') !== null && !empty($request->getParam('password'))) { $this->database->query('UPDATE `users` SET `email`=?, `password`=? WHERE `id` = ?', [
$this->database->query('UPDATE `users` SET `email`=?, `password`=? WHERE `id` = ?', [ $request->getParam('email'),
$request->getParam('email'), password_hash($request->getParam('password'), PASSWORD_DEFAULT),
password_hash($request->getParam('password'), PASSWORD_DEFAULT), $user->id,
$user->id, ]);
]); } else {
} else { $this->database->query('UPDATE `users` SET `email`=? WHERE `id` = ?', [
$this->database->query('UPDATE `users` SET `email`=? WHERE `id` = ?', [ $request->getParam('email'),
$request->getParam('email'), $user->id,
$user->id, ]);
]); }
}
$this->session->alert(lang('profile_updated'), 'success');
$this->session->alert(lang('profile_updated'), 'success'); $this->logger->info('User ' . $this->session->get('username') . " updated profile of $user->id.");
$this->logger->info('User ' . $this->session->get('username') . " updated profile of $user->id.");
return redirect($response, 'profile');
return redirect($response, 'profile'); }
}
/**
/** * @param Request $request
* @param Request $request * @param Response $response
* @param Response $response * @param $args
* @param $args * @return Response
* @return Response * @throws NotFoundException
* @throws NotFoundException * @throws UnauthorizedException
* @throws UnauthorizedException */
*/ public function refreshToken(Request $request, Response $response, $args): Response
public function refreshToken(Request $request, Response $response, $args): Response {
{ $user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
if (!$user) {
if (!$user) { throw new NotFoundException($request, $response);
throw new NotFoundException($request, $response); }
}
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) { throw new UnauthorizedException();
throw new UnauthorizedException(); }
}
$token = $this->generateNewToken();
$token = $this->generateNewToken();
$this->database->query('UPDATE `users` SET `token`=? WHERE `id` = ?', [
$this->database->query('UPDATE `users` SET `token`=? WHERE `id` = ?', [ $token,
$token, $user->id,
$user->id, ]);
]);
$this->logger->info('User ' . $this->session->get('username') . " refreshed token of user $user->id.");
$this->logger->info('User ' . $this->session->get('username') . " refreshed token of user $user->id.");
$response->getBody()->write($token);
$response->getBody()->write($token);
return $response;
return $response; }
}
/**
/** * @param Request $request
* @param Request $request * @param Response $response
* @param Response $response * @param $args
* @param $args * @return Response
* @return Response * @throws NotFoundException
* @throws NotFoundException * @throws UnauthorizedException
* @throws UnauthorizedException */
*/ public function getShareXconfigFile(Request $request, Response $response, $args): Response
public function getShareXconfigFile(Request $request, Response $response, $args): Response {
{ $user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
if (!$user) {
if (!$user) { throw new NotFoundException($request, $response);
throw new NotFoundException($request, $response); }
}
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) { throw new UnauthorizedException();
throw new UnauthorizedException(); }
}
if ($user->token === null || $user->token === '') {
if ($user->token === null || $user->token === '') { $this->session->alert('You don\'t have a personal upload token. (Click the update token button and try again)', 'danger');
$this->session->alert('You don\'t have a personal upload token. (Click the update token button and try again)', 'danger'); return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
return $response->withRedirect($request->getHeaderLine('HTTP_REFERER')); }
}
$json = [
$json = [ 'DestinationType' => 'ImageUploader, TextUploader, FileUploader',
'DestinationType' => 'ImageUploader, TextUploader, FileUploader', 'RequestURL' => route('upload'),
'RequestURL' => route('upload'), 'FileFormName' => 'upload',
'FileFormName' => 'upload', 'Arguments' => [
'Arguments' => [ 'file' => '$filename$',
'file' => '$filename$', 'text' => '$input$',
'text' => '$input$', 'token' => $user->token,
'token' => $user->token, ],
], 'URL' => '$json:url$',
'URL' => '$json:url$', 'ThumbnailURL' => '$json:url$/raw',
'ThumbnailURL' => '$json:url$/raw', 'DeletionURL' => '$json:url$/delete/' . $user->token,
'DeletionURL' => '$json:url$/delete/' . $user->token, ];
];
return $response
return $response ->withHeader('Content-Disposition', 'attachment;filename="' . $user->username . '-ShareX.sxcu"')
->withHeader('Content-Disposition', 'attachment;filename="' . $user->username . '-ShareX.sxcu"') ->withJson($json, 200, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
->withJson($json, 200, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); }
}
/**
/** * @param Request $request
* @param Request $request * @param Response $response
* @param Response $response * @param $args
* @param $args * @return Response
* @return Response * @throws NotFoundException
* @throws NotFoundException * @throws UnauthorizedException
* @throws UnauthorizedException */
*/ public function getUploaderScriptFile(Request $request, Response $response, $args): Response
public function getUploaderScriptFile(Request $request, Response $response, $args): Response {
{ $user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
if (!$user) {
if (!$user) { throw new NotFoundException($request, $response);
throw new NotFoundException($request, $response); }
}
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) { throw new UnauthorizedException();
throw new UnauthorizedException(); }
}
if ($user->token === null || $user->token === '') {
if ($user->token === null || $user->token === '') { $this->session->alert('You don\'t have a personal upload token. (Click the update token button and try again)', 'danger');
$this->session->alert('You don\'t have a personal upload token. (Click the update token button and try again)', 'danger'); return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
return $response->withRedirect($request->getHeaderLine('HTTP_REFERER')); }
}
return $this->view->render($response->withHeader('Content-Disposition', 'attachment;filename="xbackbone_uploader_' . $user->username . '.sh"'),
return $this->view->render($response->withHeader('Content-Disposition', 'attachment;filename="xbackbone_uploader_' . $user->username . '.sh"'), 'scripts/xbackbone_uploader.sh.twig',
'scripts/xbackbone_uploader.sh.twig', [
[ 'username' => $user->username,
'username' => $user->username, 'upload_url' => route('upload'),
'upload_url' => route('upload'), 'token' => $user->token,
'token' => $user->token, ]
] );
); }
}
/**
/** * @return string
* @return string */
*/ protected function generateNewToken(): string
protected function generateNewToken(): string {
{ do {
do { $token = 'token_' . md5(uniqid('', true));
$token = 'token_' . md5(uniqid('', true)); } while ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `token` = ?', $token)->fetch()->count > 0);
} while ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `token` = ?', $token)->fetch()->count > 0);
return $token;
return $token; }
}
} }

View file

@ -2,128 +2,124 @@
namespace App\Database; namespace App\Database;
use PDO; use PDO;
class DB class DB
{ {
/** @var DB */ /** @var DB */
protected static $instance; protected static $instance;
/** @var string */ /** @var string */
private static $password; private static $password;
/** @var string */ /** @var string */
private static $username; private static $username;
/** @var PDO */ /** @var PDO */
protected $pdo; protected $pdo;
/** @var string */ /** @var string */
protected static $dsn = 'sqlite:database.db'; protected static $dsn = 'sqlite:database.db';
/** @var string */ /** @var string */
protected $currentDriver; protected $currentDriver;
public function __construct(string $dsn, string $username = null, string $password = null) public function __construct(string $dsn, string $username = null, string $password = null)
{ {
self::setDsn($dsn, $username, $password); self::setDsn($dsn, $username, $password);
$this->pdo = new PDO($dsn, $username, $password); $this->pdo = new PDO($dsn, $username, $password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$this->currentDriver = $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME); $this->currentDriver = $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($this->currentDriver === 'sqlite') { if ($this->currentDriver === 'sqlite') {
$this->pdo->exec('PRAGMA foreign_keys = ON'); $this->pdo->exec('PRAGMA foreign_keys = ON');
} }
} }
public function query(string $query, $parameters = []) public function query(string $query, $parameters = [])
{ {
if (!is_array($parameters)) { if (!is_array($parameters)) {
$parameters = [$parameters]; $parameters = [$parameters];
} }
$query = $this->pdo->prepare($query); $query = $this->pdo->prepare($query);
foreach ($parameters as $index => $parameter) { foreach ($parameters as $index => $parameter) {
$query->bindValue($index + 1, $parameter, is_int($parameter) ? PDO::PARAM_INT : PDO::PARAM_STR); $query->bindValue($index + 1, $parameter, is_int($parameter) ? PDO::PARAM_INT : PDO::PARAM_STR);
} }
$query->execute(); $query->execute();
return $query; return $query;
} }
/** /**
* Get the PDO instance * Get the PDO instance
* @return PDO * @return PDO
*/ */
public function getPdo(): PDO public function getPdo(): PDO
{ {
return $this->pdo; return $this->pdo;
} }
/** /**
* Get the current PDO driver * Get the current PDO driver
* @return string * @return string
*/ */
public function getCurrentDriver(): string public function getCurrentDriver(): string
{ {
return $this->currentDriver; return $this->currentDriver;
} }
public static function getInstance(): DB public static function getInstance(): DB
{ {
if (self::$instance === null) { if (self::$instance === null) {
self::$instance = new self(self::$dsn, self::$username, self::$password); self::$instance = new self(self::$dsn, self::$username, self::$password);
} }
return self::$instance; return self::$instance;
} }
/** /**
* Perform a query * Perform a query
* @param string $query * @param string $query
* @param array $parameters * @param array $parameters
* @return bool|\PDOStatement|string * @return bool|\PDOStatement|string
*/ */
public static function doQuery(string $query, $parameters = []) public static function doQuery(string $query, $parameters = [])
{ {
return self::getInstance()->query($query, $parameters); return self::getInstance()->query($query, $parameters);
} }
/** /**
* Static method to get the current driver name * Static method to get the current driver name
* @return string * @return string
*/ */
public static function driver(): string public static function driver(): string
{ {
return self::getInstance()->getCurrentDriver();
}
return self::getInstance()->getCurrentDriver(); /**
} * Get directly the PDO instance
* @return PDO
/** */
* Get directly the PDO instance public static function raw(): PDO
* @return PDO {
*/ return self::getInstance()->getPdo();
public static function raw(): PDO }
{
return self::getInstance()->getPdo();
}
/**
* Set the PDO connection string
* @param string $dsn
* @param string|null $username
* @param string|null $password
*/
public static function setDsn(string $dsn, string $username = null, string $password = null)
{
self::$dsn = $dsn;
self::$username = $username;
self::$password = $password;
}
/**
* Set the PDO connection string
* @param string $dsn
* @param string|null $username
* @param string|null $password
*/
public static function setDsn(string $dsn, string $username = null, string $password = null)
{
self::$dsn = $dsn;
self::$username = $username;
self::$password = $password;
}
} }

View file

@ -2,7 +2,6 @@
namespace App\Database\Queries; namespace App\Database\Queries;
use App\Database\DB; use App\Database\DB;
use League\Flysystem\FileNotFoundException; use League\Flysystem\FileNotFoundException;
use League\Flysystem\Filesystem; use League\Flysystem\Filesystem;
@ -10,222 +9,220 @@ use League\Flysystem\Plugin\ListFiles;
class MediaQuery class MediaQuery
{ {
const PER_PAGE = 21; const PER_PAGE = 21;
const PER_PAGE_ADMIN = 27; const PER_PAGE_ADMIN = 27;
const ORDER_TIME = 0; const ORDER_TIME = 0;
const ORDER_NAME = 1; const ORDER_NAME = 1;
const ORDER_SIZE = 2; const ORDER_SIZE = 2;
/** @var DB */ /** @var DB */
protected $db; protected $db;
/** @var bool */ /** @var bool */
protected $isAdmin; protected $isAdmin;
protected $userId; protected $userId;
/** @var int */ /** @var int */
protected $orderBy; protected $orderBy;
/** @var string */ /** @var string */
protected $orderMode; protected $orderMode;
/** @var string */ /** @var string */
protected $text; protected $text;
/** @var Filesystem */ /** @var Filesystem */
protected $storage; protected $storage;
private $pages; private $pages;
private $media; private $media;
/** /**
* MediaQuery constructor. * MediaQuery constructor.
* @param DB $db * @param DB $db
* @param bool $isAdmin * @param bool $isAdmin
* @param Filesystem $storage * @param Filesystem $storage
*/ */
public function __construct(DB $db, bool $isAdmin, Filesystem $storage) public function __construct(DB $db, bool $isAdmin, Filesystem $storage)
{ {
$this->db = $db; $this->db = $db;
$this->isAdmin = $isAdmin; $this->isAdmin = $isAdmin;
$this->storage = $storage; $this->storage = $storage;
} }
/** /**
* @param $id * @param $id
* @return $this * @return $this
*/ */
public function withUserId($id) public function withUserId($id)
{ {
$this->userId = $id; $this->userId = $id;
return $this; return $this;
} }
/** /**
* @param string|null $type * @param string|null $type
* @param string $mode * @param string $mode
* @return $this * @return $this
*/ */
public function orderBy(string $type = null, $mode = 'ASC') public function orderBy(string $type = null, $mode = 'ASC')
{ {
$this->orderBy = ($type === null) ? self::ORDER_TIME : $type; $this->orderBy = ($type === null) ? self::ORDER_TIME : $type;
$this->orderMode = (strtoupper($mode) === 'ASC') ? 'ASC' : 'DESC'; $this->orderMode = (strtoupper($mode) === 'ASC') ? 'ASC' : 'DESC';
return $this; return $this;
} }
/** /**
* @param string $text * @param string $text
* @return $this * @return $this
*/ */
public function search(?string $text) public function search(?string $text)
{ {
$this->text = $text; $this->text = $text;
return $this; return $this;
} }
/** /**
* @param int $page * @param int $page
*/ */
public function run(int $page) public function run(int $page)
{ {
if ($this->orderBy == self::ORDER_SIZE) { if ($this->orderBy == self::ORDER_SIZE) {
$this->runWithOrderBySize($page); $this->runWithOrderBySize($page);
return; return;
} }
$queryPages = 'SELECT COUNT(*) AS `count` FROM `uploads`'; $queryPages = 'SELECT COUNT(*) AS `count` FROM `uploads`';
if ($this->isAdmin) { if ($this->isAdmin) {
$queryMedia = 'SELECT `uploads`.*, `users`.`user_code`, `users`.`username` FROM `uploads` LEFT JOIN `users` ON `uploads`.`user_id` = `users`.`id` %s LIMIT ? OFFSET ?'; $queryMedia = 'SELECT `uploads`.*, `users`.`user_code`, `users`.`username` FROM `uploads` LEFT JOIN `users` ON `uploads`.`user_id` = `users`.`id` %s LIMIT ? OFFSET ?';
} else { } else {
$queryMedia = 'SELECT `uploads`.*,`users`.`user_code`, `users`.`username` FROM `uploads` INNER JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `user_id` = ? %s LIMIT ? OFFSET ?'; $queryMedia = 'SELECT `uploads`.*,`users`.`user_code`, `users`.`username` FROM `uploads` INNER JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `user_id` = ? %s LIMIT ? OFFSET ?';
$queryPages .= ' WHERE `user_id` = ?'; $queryPages .= ' WHERE `user_id` = ?';
} }
$orderAndSearch = ''; $orderAndSearch = '';
$params = []; $params = [];
if ($this->text !== null) { if ($this->text !== null) {
$orderAndSearch = $this->isAdmin ? 'WHERE `uploads`.`filename` LIKE ? ' : 'AND `uploads`.`filename` LIKE ? '; $orderAndSearch = $this->isAdmin ? 'WHERE `uploads`.`filename` LIKE ? ' : 'AND `uploads`.`filename` LIKE ? ';
$queryPages .= $this->isAdmin ? ' WHERE `filename` LIKE ?' : ' AND `filename` LIKE ?'; $queryPages .= $this->isAdmin ? ' WHERE `filename` LIKE ?' : ' AND `filename` LIKE ?';
$params[] = '%' . htmlentities($this->text) . '%'; $params[] = '%' . htmlentities($this->text) . '%';
} }
switch ($this->orderBy) { switch ($this->orderBy) {
case self::ORDER_NAME: case self::ORDER_NAME:
$orderAndSearch .= 'ORDER BY `filename` ' . $this->orderMode; $orderAndSearch .= 'ORDER BY `filename` ' . $this->orderMode;
break; break;
default: default:
case self::ORDER_TIME: case self::ORDER_TIME:
$orderAndSearch .= 'ORDER BY `timestamp` ' . $this->orderMode; $orderAndSearch .= 'ORDER BY `timestamp` ' . $this->orderMode;
break; break;
} }
$queryMedia = sprintf($queryMedia, $orderAndSearch); $queryMedia = sprintf($queryMedia, $orderAndSearch);
if ($this->isAdmin) { if ($this->isAdmin) {
$this->media = $this->db->query($queryMedia, array_merge($params, [self::PER_PAGE_ADMIN, $page * self::PER_PAGE_ADMIN]))->fetchAll(); $this->media = $this->db->query($queryMedia, array_merge($params, [self::PER_PAGE_ADMIN, $page * self::PER_PAGE_ADMIN]))->fetchAll();
$this->pages = $this->db->query($queryPages, $params)->fetch()->count / self::PER_PAGE_ADMIN; $this->pages = $this->db->query($queryPages, $params)->fetch()->count / self::PER_PAGE_ADMIN;
} else { } else {
$this->media = $this->db->query($queryMedia, array_merge([$this->userId], $params, [self::PER_PAGE, $page * self::PER_PAGE]))->fetchAll(); $this->media = $this->db->query($queryMedia, array_merge([$this->userId], $params, [self::PER_PAGE, $page * self::PER_PAGE]))->fetchAll();
$this->pages = $this->db->query($queryPages, array_merge([$this->userId], $params))->fetch()->count / self::PER_PAGE; $this->pages = $this->db->query($queryPages, array_merge([$this->userId], $params))->fetch()->count / self::PER_PAGE;
} }
foreach ($this->media as $media) { foreach ($this->media as $media) {
try { try {
$media->size = humanFileSize($this->storage->getSize($media->storage_path)); $media->size = humanFileSize($this->storage->getSize($media->storage_path));
$media->mimetype = $this->storage->getMimetype($media->storage_path); $media->mimetype = $this->storage->getMimetype($media->storage_path);
} catch (FileNotFoundException $e) { } catch (FileNotFoundException $e) {
$media->size = null; $media->size = null;
$media->mimetype = null; $media->mimetype = null;
} }
$media->extension = pathinfo($media->filename, PATHINFO_EXTENSION); $media->extension = pathinfo($media->filename, PATHINFO_EXTENSION);
} }
}
} /**
* @param int $page
*/
private function runWithOrderBySize(int $page)
{
$this->storage->addPlugin(new ListFiles());
/** if ($this->isAdmin) {
* @param int $page $files = $this->storage->listFiles('/', true);
*/ $this->pages = count($files) / self::PER_PAGE_ADMIN;
private function runWithOrderBySize(int $page)
{
$this->storage->addPlugin(new ListFiles());
if ($this->isAdmin) { $offset = $page * self::PER_PAGE_ADMIN;
$files = $this->storage->listFiles('/', true); $limit = self::PER_PAGE_ADMIN;
$this->pages = count($files) / self::PER_PAGE_ADMIN; } else {
$userCode = $this->db->query('SELECT `user_code` FROM `users` WHERE `id` = ?', [$this->userId])->fetch()->user_code;
$files = $this->storage->listFiles($userCode);
$this->pages = count($files) / self::PER_PAGE;
$offset = $page * self::PER_PAGE_ADMIN; $offset = $page * self::PER_PAGE;
$limit = self::PER_PAGE_ADMIN; $limit = self::PER_PAGE;
} else { }
$userCode = $this->db->query('SELECT `user_code` FROM `users` WHERE `id` = ?', [$this->userId])->fetch()->user_code;
$files = $this->storage->listFiles($userCode);
$this->pages = count($files) / self::PER_PAGE;
$offset = $page * self::PER_PAGE; array_multisort(array_column($files, 'size'), ($this->orderMode === 'ASC') ? SORT_ASC : SORT_DESC, SORT_NUMERIC, $files);
$limit = self::PER_PAGE;
}
array_multisort(array_column($files, 'size'), ($this->orderMode === 'ASC') ? SORT_ASC : SORT_DESC, SORT_NUMERIC, $files); if ($this->text !== null) {
if ($this->isAdmin) {
$medias = $this->db->query('SELECT `uploads`.*, `users`.`user_code`, `users`.`username` FROM `uploads` LEFT JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `uploads`.`filename` LIKE ? ', ['%' . htmlentities($this->text) . '%'])->fetchAll();
} else {
$medias = $this->db->query('SELECT `uploads`.*, `users`.`user_code`, `users`.`username` FROM `uploads` LEFT JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `user_id` = ? AND `uploads`.`filename` LIKE ? ', [$this->userId, '%' . htmlentities($this->text) . '%'])->fetchAll();
}
if ($this->text !== null) { $paths = array_column($files, 'path');
if ($this->isAdmin) { } else {
$medias = $this->db->query('SELECT `uploads`.*, `users`.`user_code`, `users`.`username` FROM `uploads` LEFT JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `uploads`.`filename` LIKE ? ', ['%' . htmlentities($this->text) . '%'])->fetchAll(); $files = array_slice($files, $offset, $limit);
} else { $paths = array_column($files, 'path');
$medias = $this->db->query('SELECT `uploads`.*, `users`.`user_code`, `users`.`username` FROM `uploads` LEFT JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `user_id` = ? AND `uploads`.`filename` LIKE ? ', [$this->userId, '%' . htmlentities($this->text) . '%'])->fetchAll();
}
$paths = array_column($files, 'path'); $medias = $this->db->query('SELECT `uploads`.*, `users`.`user_code`, `users`.`username` FROM `uploads` LEFT JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `uploads`.`storage_path` IN ("' . implode('","', $paths) . '")')->fetchAll();
} else { }
$files = array_slice($files, $offset, $limit);
$paths = array_column($files, 'path');
$medias = $this->db->query('SELECT `uploads`.*, `users`.`user_code`, `users`.`username` FROM `uploads` LEFT JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `uploads`.`storage_path` IN ("' . implode('","', $paths) . '")')->fetchAll(); $paths = array_flip($paths);
} foreach ($medias as $media) {
$paths[$media->storage_path] = $media;
}
$paths = array_flip($paths); $this->media = [];
foreach ($medias as $media) { foreach ($files as $file) {
$paths[$media->storage_path] = $media; $media = $paths[$file['path']];
} if (!is_object($media)) {
continue;
}
$media->size = humanFileSize($file['size']);
try {
$media->mimetype = $this->storage->getMimetype($file['path']);
} catch (FileNotFoundException $e) {
$media->mimetype = null;
}
$media->extension = $file['extension'];
$this->media[] = $media;
}
$this->media = []; if ($this->text !== null) {
foreach ($files as $file) { $this->media = array_slice($this->media, $offset, $limit);
$media = $paths[$file['path']]; }
if (!is_object($media)) { }
continue;
}
$media->size = humanFileSize($file['size']);
try {
$media->mimetype = $this->storage->getMimetype($file['path']);
} catch (FileNotFoundException $e) {
$media->mimetype = null;
}
$media->extension = $file['extension'];
$this->media[] = $media;
}
if ($this->text !== null) { /**
$this->media = array_slice($this->media, $offset, $limit); * @return mixed
} */
} public function getMedia()
{
return $this->media;
}
/** /**
* @return mixed * @return mixed
*/ */
public function getMedia() public function getPages()
{ {
return $this->media; return $this->pages;
}
}
/**
* @return mixed
*/
public function getPages()
{
return $this->pages;
}
} }

View file

@ -2,14 +2,13 @@
namespace App\Exceptions; namespace App\Exceptions;
use Exception; use Exception;
use Throwable; use Throwable;
class MaintenanceException extends Exception class MaintenanceException extends Exception
{ {
public function __construct(string $message = 'Under Maintenance', int $code = 503, Throwable $previous = null) public function __construct(string $message = 'Under Maintenance', int $code = 503, Throwable $previous = null)
{ {
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
} }
} }

View file

@ -2,14 +2,13 @@
namespace App\Exceptions; namespace App\Exceptions;
use Exception; use Exception;
use Throwable; use Throwable;
class UnauthorizedException extends Exception class UnauthorizedException extends Exception
{ {
public function __construct(string $message = 'Forbidden', int $code = 403, Throwable $previous = null) public function __construct(string $message = 'Forbidden', int $code = 403, Throwable $previous = null)
{ {
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
} }
} }

View file

@ -8,21 +8,20 @@ use Slim\Http\Response;
class AdminMiddleware extends Middleware class AdminMiddleware extends Middleware
{ {
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @param callable $next * @param callable $next
* @return Response * @return Response
* @throws UnauthorizedException * @throws UnauthorizedException
*/ */
public function __invoke(Request $request, Response $response, callable $next) public function __invoke(Request $request, Response $response, callable $next)
{ {
if (!$this->database->query('SELECT `id`, `is_admin` FROM `users` WHERE `id` = ? LIMIT 1', [$this->session->get('user_id')])->fetch()->is_admin) { if (!$this->database->query('SELECT `id`, `is_admin` FROM `users` WHERE `id` = ? LIMIT 1', [$this->session->get('user_id')])->fetch()->is_admin) {
$this->session->set('admin', false); $this->session->set('admin', false);
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
return $next($request, $response);
}
return $next($request, $response);
}
} }

View file

@ -8,27 +8,26 @@ use Slim\Http\Response;
class AuthMiddleware extends Middleware class AuthMiddleware extends Middleware
{ {
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @param callable $next * @param callable $next
* @return Response * @return Response
*/ */
public function __invoke(Request $request, Response $response, callable $next) public function __invoke(Request $request, Response $response, callable $next)
{ {
if (!$this->session->get('logged', false)) { if (!$this->session->get('logged', false)) {
$this->session->set('redirectTo', (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); $this->session->set('redirectTo', (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
return redirect($response, 'login.show'); return redirect($response, 'login.show');
} }
if (!$this->database->query('SELECT `id`, `active` FROM `users` WHERE `id` = ? LIMIT 1', [$this->session->get('user_id')])->fetch()->active) { if (!$this->database->query('SELECT `id`, `active` FROM `users` WHERE `id` = ? LIMIT 1', [$this->session->get('user_id')])->fetch()->active) {
$this->session->alert('Your account is not active anymore.', 'danger'); $this->session->alert('Your account is not active anymore.', 'danger');
$this->session->set('logged', false); $this->session->set('logged', false);
$this->session->set('redirectTo', (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); $this->session->set('redirectTo', (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
return redirect($response, 'login.show'); return redirect($response, 'login.show');
} }
return $next($request, $response);
}
return $next($request, $response);
}
} }

View file

@ -8,19 +8,19 @@ use Slim\Http\Response;
class CheckForMaintenanceMiddleware extends Middleware class CheckForMaintenanceMiddleware extends Middleware
{ {
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @param callable $next * @param callable $next
* @return Response * @return Response
* @throws MaintenanceException * @throws MaintenanceException
*/ */
public function __invoke(Request $request, Response $response, callable $next) public function __invoke(Request $request, Response $response, callable $next)
{ {
if (isset($this->settings['maintenance']) && $this->settings['maintenance'] && !$this->database->query('SELECT `id`, `is_admin` FROM `users` WHERE `id` = ? LIMIT 1', [$this->session->get('user_id')])->fetch()->is_admin) { if (isset($this->settings['maintenance']) && $this->settings['maintenance'] && !$this->database->query('SELECT `id`, `is_admin` FROM `users` WHERE `id` = ? LIMIT 1', [$this->session->get('user_id')])->fetch()->is_admin) {
throw new MaintenanceException(); throw new MaintenanceException();
} }
return $next($request, $response); return $next($request, $response);
} }
} }

View file

@ -8,31 +8,31 @@ use Slim\Http\Response;
abstract class Middleware abstract class Middleware
{ {
/** @var Container */ /** @var Container */
protected $container; protected $container;
public function __construct(Container $container) public function __construct(Container $container)
{ {
$this->container = $container; $this->container = $container;
} }
/** /**
* @param $name * @param $name
* @return mixed|null * @return mixed|null
* @throws \Interop\Container\Exception\ContainerException * @throws \Interop\Container\Exception\ContainerException
*/ */
public function __get($name) public function __get($name)
{ {
if ($this->container->has($name)) { if ($this->container->has($name)) {
return $this->container->get($name); return $this->container->get($name);
} }
return null; return null;
} }
/** /**
* @param Request $request * @param Request $request
* @param Response $response * @param Response $response
* @param callable $next * @param callable $next
*/ */
public abstract function __invoke(Request $request, Response $response, callable $next); abstract public function __invoke(Request $request, Response $response, callable $next);
} }

View file

@ -2,138 +2,136 @@
namespace App\Web; namespace App\Web;
class Lang class Lang
{ {
const DEFAULT_LANG = 'en';
const LANG_PATH = __DIR__ . '../../resources/lang/';
const DEFAULT_LANG = 'en'; /** @var string */
const LANG_PATH = __DIR__ . '../../resources/lang/'; protected static $langPath = self::LANG_PATH;
/** @var string */ /** @var string */
protected static $langPath = self::LANG_PATH; protected static $lang;
/** @var string */ /** @var Lang */
protected static $lang; protected static $instance;
/** @var Lang */ /** @var array */
protected static $instance; protected $cache = [];
/** @var array */
protected $cache = [];
/** /**
* @return Lang * @return Lang
*/ */
public static function getInstance(): Lang public static function getInstance(): Lang
{ {
if (self::$instance === null) { if (self::$instance === null) {
self::$instance = new self(); self::$instance = new self();
} }
return self::$instance; return self::$instance;
} }
/** /**
* @param string $lang * @param string $lang
* @param string $langPath * @param string $langPath
* @return Lang * @return Lang
*/ */
public static function build($lang = self::DEFAULT_LANG, $langPath = null): Lang public static function build($lang = self::DEFAULT_LANG, $langPath = null): Lang
{ {
self::$lang = $lang; self::$lang = $lang;
if ($langPath !== null) { if ($langPath !== null) {
self::$langPath = $langPath; self::$langPath = $langPath;
} }
self::$instance = new self(); self::$instance = new self();
return self::$instance; return self::$instance;
} }
/** /**
* Recognize the current language from the request. * Recognize the current language from the request.
* @return bool|string * @return bool|string
*/ */
public static function recognize() public static function recognize()
{ {
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
return locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']); return locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
} }
return self::DEFAULT_LANG; return self::DEFAULT_LANG;
} }
/** /**
* @return string * @return string
*/ */
public static function getLang(): string public static function getLang(): string
{ {
return self::$lang; return self::$lang;
} }
/** /**
* @return array * @return array
*/ */
public static function getList() public static function getList()
{ {
$languages = []; $languages = [];
$default = count(include self::$langPath . self::DEFAULT_LANG . '.lang.php') - 1; $default = count(include self::$langPath . self::DEFAULT_LANG . '.lang.php') - 1;
foreach (glob(self::$langPath . '*.lang.php') as $file) { foreach (glob(self::$langPath . '*.lang.php') as $file) {
$dict = include $file; $dict = include $file;
$count = count($dict) - 1; $count = count($dict) - 1;
$prepend = "[{$count}/{$default}] "; $prepend = "[{$count}/{$default}] ";
$languages[str_replace('.lang.php', '', basename($file))] = $prepend . $dict['lang']; $languages[str_replace('.lang.php', '', basename($file))] = $prepend . $dict['lang'];
} }
return $languages; return $languages;
} }
/** /**
* @param $key * @param $key
* @param array $args * @param array $args
* @return string * @return string
*/ */
public function get($key, $args = []): string public function get($key, $args = []): string
{ {
return $this->getString($key, self::$lang, $args); return $this->getString($key, self::$lang, $args);
} }
/** /**
* @param $key * @param $key
* @param $lang * @param $lang
* @param $args * @param $args
* @return string * @return string
*/ */
private function getString($key, $lang, $args): string private function getString($key, $lang, $args): string
{ {
$redLang = strtolower(substr($lang, 0, 2)); $redLang = strtolower(substr($lang, 0, 2));
if (array_key_exists($lang, $this->cache)) { if (array_key_exists($lang, $this->cache)) {
$transDict = $this->cache[$lang]; $transDict = $this->cache[$lang];
} else if (file_exists(self::$langPath . $lang . '.lang.php')) { } elseif (file_exists(self::$langPath . $lang . '.lang.php')) {
$transDict = include self::$langPath . $lang . '.lang.php'; $transDict = include self::$langPath . $lang . '.lang.php';
$this->cache[$lang] = $transDict; $this->cache[$lang] = $transDict;
} else if (file_exists(self::$langPath . $redLang . '.lang.php')) { } elseif (file_exists(self::$langPath . $redLang . '.lang.php')) {
$transDict = include self::$langPath . $redLang . '.lang.php'; $transDict = include self::$langPath . $redLang . '.lang.php';
$this->cache[$lang] = $transDict; $this->cache[$lang] = $transDict;
} else { } else {
$transDict = []; $transDict = [];
} }
if (array_key_exists($key, $transDict)) { if (array_key_exists($key, $transDict)) {
return vsprintf($transDict[$key], $args); return vsprintf($transDict[$key], $args);
} }
if ($lang !== self::DEFAULT_LANG) { if ($lang !== self::DEFAULT_LANG) {
return $this->getString($key, self::DEFAULT_LANG, $args); return $this->getString($key, self::DEFAULT_LANG, $args);
} }
return $key; return $key;
} }
} }

View file

@ -2,115 +2,113 @@
namespace App\Web; namespace App\Web;
use Exception; use Exception;
class Session class Session
{ {
/** /**
* Session constructor. * Session constructor.
* @param string $name * @param string $name
* @param string $path * @param string $path
* @throws Exception * @throws Exception
*/ */
public function __construct(string $name, $path = '') public function __construct(string $name, $path = '')
{ {
if (session_status() === PHP_SESSION_NONE) { if (session_status() === PHP_SESSION_NONE) {
if (!is_writable($path) && $path !== '') { if (!is_writable($path) && $path !== '') {
throw new Exception("The given path '{$path}' is not writable."); throw new Exception("The given path '{$path}' is not writable.");
} }
$started = @session_start([ $started = @session_start([
'name' => $name, 'name' => $name,
'save_path' => $path, 'save_path' => $path,
'cookie_httponly' => true, 'cookie_httponly' => true,
'gc_probability' => 25, 'gc_probability' => 25,
]); ]);
if (!$started) { if (!$started) {
throw new Exception("Cannot start the HTTP session. That the session path '{$path}' is writable and your PHP settings."); throw new Exception("Cannot start the HTTP session. That the session path '{$path}' is writable and your PHP settings.");
} }
} }
} }
/** /**
* Destroy the current session * Destroy the current session
* @return bool * @return bool
*/ */
public function destroy(): bool public function destroy(): bool
{ {
return session_destroy(); return session_destroy();
} }
/** /**
* Clear all session stored values * Clear all session stored values
*/ */
public function clear(): void public function clear(): void
{ {
$_SESSION = []; $_SESSION = [];
} }
/** /**
* Check if session has a stored key * Check if session has a stored key
* @param $key * @param $key
* @return bool * @return bool
*/ */
public function has($key): bool public function has($key): bool
{ {
return isset($_SESSION[$key]); return isset($_SESSION[$key]);
} }
/** /**
* Get the content of the current session * Get the content of the current session
* @return array * @return array
*/ */
public function all(): array public function all(): array
{ {
return $_SESSION; return $_SESSION;
} }
/** /**
* Returned a value given a key * Returned a value given a key
* @param $key * @param $key
* @param null $default * @param null $default
* @return mixed * @return mixed
*/ */
public function get($key, $default = null) public function get($key, $default = null)
{ {
return self::has($key) ? $_SESSION[$key] : $default; return self::has($key) ? $_SESSION[$key] : $default;
} }
/** /**
* Add a key-value pair to the session * Add a key-value pair to the session
* @param $key * @param $key
* @param $value * @param $value
*/ */
public function set($key, $value): void public function set($key, $value): void
{ {
$_SESSION[$key] = $value; $_SESSION[$key] = $value;
} }
/** /**
* Set a flash alert * Set a flash alert
* @param $message * @param $message
* @param string $type * @param string $type
*/ */
public function alert($message, string $type = 'info'): void public function alert($message, string $type = 'info'): void
{ {
$_SESSION['_flash'][] = [$type => $message]; $_SESSION['_flash'][] = [$type => $message];
} }
/** /**
* Retrieve flash alerts * Retrieve flash alerts
* @return array * @return array
*/ */
public function getAlert(): ?array public function getAlert(): ?array
{ {
$flash = self::get('_flash'); $flash = self::get('_flash');
self::set('_flash', []); self::set('_flash', []);
return $flash; return $flash;
} }
} }

View file

@ -1,318 +1,318 @@
<?php <?php
if (!defined('HUMAN_RANDOM_CHARS')) { if (!defined('HUMAN_RANDOM_CHARS')) {
define('HUMAN_RANDOM_CHARS', 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZaeiouAEIOU'); define('HUMAN_RANDOM_CHARS', 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZaeiouAEIOU');
} }
if (!function_exists('humanFileSize')) { if (!function_exists('humanFileSize')) {
/** /**
* Generate a human readable file size * Generate a human readable file size
* @param $size * @param $size
* @param int $precision * @param int $precision
* @return string * @return string
*/ */
function humanFileSize($size, $precision = 2): string function humanFileSize($size, $precision = 2): string
{ {
for ($i = 0; ($size / 1024) > 0.9; $i++, $size /= 1024) { for ($i = 0; ($size / 1024) > 0.9; $i++, $size /= 1024) {
} }
return round($size, $precision) . ' ' . ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][$i]; return round($size, $precision) . ' ' . ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][$i];
} }
} }
if (!function_exists('humanRandomString')) { if (!function_exists('humanRandomString')) {
/** /**
* @param int $length * @param int $length
* @return string * @return string
*/ */
function humanRandomString(int $length = 13): string function humanRandomString(int $length = 13): string
{ {
$result = ''; $result = '';
$numberOffset = round($length * 0.2); $numberOffset = round($length * 0.2);
for ($x = 0; $x < $length - $numberOffset; $x++) { for ($x = 0; $x < $length - $numberOffset; $x++) {
$result .= ($x % 2) ? HUMAN_RANDOM_CHARS[rand(42, 51)] : HUMAN_RANDOM_CHARS[rand(0, 41)]; $result .= ($x % 2) ? HUMAN_RANDOM_CHARS[rand(42, 51)] : HUMAN_RANDOM_CHARS[rand(0, 41)];
} }
for ($x = 0; $x < $numberOffset; $x++) { for ($x = 0; $x < $numberOffset; $x++) {
$result .= rand(0, 9); $result .= rand(0, 9);
} }
return $result; return $result;
} }
} }
if (!function_exists('isDisplayableImage')) { if (!function_exists('isDisplayableImage')) {
/** /**
* @param string $mime * @param string $mime
* @return bool * @return bool
*/ */
function isDisplayableImage(string $mime): bool function isDisplayableImage(string $mime): bool
{ {
return in_array($mime, [ return in_array($mime, [
'image/apng', 'image/apng',
'image/bmp', 'image/bmp',
'image/gif', 'image/gif',
'image/x-icon', 'image/x-icon',
'image/jpeg', 'image/jpeg',
'image/png', 'image/png',
'image/svg', 'image/svg',
'image/svg+xml', 'image/svg+xml',
'image/tiff', 'image/tiff',
'image/webp', 'image/webp',
]); ]);
} }
} }
if (!function_exists('stringToBytes')) { if (!function_exists('stringToBytes')) {
/** /**
* @param $str * @param $str
* @return float * @return float
*/ */
function stringToBytes(string $str): float function stringToBytes(string $str): float
{ {
$val = trim($str); $val = trim($str);
if (is_numeric($val)) { if (is_numeric($val)) {
return (float)$val; return (float)$val;
} }
$last = strtolower($val[strlen($val) - 1]); $last = strtolower($val[strlen($val) - 1]);
$val = substr($val, 0, -1); $val = substr($val, 0, -1);
$val = (float)$val; $val = (float)$val;
switch ($last) { switch ($last) {
case 'g': case 'g':
$val *= 1024; $val *= 1024;
case 'm': case 'm':
$val *= 1024; $val *= 1024;
case 'k': case 'k':
$val *= 1024; $val *= 1024;
} }
return $val; return $val;
} }
} }
if (!function_exists('removeDirectory')) { if (!function_exists('removeDirectory')) {
/** /**
* Remove a directory and it's content * Remove a directory and it's content
* @param $path * @param $path
*/ */
function removeDirectory($path) function removeDirectory($path)
{ {
$files = glob($path . '/*'); $files = glob($path . '/*');
foreach ($files as $file) { foreach ($files as $file) {
is_dir($file) ? removeDirectory($file) : unlink($file); is_dir($file) ? removeDirectory($file) : unlink($file);
} }
rmdir($path); rmdir($path);
return; return;
} }
} }
if (!function_exists('cleanDirectory')) { if (!function_exists('cleanDirectory')) {
/** /**
* Removes all directory contents * Removes all directory contents
* @param $path * @param $path
*/ */
function cleanDirectory($path) function cleanDirectory($path)
{ {
$directoryIterator = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS); $directoryIterator = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
$iteratorIterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST); $iteratorIterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iteratorIterator as $file) { foreach ($iteratorIterator as $file) {
if ($file->getFilename() !== '.gitkeep') { if ($file->getFilename() !== '.gitkeep') {
$file->isDir() ? rmdir($file) : unlink($file); $file->isDir() ? rmdir($file) : unlink($file);
} }
} }
} }
} }
if (!function_exists('redirect')) { if (!function_exists('redirect')) {
/** /**
* Set the redirect response * Set the redirect response
* @param \Slim\Http\Response $response * @param \Slim\Http\Response $response
* @param string $path * @param string $path
* @param array $args * @param array $args
* @param null $status * @param null $status
* @return \Slim\Http\Response * @return \Slim\Http\Response
*/ */
function redirect(\Slim\Http\Response $response, string $path, $args = [], $status = null) function redirect(\Slim\Http\Response $response, string $path, $args = [], $status = null)
{ {
if (substr($path, 0, 1) === '/' || substr($path, 0, 3) === '../' || substr($path, 0, 2) === './') { if (substr($path, 0, 1) === '/' || substr($path, 0, 3) === '../' || substr($path, 0, 2) === './') {
$url = urlFor($path); $url = urlFor($path);
} else { } else {
$url = route($path, $args); $url = route($path, $args);
} }
return $response->withRedirect($url, $status); return $response->withRedirect($url, $status);
} }
} }
if (!function_exists('asset')) { if (!function_exists('asset')) {
/** /**
* Get the asset link with timestamp * Get the asset link with timestamp
* @param string $path * @param string $path
* @return string * @return string
*/ */
function asset(string $path): string function asset(string $path): string
{ {
return urlFor($path, '?' . filemtime(realpath(BASE_DIR . $path))); return urlFor($path, '?' . filemtime(realpath(BASE_DIR . $path)));
} }
} }
if (!function_exists('urlFor')) { if (!function_exists('urlFor')) {
/** /**
* Generate the app url given a path * Generate the app url given a path
* @param string $path * @param string $path
* @param string $append * @param string $append
* @return string * @return string
*/ */
function urlFor(string $path, string $append = ''): string function urlFor(string $path, string $append = ''): string
{ {
global $app; global $app;
$baseUrl = $app->getContainer()->get('settings')['base_url']; $baseUrl = $app->getContainer()->get('settings')['base_url'];
return $baseUrl . $path . $append; return $baseUrl . $path . $append;
} }
} }
if (!function_exists('route')) { if (!function_exists('route')) {
/** /**
* Generate the app url given a path * Generate the app url given a path
* @param string $path * @param string $path
* @param array $args * @param array $args
* @param string $append * @param string $append
* @return string * @return string
*/ */
function route(string $path, array $args = [], string $append = ''): string function route(string $path, array $args = [], string $append = ''): string
{ {
global $app; global $app;
$uri = $app->getContainer()->get('router')->relativePathFor($path, $args); $uri = $app->getContainer()->get('router')->relativePathFor($path, $args);
return urlFor($uri, $append); return urlFor($uri, $append);
} }
} }
if (!function_exists('lang')) { if (!function_exists('lang')) {
/** /**
* @param string $key * @param string $key
* @param array $args * @param array $args
* @return string * @return string
*/ */
function lang(string $key, $args = []): string function lang(string $key, $args = []): string
{ {
global $app; global $app;
return $app->getContainer()->get('lang')->get($key, $args); return $app->getContainer()->get('lang')->get($key, $args);
} }
} }
if (!function_exists('isBot')) { if (!function_exists('isBot')) {
/** /**
* @param string $userAgent * @param string $userAgent
* @return boolean * @return boolean
*/ */
function isBot(string $userAgent) function isBot(string $userAgent)
{ {
$bots = [ $bots = [
'TelegramBot', 'TelegramBot',
'facebookexternalhit/', 'facebookexternalhit/',
'Discordbot/', 'Discordbot/',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Firefox/38.0', // The discord service bot? 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Firefox/38.0', // The discord service bot?
'Facebot', 'Facebot',
'curl/', 'curl/',
'wget/', 'wget/',
]; ];
foreach ($bots as $bot) { foreach ($bots as $bot) {
if (stripos($userAgent, $bot) !== false) { if (stripos($userAgent, $bot) !== false) {
return true; return true;
} }
} }
return false; return false;
} }
} }
if (!function_exists('mime2font')) { if (!function_exists('mime2font')) {
/** /**
* Convert get the icon from the file mimetype * Convert get the icon from the file mimetype
* @param $mime * @param $mime
* @return mixed|string * @return mixed|string
*/ */
function mime2font($mime) function mime2font($mime)
{ {
$classes = [ $classes = [
'image' => 'fa-file-image', 'image' => 'fa-file-image',
'audio' => 'fa-file-audio', 'audio' => 'fa-file-audio',
'video' => 'fa-file-video', 'video' => 'fa-file-video',
'application/pdf' => 'fa-file-pdf', 'application/pdf' => 'fa-file-pdf',
'application/msword' => 'fa-file-word', 'application/msword' => 'fa-file-word',
'application/vnd.ms-word' => 'fa-file-word', 'application/vnd.ms-word' => 'fa-file-word',
'application/vnd.oasis.opendocument.text' => 'fa-file-word', 'application/vnd.oasis.opendocument.text' => 'fa-file-word',
'application/vnd.openxmlformats-officedocument.wordprocessingml' => 'fa-file-word', 'application/vnd.openxmlformats-officedocument.wordprocessingml' => 'fa-file-word',
'application/vnd.ms-excel' => 'fa-file-excel', 'application/vnd.ms-excel' => 'fa-file-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml' => 'fa-file-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml' => 'fa-file-excel',
'application/vnd.oasis.opendocument.spreadsheet' => 'fa-file-excel', 'application/vnd.oasis.opendocument.spreadsheet' => 'fa-file-excel',
'application/vnd.ms-powerpoint' => 'fa-file-powerpoint', 'application/vnd.ms-powerpoint' => 'fa-file-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml' => 'fa-file-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml' => 'fa-file-powerpoint',
'application/vnd.oasis.opendocument.presentation' => 'fa-file-powerpoint', 'application/vnd.oasis.opendocument.presentation' => 'fa-file-powerpoint',
'text/plain' => 'fa-file-alt', 'text/plain' => 'fa-file-alt',
'text/html' => 'fa-file-code', 'text/html' => 'fa-file-code',
'text/x-php' => 'fa-file-code', 'text/x-php' => 'fa-file-code',
'application/json' => 'fa-file-code', 'application/json' => 'fa-file-code',
'application/gzip' => 'fa-file-archive', 'application/gzip' => 'fa-file-archive',
'application/zip' => 'fa-file-archive', 'application/zip' => 'fa-file-archive',
'application/octet-stream' => 'fa-file-alt', 'application/octet-stream' => 'fa-file-alt',
]; ];
foreach ($classes as $fullMime => $class) { foreach ($classes as $fullMime => $class) {
if (strpos($mime, $fullMime) === 0) { if (strpos($mime, $fullMime) === 0) {
return $class; return $class;
} }
} }
return 'fa-file'; return 'fa-file';
} }
} }
if (!function_exists('dd')) { if (!function_exists('dd')) {
/** /**
* Dumps all the given vars and halt the execution. * Dumps all the given vars and halt the execution.
*/ */
function dd() function dd()
{ {
array_map(function ($x) { array_map(function ($x) {
echo '<pre>'; echo '<pre>';
print_r($x); print_r($x);
echo '</pre>'; echo '</pre>';
}, func_get_args()); }, func_get_args());
die(); die();
} }
} }
if (!function_exists('queryParams')) { if (!function_exists('queryParams')) {
/** /**
* Get the query parameters of the current request. * Get the query parameters of the current request.
* @param array $replace * @param array $replace
* @return string * @return string
* @throws \Interop\Container\Exception\ContainerException * @throws \Interop\Container\Exception\ContainerException
*/ */
function queryParams(array $replace = []) function queryParams(array $replace = [])
{ {
global $container; global $container;
/** @var \Slim\Http\Request $request */ /** @var \Slim\Http\Request $request */
$request = $container->get('request'); $request = $container->get('request');
$params = array_replace_recursive($request->getQueryParams(), $replace); $params = array_replace_recursive($request->getQueryParams(), $replace);
return !empty($params) ? '?' . http_build_query($params) : ''; return !empty($params) ? '?' . http_build_query($params) : '';
} }
} }
if (!function_exists('glob_recursive')) { if (!function_exists('glob_recursive')) {
/** /**
* Does not support flag GLOB_BRACE * Does not support flag GLOB_BRACE
* @param $pattern * @param $pattern
* @param int $flags * @param int $flags
* @return array|false * @return array|false
*/ */
function glob_recursive($pattern, $flags = 0) function glob_recursive($pattern, $flags = 0)
{ {
$files = glob($pattern, $flags); $files = glob($pattern, $flags);
foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) { foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
$files = array_merge($files, glob_recursive($dir . '/' . basename($pattern), $flags)); $files = array_merge($files, glob_recursive($dir . '/' . basename($pattern), $flags));
} }
return $files; return $files;
} }
} }

View file

@ -12,46 +12,44 @@ use App\Middleware\AuthMiddleware;
use App\Middleware\CheckForMaintenanceMiddleware; use App\Middleware\CheckForMaintenanceMiddleware;
$app->group('', function () { $app->group('', function () {
$this->get('/home[/page/{page}]', DashboardController::class . ':home')->setName('home'); $this->get('/home[/page/{page}]', DashboardController::class . ':home')->setName('home');
$this->group('', function () { $this->group('', function () {
$this->get('/home/switchView', DashboardController::class . ':switchView')->setName('switchView'); $this->get('/home/switchView', DashboardController::class . ':switchView')->setName('switchView');
$this->get('/system/deleteOrphanFiles', AdminController::class . ':deleteOrphanFiles')->setName('system.deleteOrphanFiles'); $this->get('/system/deleteOrphanFiles', AdminController::class . ':deleteOrphanFiles')->setName('system.deleteOrphanFiles');
$this->get('/system/themes', ThemeController::class . ':getThemes')->setName('theme'); $this->get('/system/themes', ThemeController::class . ':getThemes')->setName('theme');
$this->post('/system/theme/apply', ThemeController::class . ':applyTheme')->setName('theme.apply'); $this->post('/system/theme/apply', ThemeController::class . ':applyTheme')->setName('theme.apply');
$this->post('/system/lang/apply', AdminController::class . ':applyLang')->setName('lang.apply'); $this->post('/system/lang/apply', AdminController::class . ':applyLang')->setName('lang.apply');
$this->post('/system/upgrade', UpgradeController::class . ':upgrade')->setName('system.upgrade'); $this->post('/system/upgrade', UpgradeController::class . ':upgrade')->setName('system.upgrade');
$this->get('/system/checkForUpdates', UpgradeController::class . ':checkForUpdates')->setName('system.checkForUpdates'); $this->get('/system/checkForUpdates', UpgradeController::class . ':checkForUpdates')->setName('system.checkForUpdates');
$this->get('/system', AdminController::class . ':system')->setName('system'); $this->get('/system', AdminController::class . ':system')->setName('system');
$this->get('/users[/page/{page}]', UserController::class . ':index')->setName('user.index'); $this->get('/users[/page/{page}]', UserController::class . ':index')->setName('user.index');
})->add(AdminMiddleware::class); })->add(AdminMiddleware::class);
$this->group('/user', function () { $this->group('/user', function () {
$this->get('/create', UserController::class . ':create')->setName('user.create');
$this->post('/create', UserController::class . ':store')->setName('user.store');
$this->get('/{id}/edit', UserController::class . ':edit')->setName('user.edit');
$this->post('/{id}', UserController::class . ':update')->setName('user.update');
$this->get('/{id}/delete', UserController::class . ':delete')->setName('user.delete');
})->add(AdminMiddleware::class);
$this->get('/create', UserController::class . ':create')->setName('user.create'); $this->get('/profile', UserController::class . ':profile')->setName('profile');
$this->post('/create', UserController::class . ':store')->setName('user.store'); $this->post('/profile/{id}', UserController::class . ':profileEdit')->setName('profile.update');
$this->get('/{id}/edit', UserController::class . ':edit')->setName('user.edit'); $this->post('/user/{id}/refreshToken', UserController::class . ':refreshToken')->setName('refreshToken');
$this->post('/{id}', UserController::class . ':update')->setName('user.update'); $this->get('/user/{id}/config/sharex', UserController::class . ':getShareXconfigFile')->setName('config.sharex');
$this->get('/{id}/delete', UserController::class . ':delete')->setName('user.delete'); $this->get('/user/{id}/config/script', UserController::class . ':getUploaderScriptFile')->setName('config.script');
})->add(AdminMiddleware::class);
$this->get('/profile', UserController::class . ':profile')->setName('profile');
$this->post('/profile/{id}', UserController::class . ':profileEdit')->setName('profile.update');
$this->post('/user/{id}/refreshToken', UserController::class . ':refreshToken')->setName('refreshToken');
$this->get('/user/{id}/config/sharex', UserController::class . ':getShareXconfigFile')->setName('config.sharex');
$this->get('/user/{id}/config/script', UserController::class . ':getUploaderScriptFile')->setName('config.script');
$this->post('/upload/{id}/publish', UploadController::class . ':togglePublish')->setName('upload.publish');
$this->post('/upload/{id}/unpublish', UploadController::class . ':togglePublish')->setName('upload.unpublish');
$this->get('/upload/{id}/raw', UploadController::class . ':getRawById')->add(AdminMiddleware::class)->setName('upload.raw');
$this->post('/upload/{id}/delete', UploadController::class . ':delete')->setName('upload.delete');
$this->post('/upload/{id}/publish', UploadController::class . ':togglePublish')->setName('upload.publish');
$this->post('/upload/{id}/unpublish', UploadController::class . ':togglePublish')->setName('upload.unpublish');
$this->get('/upload/{id}/raw', UploadController::class . ':getRawById')->add(AdminMiddleware::class)->setName('upload.raw');
$this->post('/upload/{id}/delete', UploadController::class . ':delete')->setName('upload.delete');
})->add(App\Middleware\CheckForMaintenanceMiddleware::class)->add(AuthMiddleware::class); })->add(App\Middleware\CheckForMaintenanceMiddleware::class)->add(AuthMiddleware::class);
$app->get('/', DashboardController::class . ':redirects')->setName('root'); $app->get('/', DashboardController::class . ':redirects')->setName('root');

View file

@ -27,196 +27,194 @@ use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter;
use Twig\TwigFunction; use Twig\TwigFunction;
if (!file_exists('config.php') && is_dir('install/')) { if (!file_exists('config.php') && is_dir('install/')) {
header('Location: ./install/'); header('Location: ./install/');
exit(); exit();
} else if (!file_exists('config.php') && !is_dir('install/')) { } elseif (!file_exists('config.php') && !is_dir('install/')) {
exit('Cannot find the config file.'); exit('Cannot find the config file.');
} }
// Load the config // Load the config
$config = array_replace_recursive([ $config = array_replace_recursive([
'app_name' => 'XBackBone', 'app_name' => 'XBackBone',
'base_url' => isset($_SERVER['HTTPS']) ? 'https://' . $_SERVER['HTTP_HOST'] : 'http://' . $_SERVER['HTTP_HOST'], 'base_url' => isset($_SERVER['HTTPS']) ? 'https://' . $_SERVER['HTTP_HOST'] : 'http://' . $_SERVER['HTTP_HOST'],
'displayErrorDetails' => false, 'displayErrorDetails' => false,
'maintenance' => false, 'maintenance' => false,
'db' => [ 'db' => [
'connection' => 'sqlite', 'connection' => 'sqlite',
'dsn' => BASE_DIR . 'resources/database/xbackbone.db', 'dsn' => BASE_DIR . 'resources/database/xbackbone.db',
'username' => null, 'username' => null,
'password' => null, 'password' => null,
], ],
'storage' => [ 'storage' => [
'driver' => 'local', 'driver' => 'local',
'path' => realpath(__DIR__ . '/') . DIRECTORY_SEPARATOR . 'storage', 'path' => realpath(__DIR__ . '/') . DIRECTORY_SEPARATOR . 'storage',
], ],
], require BASE_DIR . 'config.php'); ], require BASE_DIR . 'config.php');
if (!$config['displayErrorDetails']) { if (!$config['displayErrorDetails']) {
$config['routerCacheFile'] = BASE_DIR . 'resources/cache/routes.cache.php'; $config['routerCacheFile'] = BASE_DIR . 'resources/cache/routes.cache.php';
} }
$container = new Container(['settings' => $config]); $container = new Container(['settings' => $config]);
$container['config'] = function ($container) use ($config) { $container['config'] = function ($container) use ($config) {
return $config; return $config;
}; };
$container['logger'] = function ($container) { $container['logger'] = function ($container) {
$logger = new Logger('app'); $logger = new Logger('app');
$streamHandler = new RotatingFileHandler(BASE_DIR . 'logs/log.txt', 10, Logger::DEBUG); $streamHandler = new RotatingFileHandler(BASE_DIR . 'logs/log.txt', 10, Logger::DEBUG);
$lineFormatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", "Y-m-d H:i:s"); $lineFormatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", "Y-m-d H:i:s");
$lineFormatter->includeStacktraces(true); $lineFormatter->includeStacktraces(true);
$streamHandler->setFormatter($lineFormatter); $streamHandler->setFormatter($lineFormatter);
$logger->pushHandler($streamHandler); $logger->pushHandler($streamHandler);
return $logger; return $logger;
}; };
$container['session'] = function ($container) { $container['session'] = function ($container) {
return new Session('xbackbone_session', BASE_DIR . 'resources/sessions'); return new Session('xbackbone_session', BASE_DIR . 'resources/sessions');
}; };
$container['database'] = function ($container) use (&$config) { $container['database'] = function ($container) use (&$config) {
$dsn = $config['db']['connection'] === 'sqlite' ? BASE_DIR . $config['db']['dsn'] : $config['db']['dsn']; $dsn = $config['db']['connection'] === 'sqlite' ? BASE_DIR . $config['db']['dsn'] : $config['db']['dsn'];
return new DB($config['db']['connection'] . ':' . $dsn, $config['db']['username'], $config['db']['password']); return new DB($config['db']['connection'] . ':' . $dsn, $config['db']['username'], $config['db']['password']);
}; };
$container['storage'] = function ($container) use (&$config) { $container['storage'] = function ($container) use (&$config) {
switch ($config['storage']['driver']) {
case 'local':
return new Filesystem(new Local($config['storage']['path']));
case 's3':
$client = new S3Client([
'credentials' => [
'key' => $config['storage']['key'],
'secret' => $config['storage']['secret'],
],
'region' => $config['storage']['region'],
'version' => 'latest',
]);
switch ($config['storage']['driver']) { return new Filesystem(new AwsS3Adapter($client, $config['storage']['bucket'], $config['storage']['path']));
case 'local': case 'dropbox':
return new Filesystem(new Local($config['storage']['path'])); $client = new DropboxClient($config['storage']['token']);
case 's3': return new Filesystem(new DropboxAdapter($client), ['case_sensitive' => false]);
$client = new S3Client([ case 'ftp':
'credentials' => [ return new Filesystem(new FtpAdapter([
'key' => $config['storage']['key'], 'host' => $config['storage']['host'],
'secret' => $config['storage']['secret'], 'username' => $config['storage']['username'],
], 'password' => $config['storage']['password'],
'region' => $config['storage']['region'], 'port' => $config['storage']['port'],
'version' => 'latest', 'root' => $config['storage']['path'],
]); 'passive' => $config['storage']['passive'],
'ssl' => $config['storage']['ssl'],
return new Filesystem(new AwsS3Adapter($client, $config['storage']['bucket'], $config['storage']['path'])); 'timeout' => 30,
case 'dropbox': ]));
$client = new DropboxClient($config['storage']['token']); case 'google-cloud':
return new Filesystem(new DropboxAdapter($client), ['case_sensitive' => false]); $client = new StorageClient([
case 'ftp': 'projectId' => $config['storage']['project_id'],
return new Filesystem(new FtpAdapter([ 'keyFilePath' => $config['storage']['key_path'],
'host' => $config['storage']['host'], ]);
'username' => $config['storage']['username'], return new Filesystem(new GoogleStorageAdapter($client, $client->bucket($config['storage']['bucket'])));
'password' => $config['storage']['password'], default:
'port' => $config['storage']['port'], throw new InvalidArgumentException('The driver specified is not supported.');
'root' => $config['storage']['path'], }
'passive' => $config['storage']['passive'],
'ssl' => $config['storage']['ssl'],
'timeout' => 30,
]));
case 'google-cloud':
$client = new StorageClient([
'projectId' => $config['storage']['project_id'],
'keyFilePath' => $config['storage']['key_path'],
]);
return new Filesystem(new GoogleStorageAdapter($client, $client->bucket($config['storage']['bucket'])));
default:
throw new InvalidArgumentException('The driver specified is not supported.');
}
}; };
$container['lang'] = function ($container) use (&$config) { $container['lang'] = function ($container) use (&$config) {
if (isset($config['lang'])) { if (isset($config['lang'])) {
return Lang::build($config['lang'], BASE_DIR . 'resources/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/');
}; };
$container['view'] = function ($container) use (&$config) { $container['view'] = function ($container) use (&$config) {
$view = new Twig(BASE_DIR . 'resources/templates', [ $view = new Twig(BASE_DIR . 'resources/templates', [
'cache' => BASE_DIR . 'resources/cache', 'cache' => BASE_DIR . 'resources/cache',
'autoescape' => 'html', 'autoescape' => 'html',
'debug' => $config['displayErrorDetails'], 'debug' => $config['displayErrorDetails'],
'auto_reload' => $config['displayErrorDetails'], 'auto_reload' => $config['displayErrorDetails'],
]); ]);
// Instantiate and add Slim specific extension // Instantiate and add Slim specific extension
$router = $container->get('router'); $router = $container->get('router');
$uri = Uri::createFromEnvironment(new Environment($_SERVER)); $uri = Uri::createFromEnvironment(new Environment($_SERVER));
$view->addExtension(new Slim\Views\TwigExtension($router, $uri)); $view->addExtension(new Slim\Views\TwigExtension($router, $uri));
$view->getEnvironment()->addGlobal('config', $config); $view->getEnvironment()->addGlobal('config', $config);
$view->getEnvironment()->addGlobal('request', $container->get('request')); $view->getEnvironment()->addGlobal('request', $container->get('request'));
$view->getEnvironment()->addGlobal('alerts', $container->get('session')->getAlert()); $view->getEnvironment()->addGlobal('alerts', $container->get('session')->getAlert());
$view->getEnvironment()->addGlobal('session', $container->get('session')->all()); $view->getEnvironment()->addGlobal('session', $container->get('session')->all());
$view->getEnvironment()->addGlobal('current_lang', $container->get('lang')->getLang()); $view->getEnvironment()->addGlobal('current_lang', $container->get('lang')->getLang());
$view->getEnvironment()->addGlobal('PLATFORM_VERSION', PLATFORM_VERSION); $view->getEnvironment()->addGlobal('PLATFORM_VERSION', PLATFORM_VERSION);
$view->getEnvironment()->addFunction(new TwigFunction('route', 'route')); $view->getEnvironment()->addFunction(new TwigFunction('route', 'route'));
$view->getEnvironment()->addFunction(new TwigFunction('lang', 'lang')); $view->getEnvironment()->addFunction(new TwigFunction('lang', 'lang'));
$view->getEnvironment()->addFunction(new TwigFunction('urlFor', 'urlFor')); $view->getEnvironment()->addFunction(new TwigFunction('urlFor', 'urlFor'));
$view->getEnvironment()->addFunction(new TwigFunction('asset', 'asset')); $view->getEnvironment()->addFunction(new TwigFunction('asset', 'asset'));
$view->getEnvironment()->addFunction(new TwigFunction('mime2font', 'mime2font')); $view->getEnvironment()->addFunction(new TwigFunction('mime2font', 'mime2font'));
$view->getEnvironment()->addFunction(new TwigFunction('queryParams', 'queryParams')); $view->getEnvironment()->addFunction(new TwigFunction('queryParams', 'queryParams'));
$view->getEnvironment()->addFunction(new TwigFunction('isDisplayableImage', 'isDisplayableImage')); $view->getEnvironment()->addFunction(new TwigFunction('isDisplayableImage', 'isDisplayableImage'));
return $view; return $view;
}; };
$container['phpErrorHandler'] = function ($container) { $container['phpErrorHandler'] = function ($container) {
return function (Request $request, Response $response, Throwable $error) use (&$container) { return function (Request $request, Response $response, Throwable $error) use (&$container) {
$container->logger->critical('Fatal runtime error during app execution', ['exception' => $error]); $container->logger->critical('Fatal runtime error during app execution', ['exception' => $error]);
return $container->view->render($response->withStatus(500), 'errors/500.twig', ['exception' => $error]); return $container->view->render($response->withStatus(500), 'errors/500.twig', ['exception' => $error]);
}; };
}; };
$container['errorHandler'] = function ($container) { $container['errorHandler'] = function ($container) {
return function (Request $request, Response $response, Exception $exception) use (&$container) { return function (Request $request, Response $response, Exception $exception) use (&$container) {
if ($exception instanceof MaintenanceException) {
return $container->view->render($response->withStatus(503), 'errors/maintenance.twig');
}
if ($exception instanceof MaintenanceException) { if ($exception instanceof UnauthorizedException) {
return $container->view->render($response->withStatus(503), 'errors/maintenance.twig'); return $container->view->render($response->withStatus(403), 'errors/403.twig');
} }
if ($exception instanceof UnauthorizedException) { $container->logger->critical('Fatal exception during app execution', ['exception' => $exception]);
return $container->view->render($response->withStatus(403), 'errors/403.twig'); return $container->view->render($response->withStatus(500), 'errors/500.twig', ['exception' => $exception]);
} };
$container->logger->critical('Fatal exception during app execution', ['exception' => $exception]);
return $container->view->render($response->withStatus(500), 'errors/500.twig', ['exception' => $exception]);
};
}; };
$container['notAllowedHandler'] = function ($container) { $container['notAllowedHandler'] = function ($container) {
return function (Request $request, Response $response, $methods) use (&$container) { return function (Request $request, Response $response, $methods) use (&$container) {
return $container->view->render($response->withStatus(405)->withHeader('Allow', implode(', ', $methods)), 'errors/405.twig'); return $container->view->render($response->withStatus(405)->withHeader('Allow', implode(', ', $methods)), 'errors/405.twig');
}; };
}; };
$container['notFoundHandler'] = function ($container) { $container['notFoundHandler'] = function ($container) {
return function (Request $request, Response $response) use (&$container) { return function (Request $request, Response $response) use (&$container) {
$response->withStatus(404)->withHeader('Content-Type', 'text/html'); $response->withStatus(404)->withHeader('Content-Type', 'text/html');
return $container->view->render($response, 'errors/404.twig'); return $container->view->render($response, 'errors/404.twig');
}; };
}; };
$app = new App($container); $app = new App($container);
// Permanently redirect paths with a trailing slash to their non-trailing counterpart // Permanently redirect paths with a trailing slash to their non-trailing counterpart
$app->add(function (Request $request, Response $response, callable $next) { $app->add(function (Request $request, Response $response, callable $next) {
$uri = $request->getUri(); $uri = $request->getUri();
$path = $uri->getPath(); $path = $uri->getPath();
if ($path !== '/' && substr($path, -1) === '/') { if ($path !== '/' && substr($path, -1) === '/') {
$uri = $uri->withPath(substr($path, 0, -1)); $uri = $uri->withPath(substr($path, 0, -1));
if ($request->getMethod() === 'GET') { if ($request->getMethod() === 'GET') {
return $response->withRedirect((string)$uri, 301); return $response->withRedirect((string)$uri, 301);
} else { } else {
return $next($request->withUri($uri), $response); return $next($request->withUri($uri), $response);
} }
} }
return $next($request, $response); return $next($request, $response);
}); });
// Load the application routes // Load the application routes

View file

@ -1,14 +1,14 @@
<?php <?php
return [ return [
'base_url' => 'http://localhost', 'base_url' => 'http://localhost',
'db' => [ 'db' => [
'connection' => 'sqlite', 'connection' => 'sqlite',
'dsn' => 'resources/database/xbackbone.db', 'dsn' => 'resources/database/xbackbone.db',
'username' => null, 'username' => null,
'password' => null, 'password' => null,
], ],
'storage' => [ 'storage' => [
'driver' => 'local', 'driver' => 'local',
'path' => './storage', 'path' => './storage',
], ],
]; ];

View file

@ -26,308 +26,307 @@ define('PLATFORM_VERSION', json_decode(file_get_contents(__DIR__ . '/../composer
// default config // default config
$config = [ $config = [
'base_url' => str_replace('/install/', '', (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"), 'base_url' => str_replace('/install/', '', (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"),
'displayErrorDetails' => true, 'displayErrorDetails' => true,
'db' => [ 'db' => [
'connection' => 'sqlite', 'connection' => 'sqlite',
'dsn' => realpath(__DIR__ . '/../') . implode(DIRECTORY_SEPARATOR, ['resources', 'database', 'xbackbone.db']), 'dsn' => realpath(__DIR__ . '/../') . implode(DIRECTORY_SEPARATOR, ['resources', 'database', 'xbackbone.db']),
'username' => null, 'username' => null,
'password' => null, 'password' => null,
], ],
'storage' => [ 'storage' => [
'driver' => 'local', 'driver' => 'local',
'path' => realpath(__DIR__ . '/../') . DIRECTORY_SEPARATOR . 'storage', 'path' => realpath(__DIR__ . '/../') . DIRECTORY_SEPARATOR . 'storage',
], ],
]; ];
if (file_exists(__DIR__ . '/../config.php')) { if (file_exists(__DIR__ . '/../config.php')) {
$config = array_replace_recursive($config, require __DIR__ . '/../config.php'); $config = array_replace_recursive($config, require __DIR__ . '/../config.php');
} }
$container = new Container(['settings' => $config]); $container = new Container(['settings' => $config]);
$container['session'] = function ($container) { $container['session'] = function ($container) {
return new Session('xbackbone_session'); return new Session('xbackbone_session');
}; };
$container['view'] = function ($container) use (&$config) { $container['view'] = function ($container) use (&$config) {
$view = new Twig([__DIR__ . '/templates', __DIR__ . '/../resources/templates'], [ $view = new Twig([__DIR__ . '/templates', __DIR__ . '/../resources/templates'], [
'cache' => false, 'cache' => false,
'autoescape' => 'html', 'autoescape' => 'html',
'debug' => $config['displayErrorDetails'], 'debug' => $config['displayErrorDetails'],
'auto_reload' => $config['displayErrorDetails'], 'auto_reload' => $config['displayErrorDetails'],
]); ]);
// Instantiate and add Slim specific extension // Instantiate and add Slim specific extension
$router = $container->get('router'); $router = $container->get('router');
$uri = Uri::createFromEnvironment(new Environment($_SERVER)); $uri = Uri::createFromEnvironment(new Environment($_SERVER));
$view->addExtension(new Slim\Views\TwigExtension($router, $uri)); $view->addExtension(new Slim\Views\TwigExtension($router, $uri));
$view->getEnvironment()->addGlobal('config', $config); $view->getEnvironment()->addGlobal('config', $config);
$view->getEnvironment()->addGlobal('request', $container->get('request')); $view->getEnvironment()->addGlobal('request', $container->get('request'));
$view->getEnvironment()->addGlobal('alerts', $container->get('session')->getAlert()); $view->getEnvironment()->addGlobal('alerts', $container->get('session')->getAlert());
$view->getEnvironment()->addGlobal('session', $container->get('session')->all()); $view->getEnvironment()->addGlobal('session', $container->get('session')->all());
$view->getEnvironment()->addGlobal('PLATFORM_VERSION', PLATFORM_VERSION); $view->getEnvironment()->addGlobal('PLATFORM_VERSION', PLATFORM_VERSION);
return $view; return $view;
}; };
$container['storage'] = function ($container) use (&$config) { $container['storage'] = function ($container) use (&$config) {
switch ($config['storage']['driver']) {
case 'local':
return new Filesystem(new Local($config['storage']['path']));
case 's3':
$client = new S3Client([
'credentials' => [
'key' => $config['storage']['key'],
'secret' => $config['storage']['secret'],
],
'region' => $config['storage']['region'],
'version' => 'latest',
]);
switch ($config['storage']['driver']) { return new Filesystem(new AwsS3Adapter($client, $config['storage']['bucket'], $config['storage']['path']));
case 'local': case 'dropbox':
return new Filesystem(new Local($config['storage']['path'])); $client = new DropboxClient($config['storage']['token']);
case 's3': return new Filesystem(new DropboxAdapter($client), ['case_sensitive' => false]);
$client = new S3Client([ case 'ftp':
'credentials' => [ return new Filesystem(new FtpAdapter([
'key' => $config['storage']['key'], 'host' => $config['storage']['host'],
'secret' => $config['storage']['secret'], 'username' => $config['storage']['username'],
], 'password' => $config['storage']['password'],
'region' => $config['storage']['region'], 'port' => $config['storage']['port'],
'version' => 'latest', 'root' => $config['storage']['path'],
]); 'passive' => $config['storage']['passive'],
'ssl' => $config['storage']['ssl'],
return new Filesystem(new AwsS3Adapter($client, $config['storage']['bucket'], $config['storage']['path'])); 'timeout' => 30,
case 'dropbox': ]));
$client = new DropboxClient($config['storage']['token']); case 'google-cloud':
return new Filesystem(new DropboxAdapter($client), ['case_sensitive' => false]); $client = new StorageClient([
case 'ftp': 'projectId' => $config['storage']['project_id'],
return new Filesystem(new FtpAdapter([ 'keyFilePath' => $config['storage']['key_path'],
'host' => $config['storage']['host'], ]);
'username' => $config['storage']['username'], return new Filesystem(new GoogleStorageAdapter($client, $client->bucket($config['storage']['bucket'])));
'password' => $config['storage']['password'], default:
'port' => $config['storage']['port'], throw new InvalidArgumentException('The driver specified is not supported.');
'root' => $config['storage']['path'], }
'passive' => $config['storage']['passive'],
'ssl' => $config['storage']['ssl'],
'timeout' => 30,
]));
case 'google-cloud':
$client = new StorageClient([
'projectId' => $config['storage']['project_id'],
'keyFilePath' => $config['storage']['key_path'],
]);
return new Filesystem(new GoogleStorageAdapter($client, $client->bucket($config['storage']['bucket'])));
default:
throw new InvalidArgumentException('The driver specified is not supported.');
}
}; };
function migrate($config) { function migrate($config)
$firstMigrate = false; {
if ($config['db']['connection'] === 'sqlite' && !file_exists(__DIR__ . '/../' . $config['db']['dsn'])) { $firstMigrate = false;
touch(__DIR__ . '/../' . $config['db']['dsn']); if ($config['db']['connection'] === 'sqlite' && !file_exists(__DIR__ . '/../' . $config['db']['dsn'])) {
$firstMigrate = true; touch(__DIR__ . '/../' . $config['db']['dsn']);
} $firstMigrate = true;
}
try { try {
DB::doQuery('SELECT 1 FROM `migrations` LIMIT 1'); DB::doQuery('SELECT 1 FROM `migrations` LIMIT 1');
} catch (PDOException $exception) { } catch (PDOException $exception) {
$firstMigrate = true; $firstMigrate = true;
} }
if ($firstMigrate) { if ($firstMigrate) {
DB::raw()->exec(file_get_contents(__DIR__ . '/../resources/schemas/migrations.sql')); DB::raw()->exec(file_get_contents(__DIR__ . '/../resources/schemas/migrations.sql'));
} }
$files = glob(__DIR__ . '/../resources/schemas/' . DB::driver() . '/*.sql'); $files = glob(__DIR__ . '/../resources/schemas/' . DB::driver() . '/*.sql');
$names = array_map(function ($path) { $names = array_map(function ($path) {
return basename($path); return basename($path);
}, $files); }, $files);
$in = str_repeat('?, ', count($names) - 1) . '?'; $in = str_repeat('?, ', count($names) - 1) . '?';
$inMigrationsTable = DB::doQuery("SELECT * FROM `migrations` WHERE `name` IN ($in)", $names)->fetchAll(); $inMigrationsTable = DB::doQuery("SELECT * FROM `migrations` WHERE `name` IN ($in)", $names)->fetchAll();
foreach ($files as $file) { foreach ($files as $file) {
$continue = false;
$exists = false;
$continue = false; foreach ($inMigrationsTable as $migration) {
$exists = false; if (basename($file) === $migration->name && $migration->migrated) {
$continue = true;
break;
} elseif (basename($file) === $migration->name && !$migration->migrated) {
$exists = true;
break;
}
}
if ($continue) {
continue;
}
foreach ($inMigrationsTable as $migration) { $sql = file_get_contents($file);
if (basename($file) === $migration->name && $migration->migrated) { try {
$continue = true; DB::raw()->exec($sql);
break; if (!$exists) {
} else if (basename($file) === $migration->name && !$migration->migrated) { DB::doQuery('INSERT INTO `migrations` VALUES (?,?)', [basename($file), 1]);
$exists = true; } else {
break; DB::doQuery('UPDATE `migrations` SET `migrated`=? WHERE `name`=?', [1, basename($file)]);
} }
} } catch (PDOException $exception) {
if ($continue) continue; if (!$exists) {
DB::doQuery('INSERT INTO `migrations` VALUES (?,?)', [basename($file), 0]);
$sql = file_get_contents($file); }
try { throw $exception;
DB::raw()->exec($sql); }
if (!$exists) { }
DB::doQuery('INSERT INTO `migrations` VALUES (?,?)', [basename($file), 1]);
} else {
DB::doQuery('UPDATE `migrations` SET `migrated`=? WHERE `name`=?', [1, basename($file)]);
}
} catch (PDOException $exception) {
if (!$exists) {
DB::doQuery('INSERT INTO `migrations` VALUES (?,?)', [basename($file), 0]);
}
throw $exception;
}
}
} }
$app = new App($container); $app = new App($container);
$app->get('/', function (Request $request, Response $response) { $app->get('/', function (Request $request, Response $response) {
if (!extension_loaded('gd')) {
$this->session->alert('The required "gd" extension is not loaded.', 'danger');
}
if (!extension_loaded('gd')) { if (!extension_loaded('intl')) {
$this->session->alert('The required "gd" extension is not loaded.', 'danger'); $this->session->alert('The required "intl" extension is not loaded.', 'danger');
} }
if (!extension_loaded('intl')) { if (!extension_loaded('json')) {
$this->session->alert('The required "intl" extension is not loaded.', 'danger'); $this->session->alert('The required "json" extension is not loaded.', 'danger');
} }
if (!extension_loaded('json')) { if (!is_writable(__DIR__ . '/../resources/cache')) {
$this->session->alert('The required "json" extension is not loaded.', 'danger'); $this->session->alert('The cache folder is not writable (' . __DIR__ . '/../resources/cache' . ')', 'danger');
} }
if (!is_writable(__DIR__ . '/../resources/cache')) { if (!is_writable(__DIR__ . '/../resources/database')) {
$this->session->alert('The cache folder is not writable (' . __DIR__ . '/../resources/cache' . ')', 'danger'); $this->session->alert('The database folder is not writable (' . __DIR__ . '/../resources/database' . ')', 'danger');
} }
if (!is_writable(__DIR__ . '/../resources/database')) { if (!is_writable(__DIR__ . '/../resources/sessions')) {
$this->session->alert('The database folder is not writable (' . __DIR__ . '/../resources/database' . ')', 'danger'); $this->session->alert('The sessions folder is not writable (' . __DIR__ . '/../resources/sessions' . ')', 'danger');
} }
if (!is_writable(__DIR__ . '/../resources/sessions')) { $installed = file_exists(__DIR__ . '/../config.php');
$this->session->alert('The sessions folder is not writable (' . __DIR__ . '/../resources/sessions' . ')', 'danger');
}
$installed = file_exists(__DIR__ . '/../config.php'); return $this->view->render($response, 'install.twig', [
'installed' => $installed,
return $this->view->render($response, 'install.twig', [ ]);
'installed' => $installed,
]);
}); });
$app->post('/', function (Request $request, Response $response) use (&$config) { $app->post('/', function (Request $request, Response $response) use (&$config) {
// Check if there is a previous installation, if not, setup the config file // Check if there is a previous installation, if not, setup the config file
$installed = true; $installed = true;
if (!file_exists(__DIR__ . '/../config.php')) { if (!file_exists(__DIR__ . '/../config.php')) {
$installed = false; $installed = false;
// config file setup // config file setup
$config['base_url'] = $request->getParam('base_url'); $config['base_url'] = $request->getParam('base_url');
$config['storage']['driver'] = $request->getParam('storage_driver'); $config['storage']['driver'] = $request->getParam('storage_driver');
unset($config['displayErrorDetails']); unset($config['displayErrorDetails']);
$config['db']['connection'] = $request->getParam('connection'); $config['db']['connection'] = $request->getParam('connection');
$config['db']['dsn'] = $request->getParam('dsn'); $config['db']['dsn'] = $request->getParam('dsn');
$config['db']['username'] = $request->getParam('db_user'); $config['db']['username'] = $request->getParam('db_user');
$config['db']['password'] = $request->getParam('db_password'); $config['db']['password'] = $request->getParam('db_password');
// setup storage configuration // setup storage configuration
switch ($config['storage']['driver']) { switch ($config['storage']['driver']) {
case 's3': case 's3':
$config['storage']['key'] = $request->getParam('storage_key'); $config['storage']['key'] = $request->getParam('storage_key');
$config['storage']['secret'] = $request->getParam('storage_secret'); $config['storage']['secret'] = $request->getParam('storage_secret');
$config['storage']['region'] = $request->getParam('storage_region'); $config['storage']['region'] = $request->getParam('storage_region');
$config['storage']['bucket'] = $request->getParam('storage_bucket'); $config['storage']['bucket'] = $request->getParam('storage_bucket');
$config['storage']['path'] = $request->getParam('storage_path'); $config['storage']['path'] = $request->getParam('storage_path');
break; break;
case 'dropbox': case 'dropbox':
$config['storage']['token'] = $request->getParam('storage_token'); $config['storage']['token'] = $request->getParam('storage_token');
break; break;
case 'ftp': case 'ftp':
$config['storage']['host'] = $request->getParam('storage_host'); $config['storage']['host'] = $request->getParam('storage_host');
$config['storage']['username'] = $request->getParam('storage_username'); $config['storage']['username'] = $request->getParam('storage_username');
$config['storage']['password'] = $request->getParam('storage_password'); $config['storage']['password'] = $request->getParam('storage_password');
$config['storage']['port'] = $request->getParam('storage_port'); $config['storage']['port'] = $request->getParam('storage_port');
$config['storage']['path'] = $request->getParam('storage_path'); $config['storage']['path'] = $request->getParam('storage_path');
$config['storage']['passive'] = $request->getParam('storage_passive') === '1'; $config['storage']['passive'] = $request->getParam('storage_passive') === '1';
$config['storage']['ssl'] = $request->getParam('storage_ssl') === '1'; $config['storage']['ssl'] = $request->getParam('storage_ssl') === '1';
break; break;
case 'google-cloud': case 'google-cloud':
$config['storage']['project_id'] = $request->getParam('storage_project_id'); $config['storage']['project_id'] = $request->getParam('storage_project_id');
$config['storage']['key_path'] = $request->getParam('storage_key_path'); $config['storage']['key_path'] = $request->getParam('storage_key_path');
$config['storage']['bucket'] = $request->getParam('storage_bucket'); $config['storage']['bucket'] = $request->getParam('storage_bucket');
break; break;
case 'local': case 'local':
default: default:
$config['storage']['path'] = $request->getParam('storage_path'); $config['storage']['path'] = $request->getParam('storage_path');
break; break;
} }
// check if the storage is valid // check if the storage is valid
$storageTestFile = 'storage_test.xbackbone.txt'; $storageTestFile = 'storage_test.xbackbone.txt';
try { try {
try { try {
$success = $this->storage->write($storageTestFile, 'XBACKBONE_TEST_FILE'); $success = $this->storage->write($storageTestFile, 'XBACKBONE_TEST_FILE');
} catch (FileExistsException $fileExistsException) { } catch (FileExistsException $fileExistsException) {
$success = $this->storage->update($storageTestFile, 'XBACKBONE_TEST_FILE'); $success = $this->storage->update($storageTestFile, 'XBACKBONE_TEST_FILE');
} }
if (!$success) { if (!$success) {
throw new Exception('The storage is not writable.'); throw new Exception('The storage is not writable.');
} }
$this->storage->readAndDelete($storageTestFile); $this->storage->readAndDelete($storageTestFile);
} catch (Exception $e) { } catch (Exception $e) {
$this->session->alert("Storage setup error: {$e->getMessage()} [{$e->getCode()}]", 'danger'); $this->session->alert("Storage setup error: {$e->getMessage()} [{$e->getCode()}]", 'danger');
return redirect($response, '/install'); return redirect($response, '/install');
} }
$ret = file_put_contents(__DIR__ . '/../config.php', '<?php' . PHP_EOL . 'return ' . var_export($config, true) . ';'); $ret = file_put_contents(__DIR__ . '/../config.php', '<?php' . PHP_EOL . 'return ' . var_export($config, true) . ';');
if ($ret === false) { if ($ret === false) {
$this->session->alert('The config folder is not writable (' . __DIR__ . '/../config.php' . ')', 'danger'); $this->session->alert('The config folder is not writable (' . __DIR__ . '/../config.php' . ')', 'danger');
return redirect($response, '/install'); return redirect($response, '/install');
} }
} }
// if from older installations with no support of other than local driver // if from older installations with no support of other than local driver
// update the config // update the config
if ($installed && isset($config['storage_dir'])) { if ($installed && isset($config['storage_dir'])) {
$config['storage']['driver'] = 'local'; $config['storage']['driver'] = 'local';
$config['storage']['path'] = $config['storage_dir']; $config['storage']['path'] = $config['storage_dir'];
unset($config['storage_dir']); unset($config['storage_dir']);
} }
// Build the dns string and run the migrations // Build the dns string and run the migrations
try { try {
$dsn = $config['db']['connection'] === 'sqlite' ? __DIR__ . '/../' . $config['db']['dsn'] : $config['db']['dsn'];
DB::setDsn($config['db']['connection'] . ':' . $dsn, $config['db']['username'], $config['db']['password']);
$dsn = $config['db']['connection'] === 'sqlite' ? __DIR__ . '/../' . $config['db']['dsn'] : $config['db']['dsn']; migrate($config);
DB::setDsn($config['db']['connection'] . ':' . $dsn, $config['db']['username'], $config['db']['password']); } catch (PDOException $e) {
$this->session->alert("Cannot connect to the database: {$e->getMessage()} [{$e->getCode()}]", 'danger');
return redirect($response, '/install');
}
migrate($config); // if not installed, create the default admin account
} catch (PDOException $e) { if (!$installed) {
$this->session->alert("Cannot connect to the database: {$e->getMessage()} [{$e->getCode()}]", 'danger'); DB::doQuery("INSERT INTO `users` (`email`, `username`, `password`, `is_admin`, `user_code`) VALUES (?, 'admin', ?, 1, ?)", [$request->getParam('email'), password_hash($request->getParam('password'), PASSWORD_DEFAULT), humanRandomString(5)]);
return redirect($response, '/install'); }
}
// if not installed, create the default admin account // post install cleanup
if (!$installed) { cleanDirectory(__DIR__ . '/../resources/cache');
DB::doQuery("INSERT INTO `users` (`email`, `username`, `password`, `is_admin`, `user_code`) VALUES (?, 'admin', ?, 1, ?)", [$request->getParam('email'), password_hash($request->getParam('password'), PASSWORD_DEFAULT), humanRandomString(5)]); cleanDirectory(__DIR__ . '/../resources/sessions');
}
// post install cleanup removeDirectory(__DIR__ . '/../install');
cleanDirectory(__DIR__ . '/../resources/cache');
cleanDirectory(__DIR__ . '/../resources/sessions');
removeDirectory(__DIR__ . '/../install'); // if is upgrading and existing installation, put it out maintenance
if ($installed) {
unset($config['maintenance']);
// if is upgrading and existing installation, put it out maintenance $ret = file_put_contents(__DIR__ . '/../config.php', '<?php' . PHP_EOL . 'return ' . var_export($config, true) . ';');
if ($installed) { if ($ret === false) {
unset($config['maintenance']); $this->session->alert('The config folder is not writable (' . __DIR__ . '/../config.php' . ')', 'danger');
return redirect($response, '/install');
}
}
$ret = file_put_contents(__DIR__ . '/../config.php', '<?php' . PHP_EOL . 'return ' . var_export($config, true) . ';'); // Installed successfully, destroy the installer session
if ($ret === false) { session_destroy();
$this->session->alert('The config folder is not writable (' . __DIR__ . '/../config.php' . ')', 'danger'); return $response->withRedirect("{$config['base_url']}/?afterInstall=true");
return redirect($response, '/install');
}
}
// Installed successfully, destroy the installer session
session_destroy();
return $response->withRedirect("{$config['base_url']}/?afterInstall=true");
}); });
$app->run(); $app->run();