Upgrade to slim 4

This commit is contained in:
Sergio Brighenti 2019-11-13 00:13:23 +01:00
parent f898f4fbd4
commit d8df60040a
26 changed files with 2607 additions and 1955 deletions

View file

@ -4,90 +4,92 @@ namespace App\Controllers;
use League\Flysystem\FileNotFoundException;
use Slim\Http\Request;
use Slim\Http\Response;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class AdminController extends Controller
{
/**
* @param Request $request
* @param Response $response
* @return Response
* @throws FileNotFoundException
*/
public function system(Request $request, Response $response): Response
{
$usersCount = $this->database->query('SELECT COUNT(*) AS `count` FROM `users`')->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;
/**
* @param Response $response
* @return Response
* @throws FileNotFoundException
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function system(Response $response): Response
{
$usersCount = $this->database->query('SELECT COUNT(*) AS `count` FROM `users`')->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;
$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;
foreach ($medias as $media) {
$totalSize += $filesystem->getSize($media->storage_path);
}
$filesystem = $this->storage;
foreach ($medias as $media) {
$totalSize += $filesystem->getSize($media->storage_path);
}
return $this->view->render($response, 'dashboard/system.twig', [
'usersCount' => $usersCount,
'mediasCount' => $mediasCount,
'orphanFilesCount' => $orphanFilesCount,
'totalSize' => humanFileSize($totalSize),
'post_max_size' => ini_get('post_max_size'),
'upload_max_filesize' => ini_get('upload_max_filesize'),
'installed_lang' => $this->lang->getList(),
]);
}
return view()->render($response, 'dashboard/system.twig', [
'usersCount' => $usersCount,
'mediasCount' => $mediasCount,
'orphanFilesCount' => $orphanFilesCount,
'totalSize' => humanFileSize($totalSize),
'post_max_size' => ini_get('post_max_size'),
'upload_max_filesize' => ini_get('upload_max_filesize'),
'installed_lang' => $this->lang->getList(),
]);
}
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function deleteOrphanFiles(Request $request, Response $response): Response
{
$orphans = $this->database->query('SELECT * FROM `uploads` WHERE `user_id` IS NULL')->fetchAll();
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function deleteOrphanFiles(Response $response): Response
{
$orphans = $this->database->query('SELECT * FROM `uploads` WHERE `user_id` IS NULL')->fetchAll();
$filesystem = $this->storage;
$deleted = 0;
$filesystem = $this->storage;
$deleted = 0;
foreach ($orphans as $orphan) {
try {
$filesystem->delete($orphan->storage_path);
$deleted++;
} catch (FileNotFoundException $e) {
}
}
foreach ($orphans as $orphan) {
try {
$filesystem->delete($orphan->storage_path);
$deleted++;
} 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, route('system'));
}
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function applyLang(Request $request, Response $response): Response
{
$config = require BASE_DIR . 'config.php';
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function applyLang(Request $request, Response $response): Response
{
$config = require BASE_DIR.'config.php';
if ($request->getParam('lang') !== 'auto') {
$config['lang'] = $request->getParam('lang');
} else {
unset($config['lang']);
}
if (param($request,'lang') !== 'auto') {
$config['lang'] = param($request,'lang');
} else {
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', [param($request, 'lang')]));
return redirect($response, 'system');
}
return redirect($response, route('system'));
}
}

View file

@ -5,63 +5,67 @@ namespace App\Controllers;
use App\Database\DB;
use App\Web\Lang;
use App\Web\Session;
use DI\Container;
use DI\DependencyException;
use DI\NotFoundException;
use League\Flysystem\FileNotFoundException;
use League\Flysystem\Filesystem;
use Monolog\Logger;
use Slim\Container;
use Twig\Environment;
/**
* @property Session|null session
* @property mixed|null view
* @property Environment view
* @property DB|null database
* @property Logger|null logger
* @property Filesystem|null storage
* @property Lang lang
* @property array settings
* @property array config
*/
abstract class Controller
{
/** @var Container */
protected $container;
/** @var Container */
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
}
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* @param $name
* @return mixed|null
* @throws \Interop\Container\Exception\ContainerException
*/
public function __get($name)
{
if ($this->container->has($name)) {
return $this->container->get($name);
}
return null;
}
/**
* @param $name
* @return mixed|null
* @throws DependencyException
* @throws NotFoundException
*/
public function __get($name)
{
if ($this->container->has($name)) {
return $this->container->get($name);
}
return null;
}
/**
* @param $id
* @return int
*/
protected function getUsedSpaceByUser($id): int
{
$medias = $this->database->query('SELECT `uploads`.`storage_path` FROM `uploads` WHERE `user_id` = ?', $id);
/**
* @param $id
* @return int
*/
protected function getUsedSpaceByUser($id): int
{
$medias = $this->database->query('SELECT `uploads`.`storage_path` FROM `uploads` WHERE `user_id` = ?', $id);
$totalSize = 0;
$totalSize = 0;
$filesystem = $this->storage;
foreach ($medias as $media) {
try {
$totalSize += $filesystem->getSize($media->storage_path);
} catch (FileNotFoundException $e) {
$this->logger->error('Error calculating file size', ['exception' => $e]);
}
}
$filesystem = $this->storage;
foreach ($medias as $media) {
try {
$totalSize += $filesystem->getSize($media->storage_path);
} catch (FileNotFoundException $e) {
$this->logger->error('Error calculating file size', ['exception' => $e]);
}
}
return $totalSize;
}
return $totalSize;
}
}

View file

@ -3,78 +3,79 @@
namespace App\Controllers;
use App\Database\Queries\MediaQuery;
use Slim\Http\Request;
use Slim\Http\Response;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class DashboardController extends Controller
{
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function redirects(Request $request, Response $response): Response
{
if ($request->getParam('afterInstall') !== null && !is_dir(BASE_DIR . 'install')) {
$this->session->alert(lang('installed'), 'success');
}
/**
* @Inject
* @param Request $request
* @param Response $response
* @return Response
*/
public function redirects(Request $request, Response $response): Response
{
if (param($request, 'afterInstall') !== null && !is_dir(BASE_DIR.'install')) {
$this->session->alert(lang('installed'), 'success');
}
return redirect($response, 'home');
}
return redirect($response, route('home'));
}
/**
* @param Request $request
* @param Response $response
* @param $args
* @return Response
*/
public function home(Request $request, Response $response, $args): Response
{
$page = isset($args['page']) ? (int)$args['page'] : 0;
$page = max(0, --$page);
/**
* @param Request $request
* @param Response $response
* @param int|null $page
* @return Response
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function home(Request $request, Response $response, int $page = 0): Response
{
$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')) {
case 'size':
$order = MediaQuery::ORDER_SIZE;
break;
case 'name':
$order = MediaQuery::ORDER_NAME;
break;
default:
case 'time':
$order = MediaQuery::ORDER_TIME;
break;
}
switch (param($request, 'sort', 'time')) {
case 'size':
$order = MediaQuery::ORDER_SIZE;
break;
case 'name':
$order = MediaQuery::ORDER_NAME;
break;
default:
case 'time':
$order = MediaQuery::ORDER_TIME;
break;
}
$query->orderBy($order, $request->getParam('order', 'DESC'))
->withUserId($this->session->get('user_id'))
->search($request->getParam('search', null))
->run($page);
$query->orderBy($order, param($request, 'order', 'DESC'))
->withUserId($this->session->get('user_id'))
->search(param($request, 'search', null))
->run($page);
return $this->view->render(
$response,
($this->session->get('admin', false) && $this->session->get('gallery_view', true)) ? 'dashboard/admin.twig' : 'dashboard/home.twig',
[
'medias' => $query->getMedia(),
'next' => $page < floor($query->getPages()),
'previous' => $page >= 1,
'current_page' => ++$page,
]
);
}
return view()->render(
$response,
($this->session->get('admin', false) && $this->session->get('gallery_view', true)) ? 'dashboard/admin.twig' : 'dashboard/home.twig',
[
'medias' => $query->getMedia(),
'next' => $page < floor($query->getPages()),
'previous' => $page >= 1,
'current_page' => ++$page,
]
);
}
/**
* @param Request $request
* @param Response $response
* @param $args
* @return Response
*/
public function switchView(Request $request, Response $response, $args): Response
{
$this->session->set('gallery_view', !$this->session->get('gallery_view', true));
return redirect($response, 'home');
}
/**
* @param Response $response
* @return Response
*/
public function switchView(Response $response): Response
{
$this->session->set('gallery_view', !$this->session->get('gallery_view', true));
return redirect($response, route('home'));
}
}

View file

@ -3,77 +3,78 @@
namespace App\Controllers;
use Slim\Http\Request;
use Slim\Http\Response;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class LoginController extends Controller
{
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function show(Request $request, Response $response): Response
{
if ($this->session->get('logged', false)) {
return redirect($response, 'home');
}
return $this->view->render($response, 'auth/login.twig');
}
/**
* @param Response $response
* @return Response
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function show(Response $response): Response
{
if ($this->session->get('logged', false)) {
return redirect($response, route('home'));
}
return view()->render($response, 'auth/login.twig');
}
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function login(Request $request, Response $response): Response
{
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function login(Request $request, Response $response): Response
{
$username = param($request, 'username');
$result = $this->database->query('SELECT `id`, `email`, `username`, `password`,`is_admin`, `active` FROM `users` WHERE `username` = ? OR `email` = ? LIMIT 1', [$username, $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(param($request, 'password'), $result->password)) {
$this->session->alert(lang('bad_login'), 'danger');
return redirect($response, route('login'));
}
if (!$result || !password_verify($request->getParam('password'), $result->password)) {
$this->session->alert(lang('bad_login'), 'danger');
return redirect($response, 'login');
}
if (isset($this->config['maintenance']) && $this->config['maintenance'] && !$result->is_admin) {
$this->session->alert(lang('maintenance_in_progress'), 'info');
return redirect($response, route('login'));
}
if (isset($this->settings['maintenance']) && $this->settings['maintenance'] && !$result->is_admin) {
$this->session->alert(lang('maintenance_in_progress'), 'info');
return redirect($response, 'login');
}
if (!$result->active) {
$this->session->alert(lang('account_disabled'), 'danger');
return redirect($response, route('login'));
}
if (!$result->active) {
$this->session->alert(lang('account_disabled'), 'danger');
return redirect($response, 'login');
}
$this->session->set('logged', true);
$this->session->set('user_id', $result->id);
$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->set('user_id', $result->id);
$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');
$this->logger->info("User $result->username logged in.");
$this->session->alert(lang('welcome', [$result->username]), 'info');
$this->logger->info("User $result->username logged in.");
if ($this->session->has('redirectTo')) {
return redirect($response, $this->session->get('redirectTo'));
}
if ($this->session->has('redirectTo')) {
return $response->withRedirect($this->session->get('redirectTo'));
}
return redirect($response, route('home'));
}
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 Response $response
* @return Response
*/
public function logout(Response $response): Response
{
$this->session->clear();
$this->session->set('logged', false);
$this->session->alert(lang('goodbye'), 'warning');
return redirect($response, route('login.show'));
}
}

View file

@ -2,40 +2,42 @@
namespace App\Controllers;
use Slim\Http\Request;
use Slim\Http\Response;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class ThemeController extends Controller
{
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function getThemes(Request $request, Response $response): Response
{
$apiJson = json_decode(file_get_contents('https://bootswatch.com/api/4.json'));
/**
* @param Response $response
* @return Response
*/
public function getThemes(Response $response): Response
{
$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';
foreach ($apiJson->themes as $theme) {
$out["{$theme->name} - {$theme->description}"] = $theme->cssMin;
}
$out['Default - Bootstrap 4 default theme'] = 'https://bootswatch.com/_vendor/bootstrap/dist/css/bootstrap.min.css';
foreach ($apiJson->themes as $theme) {
$out["{$theme->name} - {$theme->description}"] = $theme->cssMin;
}
return $response->withJson($out);
}
return json($response, $out);
}
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function applyTheme(Request $request, Response $response): Response
{
if (!is_writable(BASE_DIR.'static/bootstrap/css/bootstrap.min.css')) {
$this->session->alert(lang('cannot_write_file'), 'danger');
return redirect($response, route('system'));
}
public function applyTheme(Request $request, Response $response): Response
{
if (!is_writable(BASE_DIR . 'static/bootstrap/css/bootstrap.min.css')) {
$this->session->alert(lang('cannot_write_file'), 'danger');
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(param($request, 'css')));
return redirect($response, route('system'));
}
}

View file

@ -3,8 +3,9 @@
namespace App\Controllers;
use Slim\Http\Request;
use Slim\Http\Response;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use RuntimeException;
use ZipArchive;
class UpgradeController extends Controller
@ -12,39 +13,38 @@ class UpgradeController extends Controller
const GITHUB_SOURCE_API = 'https://api.github.com/repos/SergiX44/XBackBone/releases';
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function upgrade(Request $request, Response $response): Response
public function upgrade(Response $response): Response
{
if (!is_writable(BASE_DIR)) {
$this->session->alert(lang('path_not_writable', BASE_DIR), 'warning');
return redirect($response, 'system');
return redirect($response, route('system'));
}
try {
$json = $this->getApiJson();
} catch (\RuntimeException $e) {
} catch (RuntimeException $e) {
$this->session->alert($e->getMessage(), 'danger');
return redirect($response, 'system');
return redirect($response, route('system'));
}
if (version_compare($json[0]->tag_name, PLATFORM_VERSION, '<=')) {
$this->session->alert(lang('already_latest_version'), 'warning');
return redirect($response, 'system');
return redirect($response, route('system'));
}
$tmpFile = sys_get_temp_dir().DIRECTORY_SEPARATOR.'xbackbone_update.zip';
if (file_put_contents($tmpFile, file_get_contents($json[0]->assets[0]->browser_download_url)) === false) {
$this->session->alert(lang('cannot_retrieve_file'), 'danger');
return redirect($response, 'system');
return redirect($response, route('system'));
};
if (filesize($tmpFile) !== $json[0]->assets[0]->size) {
$this->session->alert(lang('file_size_no_match'), 'danger');
return redirect($response, 'system');
return redirect($response, route('system'));
}
$config = require BASE_DIR.'config.php';
@ -85,7 +85,7 @@ class UpgradeController extends Controller
$updateZip->close();
unlink($tmpFile);
return redirect($response, '/install');
return redirect($response, urlFor('/install'));
}
/**
@ -101,7 +101,7 @@ class UpgradeController extends Controller
'upgrade' => false,
];
$acceptPrerelease = $request->getParam('prerelease', 'false') === 'true';
$acceptPrerelease = param($request, 'prerelease', 'false') === 'true';
try {
$json = $this->getApiJson();
@ -120,11 +120,12 @@ class UpgradeController extends Controller
break;
}
}
} catch (\RuntimeException $e) {
} catch (RuntimeException $e) {
$jsonResponse['status'] = 'ERROR';
$jsonResponse['message'] = $e->getMessage();
}
return $response->withJson($jsonResponse);
return json($response, $jsonResponse);
}
protected function getApiJson()
@ -142,7 +143,7 @@ class UpgradeController extends Controller
$data = @file_get_contents(self::GITHUB_SOURCE_API, false, stream_context_create($opts));
if ($data === false) {
throw new \RuntimeException('Cannot contact the Github API. Try again.');
throw new RuntimeException('Cannot contact the Github API. Try again.');
}
return json_decode($data);

View file

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

View file

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

View file

@ -0,0 +1,14 @@
<?php
namespace App\Exception\Handlers;
use Slim\Handlers\ErrorHandler;
class AppErrorHandler extends ErrorHandler
{
protected function logError(string $error): void
{
resolve('logger')->critical($error);
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace App\Exception\Handlers\Renderers;
use App\Exceptions\UnderMaintenanceException;
use Slim\Exception\HttpForbiddenException;
use Slim\Exception\HttpMethodNotAllowedException;
use Slim\Exception\HttpNotFoundException;
use Slim\Exception\HttpUnauthorizedException;
use Slim\Interfaces\ErrorRendererInterface;
use Throwable;
class HtmlErrorRenderer implements ErrorRendererInterface
{
/**
* @param Throwable $exception
* @param bool $displayErrorDetails
* @return string
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function __invoke(Throwable $exception, bool $displayErrorDetails): string
{
if ($exception instanceof UnderMaintenanceException) {
return view()->string( 'errors/maintenance.twig');
}
if ($exception instanceof HttpUnauthorizedException || $exception instanceof HttpForbiddenException) {
return view()->string( 'errors/403.twig');
}
if ($exception instanceof HttpMethodNotAllowedException) {
return view()->string( 'errors/405.twig');
}
if ($exception instanceof HttpNotFoundException) {
return view()->string( 'errors/404.twig');
}
return view()->string('errors/500.twig', ['exception' => $displayErrorDetails ? $exception : null]);
}
}

View file

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

View file

@ -1,15 +0,0 @@
<?php
namespace App\Exceptions;
use Exception;
use Throwable;
class UnauthorizedException extends Exception
{
public function __construct(string $message = 'Forbidden', int $code = 403, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace App\Exceptions;
use Slim\Exception\HttpSpecializedException;
class UnderMaintenanceException extends HttpSpecializedException
{
protected $code = 503;
protected $message = 'Platform Under Maintenance.';
protected $title = '503 Service Unavailable';
protected $description = 'We\'ll be back very soon! :)';
}

View file

@ -2,27 +2,28 @@
namespace App\Middleware;
use App\Exceptions\UnauthorizedException;
use Slim\Http\Request;
use Slim\Http\Response;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Exception\HttpUnauthorizedException;
class AdminMiddleware extends Middleware
{
/**
* @param Request $request
* @param Response $response
* @param callable $next
* @return Response
* @throws UnauthorizedException
*/
public function __invoke(Request $request, Response $response, callable $next)
/**
* @param Request $request
* @param RequestHandler $handler
* @return Response
* @throws HttpUnauthorizedException
*/
public function __invoke(Request $request, RequestHandler $handler): ResponseInterface
{
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);
throw new UnauthorizedException();
throw new HttpUnauthorizedException($request);
}
return $next($request, $response);
return $handler->handle($request);
}
}

View file

@ -2,33 +2,34 @@
namespace App\Middleware;
use Slim\Http\Request;
use Slim\Http\Response;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
class AuthMiddleware extends Middleware
{
/**
* @param Request $request
* @param Response $response
* @param callable $next
* @return Response
*/
public function __invoke(Request $request, Response $response, callable $next)
{
if (!$this->session->get('logged', false)) {
$this->session->set('redirectTo', (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
return redirect($response, 'login.show');
}
/**
* @param Request $request
* @param RequestHandler $handler
* @return ResponseInterface
*/
public function __invoke(Request $request, RequestHandler $handler): ResponseInterface
{
if (!$this->session->get('logged', false)) {
$this->session->set('redirectTo', (string)$request->getUri());
return redirect(new Response(), route('login.show'));
}
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->set('logged', false);
$this->session->set('redirectTo', (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
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) {
$this->session->alert('Your account is not active anymore.', 'danger');
$this->session->set('logged', false);
return redirect(new Response(), route('login.show'));
}
return $next($request, $response);
}
return $handler->handle($request);
}
}

View file

@ -2,25 +2,26 @@
namespace App\Middleware;
use App\Exceptions\MaintenanceException;
use Slim\Http\Request;
use Slim\Http\Response;
use App\Exceptions\UnderMaintenanceException;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
class CheckForMaintenanceMiddleware extends Middleware
{
/**
* @param Request $request
* @param Response $response
* @param callable $next
* @return Response
* @throws MaintenanceException
*/
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) {
throw new MaintenanceException();
}
/**
* @param Request $request
* @param RequestHandler $handler
* @return Response
* @throws UnderMaintenanceException
*/
public function __invoke(Request $request, RequestHandler $handler): Response
{
if (isset($this->config['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 UnderMaintenanceException($request);
}
return $next($request, $response);
}
$response = $handler->handle($request);
return $response;
}
}

View file

@ -2,37 +2,40 @@
namespace App\Middleware;
use Slim\Container;
use Slim\Http\Request;
use Slim\Http\Response;
use DI\Container;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
abstract class Middleware
{
/** @var Container */
protected $container;
/** @var Container */
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
}
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* @param $name
* @return mixed|null
* @throws \Interop\Container\Exception\ContainerException
*/
public function __get($name)
{
if ($this->container->has($name)) {
return $this->container->get($name);
}
return null;
}
/**
* @param $name
* @return mixed|null
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
public function __get($name)
{
if ($this->container->has($name)) {
return $this->container->get($name);
}
return null;
}
/**
* @param Request $request
* @param Response $response
* @param callable $next
*/
public abstract function __invoke(Request $request, Response $response, callable $next);
/**
* @param Request $request
* @param RequestHandler $handler
* @return Response
*/
public abstract function __invoke(Request $request, RequestHandler $handler);
}

100
app/Web/View.php Normal file
View file

@ -0,0 +1,100 @@
<?php
namespace App\Web;
use DI\Container;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Factory\ServerRequestCreatorFactory;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFunction;
class View
{
/**
* @var Container
*/
private $container;
/**
* @var Environment
*/
private $twig;
/**
* View constructor.
* @param Container $container
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
public function __construct(Container $container)
{
$this->container = $container;
$config = $container->get('config');
$loader = new FilesystemLoader(BASE_DIR.'resources/templates');
$twig = new Environment($loader, [
'cache' => BASE_DIR.'resources/cache/twig',
'autoescape' => 'html',
'debug' => $config['debug'],
'auto_reload' => $config['debug'],
]);
$serverRequestCreator = ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();
$twig->addGlobal('config', $config);
$twig->addGlobal('request', $request);
$twig->addGlobal('alerts', $container->get('session')->getAlert());
$twig->addGlobal('session', $container->get('session')->all());
$twig->addGlobal('current_lang', $container->get('lang')->getLang());
$twig->addGlobal('PLATFORM_VERSION', PLATFORM_VERSION);
$twig->addFunction(new TwigFunction('route', 'route'));
$twig->addFunction(new TwigFunction('lang', 'lang'));
$twig->addFunction(new TwigFunction('urlFor', 'urlFor'));
$twig->addFunction(new TwigFunction('asset', 'asset'));
$twig->addFunction(new TwigFunction('mime2font', 'mime2font'));
$twig->addFunction(new TwigFunction('queryParams', 'queryParams'));
$twig->addFunction(new TwigFunction('isDisplayableImage', 'isDisplayableImage'));
$this->twig = $twig;
}
/**
* @param Response $response
* @param string $view
* @param array|null $parameters
* @return Response
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function render(Response $response, string $view, ?array $parameters = [])
{
$body = $this->twig->render($view, $parameters);
$response->getBody()->write($body);
return $response;
}
/**
* @param string $view
* @param array|null $parameters
* @return string
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function string(string $view, ?array $parameters = [])
{
return $this->twig->render($view, $parameters);
}
}

View file

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

View file

@ -10,59 +10,61 @@ use App\Controllers\UserController;
use App\Middleware\AdminMiddleware;
use App\Middleware\AuthMiddleware;
use App\Middleware\CheckForMaintenanceMiddleware;
use Slim\Routing\RouteCollectorProxy;
$app->group('', function () {
$this->get('/home[/page/{page}]', DashboardController::class . ':home')->setName('home');
global $app;
$app->group('', function (RouteCollectorProxy $group) {
$group->get('/home[/page/{page}]', [DashboardController::class, 'home'])->setName('home');
$this->group('', function () {
$this->get('/home/switchView', DashboardController::class . ':switchView')->setName('switchView');
$group->group('', function (RouteCollectorProxy $group) {
$group->get('/home/switchView', [DashboardController::class, 'switchView'])->setName('switchView');
$this->get('/system/deleteOrphanFiles', AdminController::class . ':deleteOrphanFiles')->setName('system.deleteOrphanFiles');
$group->get('/system/deleteOrphanFiles', [AdminController::class, 'deleteOrphanFiles'])->setName('system.deleteOrphanFiles');
$this->get('/system/themes', ThemeController::class . ':getThemes')->setName('theme');
$this->post('/system/theme/apply', ThemeController::class . ':applyTheme')->setName('theme.apply');
$group->get('/system/themes', [ThemeController::class, 'getThemes'])->setName('theme');
$group->post('/system/theme/apply', [ThemeController::class, 'applyTheme'])->setName('theme.apply');
$this->post('/system/lang/apply', AdminController::class . ':applyLang')->setName('lang.apply');
$group->post('/system/lang/apply', [AdminController::class, 'applyLang'])->setName('lang.apply');
$this->post('/system/upgrade', UpgradeController::class . ':upgrade')->setName('system.upgrade');
$this->get('/system/checkForUpdates', UpgradeController::class . ':checkForUpdates')->setName('system.checkForUpdates');
$group->post('/system/upgrade', [UpgradeController::class, 'upgrade'])->setName('system.upgrade');
$group->get('/system/checkForUpdates', [UpgradeController::class, 'checkForUpdates'])->setName('system.checkForUpdates');
$this->get('/system', AdminController::class . ':system')->setName('system');
$group->get('/system', [AdminController::class, 'system'])->setName('system');
$this->get('/users[/page/{page}]', UserController::class . ':index')->setName('user.index');
})->add(AdminMiddleware::class);
$group->get('/users[/page/{page}]', [UserController::class, 'index'])->setName('user.index');
})->add(AdminMiddleware::class);
$this->group('/user', function () {
$group->group('/user', function (RouteCollectorProxy $group) {
$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);
$group->get('/create', [UserController::class, 'create'])->setName('user.create');
$group->post('/create', [UserController::class, 'store'])->setName('user.store');
$group->get('/{id}/edit', [UserController::class, 'edit'])->setName('user.edit');
$group->post('/{id}', [UserController::class, 'update'])->setName('user.update');
$group->get('/{id}/delete', [UserController::class, 'delete'])->setName('user.delete');
})->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');
$group->get('/profile', [UserController::class, 'profile'])->setName('profile');
$group->post('/profile/{id}', [UserController::class, 'profileEdit'])->setName('profile.update');
$group->post('/user/{id}/refreshToken', [UserController::class, 'refreshToken'])->setName('refreshToken');
$group->get('/user/{id}/config/sharex', [UserController::class, 'getShareXconfigFile'])->setName('config.sharex');
$group->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');
$group->post('/upload/{id}/publish', [UploadController::class, 'togglePublish'])->setName('upload.publish');
$group->post('/upload/{id}/unpublish', [UploadController::class, 'togglePublish'])->setName('upload.unpublish');
$group->get('/upload/{id}/raw', [UploadController::class, 'getRawById'])->add(AdminMiddleware::class)->setName('upload.raw');
$group->post('/upload/{id}/delete', [UploadController::class, 'delete'])->setName('upload.delete');
})->add(App\Middleware\CheckForMaintenanceMiddleware::class)->add(AuthMiddleware::class);
$app->get('/', DashboardController::class . ':redirects')->setName('root');
$app->get('/login', LoginController::class . ':show')->setName('login.show');
$app->post('/login', LoginController::class . ':login')->setName('login');
$app->map(['GET', 'POST'], '/logout', LoginController::class . ':logout')->setName('logout');
$app->get('/', [DashboardController::class, 'redirects'])->setName('root');
$app->get('/login', [LoginController::class, 'show'])->setName('login.show');
$app->post('/login', [LoginController::class, 'login'])->setName('login');
$app->map(['GET', 'POST'], '/logout', [LoginController::class, 'logout'])->setName('logout');
$app->post('/upload', UploadController::class . ':upload')->setName('upload');
$app->post('/upload', [UploadController::class, 'upload'])->setName('upload');
$app->get('/{userCode}/{mediaCode}', UploadController::class . ':show')->setName('public');
$app->get('/{userCode}/{mediaCode}/delete/{token}', UploadController::class . ':show')->setName('public.delete.show')->add(CheckForMaintenanceMiddleware::class);
$app->post('/{userCode}/{mediaCode}/delete/{token}', UploadController::class . ':deleteByToken')->setName('public.delete')->add(CheckForMaintenanceMiddleware::class);
$app->get('/{userCode}/{mediaCode}/raw', UploadController::class . ':showRaw')->setName('public.raw')->setOutputBuffering(false);
$app->get('/{userCode}/{mediaCode}/download', UploadController::class . ':download')->setName('public.download')->setOutputBuffering(false);
$app->get('/{userCode}/{mediaCode}', [UploadController::class, 'show'])->setName('public');
$app->get('/{userCode}/{mediaCode}/delete/{token}', [UploadController::class, 'show'])->setName('public.delete.show')->add(CheckForMaintenanceMiddleware::class);
$app->post('/{userCode}/{mediaCode}/delete/{token}', [UploadController::class, 'deleteByToken'])->setName('public.delete')->add(CheckForMaintenanceMiddleware::class);
$app->get('/{userCode}/{mediaCode}/raw', [UploadController::class, 'showRaw'])->setName('public.raw');
$app->get('/{userCode}/{mediaCode}/download', [UploadController::class, 'download'])->setName('public.download');

View file

@ -1,12 +1,18 @@
<?php
use App\Database\DB;
use App\Exceptions\MaintenanceException;
use App\Exceptions\UnauthorizedException;
use App\Exception\Handlers\AppErrorHandler;
use App\Exception\Handlers\Renderers\HtmlErrorRenderer;
use App\Web\Lang;
use App\Web\Session;
use App\Web\View;
use Aws\S3\S3Client;
use DI\Bridge\Slim\Bridge;
use DI\ContainerBuilder;
use Google\Cloud\Storage\StorageClient;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use League\Flysystem\Adapter\Ftp as FtpAdapter;
use League\Flysystem\Adapter\Local;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
@ -14,212 +20,167 @@ use League\Flysystem\Filesystem;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Slim\App;
use Slim\Container;
use Slim\Http\Environment;
use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Http\Uri;
use Slim\Views\Twig;
use Psr\Container\ContainerInterface as Container;
use Spatie\Dropbox\Client as DropboxClient;
use Spatie\FlysystemDropbox\DropboxAdapter;
use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter;
use Twig\TwigFunction;
use function DI\factory;
use function DI\value;
if (!file_exists('config.php') && is_dir('install/')) {
header('Location: ./install/');
exit();
} else if (!file_exists('config.php') && !is_dir('install/')) {
exit('Cannot find the config file.');
header('Location: ./install/');
exit();
} else {
if (!file_exists('config.php') && !is_dir('install/')) {
exit('Cannot find the config file.');
}
}
// Load the config
$config = array_replace_recursive([
'app_name' => 'XBackBone',
'base_url' => isset($_SERVER['HTTPS']) ? 'https://' . $_SERVER['HTTP_HOST'] : 'http://' . $_SERVER['HTTP_HOST'],
'displayErrorDetails' => false,
'maintenance' => false,
'db' => [
'connection' => 'sqlite',
'dsn' => BASE_DIR . 'resources/database/xbackbone.db',
'username' => null,
'password' => null,
],
'storage' => [
'driver' => 'local',
'path' => realpath(__DIR__ . '/') . DIRECTORY_SEPARATOR . 'storage',
],
], require BASE_DIR . 'config.php');
'app_name' => 'XBackBone',
'base_url' => isset($_SERVER['HTTPS']) ? 'https://'.$_SERVER['HTTP_HOST'] : 'http://'.$_SERVER['HTTP_HOST'],
'debug' => false,
'maintenance' => false,
'db' => [
'connection' => 'sqlite',
'dsn' => BASE_DIR.'resources/database/xbackbone.db',
'username' => null,
'password' => null,
],
'storage' => [
'driver' => 'local',
'path' => realpath(__DIR__.'/').DIRECTORY_SEPARATOR.'storage',
],
], require BASE_DIR.'config.php');
if (!$config['displayErrorDetails']) {
$config['routerCacheFile'] = BASE_DIR . 'resources/cache/routes.cache.php';
$builder = new ContainerBuilder();
if (!$config['debug']) {
$builder->enableCompilation(BASE_DIR.'/resources/cache/di/');
$builder->writeProxiesToFile(true, BASE_DIR.'/resources/cache/proxies');
}
$builder->addDefinitions([
'config' => value($config),
'logger' => factory(function (Container $container) {
$logger = new Logger('app');
$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->includeStacktraces(true);
$streamHandler->setFormatter($lineFormatter);
$logger->pushHandler($streamHandler);
return $logger;
}),
'session' => factory(function (Container $container) {
return new Session('xbackbone_session', BASE_DIR.'resources/sessions');
}),
'database' => factory(function (Container $container) {
$config = $container->get('config');
$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']);
}),
'storage' => factory(function (Container $container) {
$config = $container->get('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',
]);
return new Filesystem(new AwsS3Adapter($client, $config['storage']['bucket'], $config['storage']['path']));
case 'dropbox':
$client = new DropboxClient($config['storage']['token']);
return new Filesystem(new DropboxAdapter($client), ['case_sensitive' => false]);
case 'ftp':
return new Filesystem(new FtpAdapter([
'host' => $config['storage']['host'],
'username' => $config['storage']['username'],
'password' => $config['storage']['password'],
'port' => $config['storage']['port'],
'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.');
}
}),
'lang' => factory(function (Container $container) {
$config = $container->get('config');
if (isset($config['lang'])) {
return Lang::build($config['lang'], BASE_DIR.'resources/lang/');
}
return Lang::build(Lang::recognize(), BASE_DIR.'resources/lang/');
}),
'view' => factory(function ($container) {
return new View($container);
}),
]);
$app = Bridge::create($builder->build());
if (!$config['debug']) {
$app->getRouteCollector()->setCacheFile(BASE_DIR.'resources/cache/routes.cache.php');
}
$container = new Container(['settings' => $config]);
$container['config'] = function ($container) use ($config) {
return $config;
};
$container['logger'] = function ($container) {
$logger = new Logger('app');
$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->includeStacktraces(true);
$streamHandler->setFormatter($lineFormatter);
$logger->pushHandler($streamHandler);
return $logger;
};
$container['session'] = function ($container) {
return new Session('xbackbone_session', BASE_DIR . 'resources/sessions');
};
$container['database'] = function ($container) use (&$config) {
$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']);
};
$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',
]);
return new Filesystem(new AwsS3Adapter($client, $config['storage']['bucket'], $config['storage']['path']));
case 'dropbox':
$client = new DropboxClient($config['storage']['token']);
return new Filesystem(new DropboxAdapter($client), ['case_sensitive' => false]);
case 'ftp':
return new Filesystem(new FtpAdapter([
'host' => $config['storage']['host'],
'username' => $config['storage']['username'],
'password' => $config['storage']['password'],
'port' => $config['storage']['port'],
'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) {
if (isset($config['lang'])) {
return Lang::build($config['lang'], BASE_DIR . 'resources/lang/');
}
return Lang::build(Lang::recognize(), BASE_DIR . 'resources/lang/');
};
$container['view'] = function ($container) use (&$config) {
$view = new Twig(BASE_DIR . 'resources/templates', [
'cache' => BASE_DIR . 'resources/cache',
'autoescape' => 'html',
'debug' => $config['displayErrorDetails'],
'auto_reload' => $config['displayErrorDetails'],
]);
// Instantiate and add Slim specific extension
$router = $container->get('router');
$uri = Uri::createFromEnvironment(new Environment($_SERVER));
$view->addExtension(new Slim\Views\TwigExtension($router, $uri));
$view->getEnvironment()->addGlobal('config', $config);
$view->getEnvironment()->addGlobal('request', $container->get('request'));
$view->getEnvironment()->addGlobal('alerts', $container->get('session')->getAlert());
$view->getEnvironment()->addGlobal('session', $container->get('session')->all());
$view->getEnvironment()->addGlobal('current_lang', $container->get('lang')->getLang());
$view->getEnvironment()->addGlobal('PLATFORM_VERSION', PLATFORM_VERSION);
$view->getEnvironment()->addFunction(new TwigFunction('route', 'route'));
$view->getEnvironment()->addFunction(new TwigFunction('lang', 'lang'));
$view->getEnvironment()->addFunction(new TwigFunction('urlFor', 'urlFor'));
$view->getEnvironment()->addFunction(new TwigFunction('asset', 'asset'));
$view->getEnvironment()->addFunction(new TwigFunction('mime2font', 'mime2font'));
$view->getEnvironment()->addFunction(new TwigFunction('queryParams', 'queryParams'));
$view->getEnvironment()->addFunction(new TwigFunction('isDisplayableImage', 'isDisplayableImage'));
return $view;
};
$container['phpErrorHandler'] = function ($container) {
return function (Request $request, Response $response, Throwable $error) use (&$container) {
$container->logger->critical('Fatal runtime error during app execution', ['exception' => $error]);
return $container->view->render($response->withStatus(500), 'errors/500.twig', ['exception' => $error]);
};
};
$container['errorHandler'] = function ($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 UnauthorizedException) {
return $container->view->render($response->withStatus(403), 'errors/403.twig');
}
$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) {
return function (Request $request, Response $response, $methods) use (&$container) {
return $container->view->render($response->withStatus(405)->withHeader('Allow', implode(', ', $methods)), 'errors/405.twig');
};
};
$container['notFoundHandler'] = function ($container) {
return function (Request $request, Response $response) use (&$container) {
$response->withStatus(404)->withHeader('Content-Type', 'text/html');
return $container->view->render($response, 'errors/404.twig');
};
};
$app = new App($container);
$app->addRoutingMiddleware();
// Permanently redirect paths with a trailing slash to their non-trailing counterpart
$app->add(function (Request $request, Response $response, callable $next) {
$uri = $request->getUri();
$path = $uri->getPath();
$app->add(function (Request $request, RequestHandler $handler) {
$uri = $request->getUri();
$path = $uri->getPath();
if ($path !== '/' && substr($path, -1) === '/') {
$uri = $uri->withPath(substr($path, 0, -1));
if ($path !== '/' && substr($path, -1) === '/') {
// permanently redirect paths with a trailing slash
// to their non-trailing counterpart
$uri = $uri->withPath(substr($path, 0, -1));
if ($request->getMethod() === 'GET') {
return $response->withRedirect((string)$uri, 301);
} else {
return $next($request->withUri($uri), $response);
}
}
if ($request->getMethod() == 'GET') {
$response = new Response();
return $response->withStatus(301)
->withHeader('Location', (string)$uri);
} else {
$request = $request->withUri($uri);
}
}
return $next($request, $response);
return $handler->handle($request);
});
// Load the application routes
require BASE_DIR . 'app/routes.php';
require BASE_DIR.'app/routes.php';
// Configure the error handler
$errorHandler = new AppErrorHandler($app->getCallableResolver(), $app->getResponseFactory());
$errorHandler->registerErrorRenderer('text/html', HtmlErrorRenderer::class);
// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware($config['debug'], true, true);
$errorMiddleware->setDefaultErrorHandler($errorHandler);
return $app;

View file

@ -1,26 +1,33 @@
{
"name": "sergix44/xbackbone",
"version": "2.6.6",
"version": "3.0",
"description": "A lightweight ShareX PHP backend",
"type": "project",
"require": {
"php": ">=7.1",
"slim/slim": "^3.0",
"slim/twig-view": "^2.4",
"ext-intl": "*",
"ext-json": "*",
"ext-gd": "*",
"ext-pdo": "*",
"ext-zip": "*",
"slim/slim": "^4.0",
"php-di/slim-bridge": "^3.0",
"twig/twig": "^2.12",
"guzzlehttp/psr7": "^1.6",
"league/flysystem": "^1.0.45",
"monolog/monolog": "^1.23",
"intervention/image": "^2.4",
"league/flysystem-aws-s3-v3": "^1.0",
"spatie/flysystem-dropbox": "^1.0",
"superbalist/flysystem-google-storage": "^7.2",
"ext-intl": "*",
"ext-json": "*",
"ext-gd": "*",
"ext-pdo": "*",
"ext-zip": "*"
"http-interop/http-factory-guzzle": "^1.0"
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
},
"prefer-stable": true,
"minimum-stability": "dev",
"autoload": {
"files": [
"app/helpers.php"

963
composer.lock generated

File diff suppressed because it is too large Load diff

View file

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

View file

@ -12,7 +12,7 @@
</div>
</div>
</div>
{% if config.displayErrorDetails %}
{% if exception is not null %}
<div class="row">
<div class="col-md-12">
<div class="card">

View file

@ -83,9 +83,9 @@ var app = {
var $themes = $('#themes');
$.get(window.AppConfig.base_url + '/system/themes', function (data) {
$themes.empty();
Object.keys(data).forEach(function (key) {
$.each(data, function (key, value) {
var opt = document.createElement('option');
opt.value = data[key];
opt.value = value;
opt.innerHTML = key;
$themes.append(opt);
});