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,19 +4,21 @@ 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
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function system(Request $request, Response $response): Response
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;
@ -31,7 +33,7 @@ class AdminController extends Controller
$totalSize += $filesystem->getSize($media->storage_path);
}
return $this->view->render($response, 'dashboard/system.twig', [
return view()->render($response, 'dashboard/system.twig', [
'usersCount' => $usersCount,
'mediasCount' => $mediasCount,
'orphanFilesCount' => $orphanFilesCount,
@ -47,7 +49,7 @@ class AdminController extends Controller
* @param Response $response
* @return Response
*/
public function deleteOrphanFiles(Request $request, Response $response): Response
public function deleteOrphanFiles(Response $response): Response
{
$orphans = $this->database->query('SELECT * FROM `uploads` WHERE `user_id` IS NULL')->fetchAll();
@ -66,7 +68,7 @@ class AdminController extends Controller
$this->session->alert(lang('deleted_orphans', [$deleted]));
return redirect($response, 'system');
return redirect($response, route('system'));
}
/**
@ -76,18 +78,18 @@ class AdminController extends Controller
*/
public function applyLang(Request $request, Response $response): Response
{
$config = require BASE_DIR . 'config.php';
$config = require BASE_DIR.'config.php';
if ($request->getParam('lang') !== 'auto') {
$config['lang'] = $request->getParam('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,19 +5,22 @@ 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
{
@ -33,7 +36,8 @@ abstract class Controller
/**
* @param $name
* @return mixed|null
* @throws \Interop\Container\Exception\ContainerException
* @throws DependencyException
* @throws NotFoundException
*/
public function __get($name)
{

View file

@ -3,40 +3,43 @@
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
{
/**
* @Inject
* @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')) {
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
* @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, $args): Response
public function home(Request $request, Response $response, int $page = 0): Response
{
$page = isset($args['page']) ? (int)$args['page'] : 0;
$page = max(0, --$page);
$query = new MediaQuery($this->database, $this->session->get('admin', false), $this->storage);
switch ($request->getParam('sort', 'time')) {
switch (param($request, 'sort', 'time')) {
case 'size':
$order = MediaQuery::ORDER_SIZE;
break;
@ -49,12 +52,12 @@ class DashboardController extends Controller
break;
}
$query->orderBy($order, $request->getParam('order', 'DESC'))
$query->orderBy($order, param($request, 'order', 'DESC'))
->withUserId($this->session->get('user_id'))
->search($request->getParam('search', null))
->search(param($request, 'search', null))
->run($page);
return $this->view->render(
return view()->render(
$response,
($this->session->get('admin', false) && $this->session->get('gallery_view', true)) ? 'dashboard/admin.twig' : 'dashboard/home.twig',
[
@ -67,14 +70,12 @@ class DashboardController extends Controller
}
/**
* @param Request $request
* @param Response $response
* @param $args
* @return Response
*/
public function switchView(Request $request, Response $response, $args): Response
public function switchView(Response $response): Response
{
$this->session->set('gallery_view', !$this->session->get('gallery_view', true));
return redirect($response, 'home');
return redirect($response, route('home'));
}
}

View file

@ -3,23 +3,25 @@
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
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function show(Request $request, Response $response): Response
public function show(Response $response): Response
{
if ($this->session->get('logged', false)) {
return redirect($response, 'home');
return redirect($response, route('home'));
}
return $this->view->render($response, 'auth/login.twig');
return view()->render($response, 'auth/login.twig');
}
/**
@ -29,22 +31,22 @@ class LoginController extends Controller
*/
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($request->getParam('password'), $result->password)) {
if (!$result || !password_verify(param($request, 'password'), $result->password)) {
$this->session->alert(lang('bad_login'), 'danger');
return redirect($response, 'login');
return redirect($response, route('login'));
}
if (isset($this->settings['maintenance']) && $this->settings['maintenance'] && !$result->is_admin) {
if (isset($this->config['maintenance']) && $this->config['maintenance'] && !$result->is_admin) {
$this->session->alert(lang('maintenance_in_progress'), 'info');
return redirect($response, 'login');
return redirect($response, route('login'));
}
if (!$result->active) {
$this->session->alert(lang('account_disabled'), 'danger');
return redirect($response, 'login');
return redirect($response, route('login'));
}
$this->session->set('logged', true);
@ -57,23 +59,22 @@ class LoginController extends Controller
$this->logger->info("User $result->username logged in.");
if ($this->session->has('redirectTo')) {
return $response->withRedirect($this->session->get('redirectTo'));
return redirect($response, $this->session->get('redirectTo'));
}
return redirect($response, 'home');
return redirect($response, route('home'));
}
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function logout(Request $request, Response $response): Response
public function logout(Response $response): Response
{
$this->session->clear();
$this->session->set('logged', false);
$this->session->alert(lang('goodbye'), 'warning');
return redirect($response, 'login.show');
return redirect($response, route('login.show'));
}
}

View file

@ -2,17 +2,16 @@
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
public function getThemes(Response $response): Response
{
$apiJson = json_decode(file_get_contents('https://bootswatch.com/api/4.json'));
@ -23,19 +22,22 @@ class ThemeController extends Controller
$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')) {
if (!is_writable(BASE_DIR.'static/bootstrap/css/bootstrap.min.css')) {
$this->session->alert(lang('cannot_write_file'), 'danger');
return redirect($response, 'system');
return redirect($response, route('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,15 +2,15 @@
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
{
@ -29,36 +29,36 @@ class UploadController extends Controller
'version' => PLATFORM_VERSION,
];
if ($this->settings['maintenance']) {
if ($this->config['maintenance']) {
$json['message'] = 'Endpoint under maintenance.';
return $response->withJson($json, 503);
return json($response, $json, 503);
}
if ($request->getServerParam('CONTENT_LENGTH') > stringToBytes(ini_get('post_max_size'))) {
if ($request->getServerParams()['CONTENT_LENGTH'] > stringToBytes(ini_get('post_max_size'))) {
$json['message'] = 'File too large (post_max_size too low?).';
return $response->withJson($json, 400);
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 $response->withJson($json, 400);
return json($response, $json, 400);
}
if ($request->getParam('token') === null) {
if (param($request, 'token') === null) {
$json['message'] = 'Token not specified.';
return $response->withJson($json, 400);
return json($response, $json, 400);
}
$user = $this->database->query('SELECT * FROM `users` WHERE `token` = ? LIMIT 1', $request->getParam('token'))->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `token` = ? LIMIT 1', param($request, 'token'))->fetch();
if (!$user) {
$json['message'] = 'Token specified not found.';
return $response->withJson($json, 404);
return json($response, $json, 404);
}
if (!$user->active) {
$json['message'] = 'Account disabled.';
return $response->withJson($json, 401);
return json($response, $json, 401);
}
do {
@ -85,23 +85,28 @@ class UploadController extends Controller
$this->logger->info("User $user->username uploaded new media.", [$this->database->raw()->lastInsertId()]);
return $response->withJson($json, 201);
return json($response, $json, 201);
}
/**
* @param Request $request
* @param Response $response
* @param $args
* @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
* @throws NotFoundException
*/
public function show(Request $request, Response $response, $args): Response
public function show(Request $request, Response $response, string $userCode, string $mediaCode, string $token = null): Response
{
$media = $this->getMedia($args['userCode'], $args['mediaCode']);
$media = $this->getMedia($userCode, $mediaCode);
if (!$media || (!$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false))) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
$filesystem = $this->storage;
@ -129,11 +134,11 @@ class UploadController extends Controller
$media->size = humanFileSize($size);
} catch (FileNotFoundException $e) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
return $this->view->render($response, 'upload/public.twig', [
'delete_token' => isset($args['token']) ? $args['token'] : null,
return view()->render($response, 'upload/public.twig', [
'delete_token' => $token,
'media' => $media,
'type' => $type,
'extension' => pathinfo($media->filename, PATHINFO_EXTENSION),
@ -144,29 +149,31 @@ class UploadController extends Controller
/**
* @param Request $request
* @param Response $response
* @param $args
* @param string $userCode
* @param string $mediaCode
* @param string $token
* @return Response
* @throws NotFoundException
* @throws UnauthorizedException
* @throws HttpNotFoundException
* @throws HttpUnauthorizedException
*/
public function deleteByToken(Request $request, Response $response, $args): Response
public function deleteByToken(Request $request, Response $response, string $userCode, string $mediaCode, string $token): Response
{
$media = $this->getMedia($args['userCode'], $args['mediaCode']);
$media = $this->getMedia($userCode, $mediaCode);
if (!$media) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
$user = $this->database->query('SELECT `id`, `active` FROM `users` WHERE `token` = ? LIMIT 1', $args['token'])->fetch();
$user = $this->database->query('SELECT `id`, `active` FROM `users` WHERE `token` = ? LIMIT 1', $token)->fetch();
if (!$user) {
$this->session->alert(lang('token_not_found'), 'danger');
return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
return redirect($response, $request->getHeaderLine('HTTP_REFERER'));
}
if (!$user->active) {
$this->session->alert(lang('account_disabled'), 'danger');
return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
return redirect($response, $request->getHeaderLine('HTTP_REFERER'));
}
if ($this->session->get('admin', false) || $user->id === $media->user_id) {
@ -174,33 +181,33 @@ class UploadController extends Controller
try {
$this->storage->delete($media->storage_path);
} catch (FileNotFoundException $e) {
throw new NotFoundException($request, $response);
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]);
$this->logger->info('User '.$user->username.' deleted a media via token.', [$media->mediaId]);
}
} else {
throw new UnauthorizedException();
throw new HttpUnauthorizedException($request);
}
return redirect($response, 'home');
return redirect($response, route('home'));
}
/**
* @param Request $request
* @param Response $response
* @param $args
* @param int $id
* @return Response
* @throws NotFoundException
* @throws FileNotFoundException
* @throws HttpNotFoundException
*/
public function getRawById(Request $request, Response $response, $args): Response
public function getRawById(Request $request, Response $response, int $id): Response
{
$media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $id)->fetch();
if (!$media) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
return $this->streamMedia($request, $response, $this->storage, $media);
@ -209,17 +216,18 @@ class UploadController extends Controller
/**
* @param Request $request
* @param Response $response
* @param $args
* @param string $userCode
* @param string $mediaCode
* @return Response
* @throws NotFoundException
* @throws FileNotFoundException
* @throws HttpNotFoundException
*/
public function showRaw(Request $request, Response $response, $args): Response
public function showRaw(Request $request, Response $response, string $userCode, string $mediaCode): Response
{
$media = $this->getMedia($args['userCode'], $args['mediaCode']);
$media = $this->getMedia($userCode, $mediaCode);
if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
return $this->streamMedia($request, $response, $this->storage, $media);
}
@ -228,17 +236,18 @@ class UploadController extends Controller
/**
* @param Request $request
* @param Response $response
* @param $args
* @param string $userCode
* @param string $mediaCode
* @return Response
* @throws NotFoundException
* @throws FileNotFoundException
* @throws HttpNotFoundException
*/
public function download(Request $request, Response $response, $args): Response
public function download(Request $request, Response $response, string $userCode, string $mediaCode): Response
{
$media = $this->getMedia($args['userCode'], $args['mediaCode']);
$media = $this->getMedia($userCode, $mediaCode);
if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
return $this->streamMedia($request, $response, $this->storage, $media, 'attachment');
}
@ -246,20 +255,20 @@ class UploadController extends Controller
/**
* @param Request $request
* @param Response $response
* @param $args
* @param int $id
* @return Response
* @throws NotFoundException
* @throws HttpNotFoundException
*/
public function togglePublish(Request $request, Response $response, $args): Response
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', $args['id'])->fetch();
$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', [$args['id'], $this->session->get('user_id')])->fetch();
$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 NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
$this->database->query('UPDATE `uploads` SET `published`=? WHERE `id`=?', [$media->published ? 0 : 1, $media->id]);
@ -270,17 +279,17 @@ class UploadController extends Controller
/**
* @param Request $request
* @param Response $response
* @param $args
* @param int $id
* @return Response
* @throws NotFoundException
* @throws UnauthorizedException
* @throws HttpNotFoundException
* @throws HttpUnauthorizedException
*/
public function delete(Request $request, Response $response, $args): Response
public function delete(Request $request, Response $response, int $id): Response
{
$media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $id)->fetch();
if (!$media) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
if ($this->session->get('admin', false) || $media->user_id === $this->session->get('user_id')) {
@ -288,14 +297,14 @@ class UploadController extends Controller
try {
$this->storage->delete($media->storage_path);
} catch (FileNotFoundException $e) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request);
} 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->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 UnauthorizedException();
throw new HttpUnauthorizedException($request);
}
return $response->withStatus(200);
@ -332,37 +341,36 @@ class UploadController extends Controller
set_time_limit(0);
$mime = $storage->getMimetype($media->storage_path);
if ($request->getParam('width') !== null && explode('/', $mime)[0] === 'image') {
if (param($request, 'width') !== null && explode('/', $mime)[0] === 'image') {
$image = Image::make($storage->readStream($media->storage_path))
->resizeCanvas(
$request->getParam('width'),
$request->getParam('height'),
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"')
->write($image);
->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-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 (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-Disposition', $disposition.'; filename="'.$media->filename.'"')
->withHeader('Content-Length', $stream->getSize())
->withHeader('Accept-Ranges', 'bytes')
->withHeader('Content-Range', "0,{$stream->getSize()}")
@ -382,7 +390,7 @@ class UploadController extends Controller
$stream->seek($start);
header("Content-Type: $mime");
header('Content-Length: ' . ($end - $start + 1));
header('Content-Length: '.($end - $start + 1));
header('Accept-Ranges: bytes');
header("Content-Range: bytes $start-$end/{$stream->getSize()}");

View file

@ -3,31 +3,32 @@
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
* @param int|null $page
* @return Response
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function index(Request $request, Response $response, $args): Response
public function index(Response $response, int $page = 0): 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,
return view()->render($response,
'user/index.twig',
[
'users' => $users,
@ -39,13 +40,15 @@ class UserController extends Controller
}
/**
* @param Request $request
* @param Response $response
* @return Response
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function create(Request $request, Response $response): Response
public function create(Response $response): Response
{
return $this->view->render($response, 'user/create.twig');
return view()->render($response, 'user/create.twig');
}
/**
@ -55,29 +58,29 @@ class UserController extends Controller
*/
public function store(Request $request, Response $response): Response
{
if ($request->getParam('email') === null) {
if (param($request, 'email') === null) {
$this->session->alert(lang('email_required'), 'danger');
return redirect($response, 'user.create');
return redirect($response, route('user.create'));
}
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ?', $request->getParam('email'))->fetch()->count > 0) {
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ?', param($request, 'email'))->fetch()->count > 0) {
$this->session->alert(lang('email_taken'), 'danger');
return redirect($response, 'user.create');
return redirect($response, route('user.create'));
}
if ($request->getParam('username') === null) {
if (param($request, 'username') === null) {
$this->session->alert(lang('username_required'), 'danger');
return redirect($response, 'user.create');
return redirect($response, route('user.create'));
}
if ($request->getParam('password') === null) {
if (param($request, 'password') === null) {
$this->session->alert(lang('password_required'), 'danger');
return redirect($response, 'user.create');
return redirect($response, route('user.create'));
}
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ?', $request->getParam('username'))->fetch()->count > 0) {
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ?', param($request, 'username'))->fetch()->count > 0) {
$this->session->alert(lang('username_taken'), 'danger');
return redirect($response, 'user.create');
return redirect($response, route('user.create'));
}
do {
@ -87,37 +90,40 @@ class UserController extends Controller
$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,
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', [$request->getParam('username')]), 'success');
$this->logger->info('User ' . $this->session->get('username') . ' created a new user.', [array_diff_key($request->getParams(), array_flip(['password']))]);
$this->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, 'user.index');
return redirect($response, route('user.index'));
}
/**
* @param Request $request
* @param Response $response
* @param $args
* @param $id
* @return Response
* @throws NotFoundException
* @throws HttpNotFoundException
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function edit(Request $request, Response $response, $args): Response
public function edit(Request $request, Response $response, int $id): Response
{
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $id)->fetch();
if (!$user) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
return $this->view->render($response, 'user/edit.twig', [
return view()->render($response, 'user/edit.twig', [
'profile' => false,
'user' => $user,
]);
@ -126,120 +132,123 @@ class UserController extends Controller
/**
* @param Request $request
* @param Response $response
* @param $args
* @param int $id
* @return Response
* @throws NotFoundException
* @throws HttpNotFoundException
*/
public function update(Request $request, Response $response, $args): Response
public function update(Request $request, Response $response, int $id): Response
{
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $id)->fetch();
if (!$user) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
if ($request->getParam('email') === null) {
if (param($request, 'email') === null) {
$this->session->alert(lang('email_required'), 'danger');
return redirect($response, 'user.edit', ['id' => $args['id']]);
return redirect($response, route('user.edit', ['id' => $id]));
}
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ? AND `email` <> ?', [$request->getParam('email'), $user->email])->fetch()->count > 0) {
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ? AND `email` <> ?', [param($request, 'email'), $user->email])->fetch()->count > 0) {
$this->session->alert(lang('email_taken'), 'danger');
return redirect($response, 'user.edit', ['id' => $args['id']]);
return redirect($response, route('user.edit', ['id' => $id]));
}
if ($request->getParam('username') === null) {
if (param($request, 'username') === null) {
$this->session->alert(lang('username_required'), 'danger');
return redirect($response, 'user.edit', ['id' => $args['id']]);
return redirect($response, route('user.edit', ['id' => $id]));
}
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ? AND `username` <> ?', [$request->getParam('username'), $user->username])->fetch()->count > 0) {
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ? AND `username` <> ?', [param($request, 'username'), $user->username])->fetch()->count > 0) {
$this->session->alert(lang('username_taken'), 'danger');
return redirect($response, 'user.edit', ['id' => $args['id']]);
return redirect($response, route('user.edit', ['id' => $id]));
}
if ($user->id === $this->session->get('user_id') && $request->getParam('is_admin') === null) {
if ($user->id === $this->session->get('user_id') && param($request, 'is_admin') === null) {
$this->session->alert(lang('cannot_demote'), 'danger');
return redirect($response, 'user.edit', ['id' => $args['id']]);
return redirect($response, route('user.edit', ['id' => $id]));
}
if ($request->getParam('password') !== null && !empty($request->getParam('password'))) {
if (param($request, 'password') !== null && !empty(param($request, '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,
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` = ?', [
$request->getParam('email'),
$request->getParam('username'),
$request->getParam('is_admin') !== null ? 1 : 0,
$request->getParam('is_active') !== null ? 1 : 0,
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', [$request->getParam('username')]), 'success');
$this->logger->info('User ' . $this->session->get('username') . " updated $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->getParams(), array_flip(['password'])),
array_diff_key($request->getParsedBody(), array_flip(['password'])),
]);
return redirect($response, 'user.index');
return redirect($response, route('user.index'));
}
/**
* @param Request $request
* @param Response $response
* @param $args
* @param int $id
* @return Response
* @throws NotFoundException
* @throws HttpNotFoundException
*/
public function delete(Request $request, Response $response, $args): Response
public function delete(Request $request, Response $response, int $id): Response
{
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $id)->fetch();
if (!$user) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request, $response);
}
if ($user->id === $this->session->get('user_id')) {
$this->session->alert(lang('cannot_delete'), 'danger');
return redirect($response, 'user.index');
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.");
$this->logger->info('User '.$this->session->get('username')." deleted $user->id.");
return redirect($response, 'user.index');
return redirect($response, route('user.index'));
}
/**
* @param Request $request
* @param Response $response
* @return Response
* @throws NotFoundException
* @throws UnauthorizedException
* @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 NotFoundException($request, $response);
throw new HttpNotFoundException($request);
}
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
throw new UnauthorizedException();
throw new HttpUnauthorizedException($request);
}
return $this->view->render($response, 'user/edit.twig', [
return view()->render($response, 'user/edit.twig', [
'profile' => true,
'user' => $user,
]);
@ -248,70 +257,70 @@ class UserController extends Controller
/**
* @param Request $request
* @param Response $response
* @param $args
* @param int $id
* @return Response
* @throws NotFoundException
* @throws UnauthorizedException
* @throws HttpNotFoundException
* @throws HttpUnauthorizedException
*/
public function profileEdit(Request $request, Response $response, $args): Response
public function profileEdit(Request $request, Response $response, int $id): Response
{
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $id)->fetch();
if (!$user) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request, $response);
}
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
throw new UnauthorizedException();
throw new HttpUnauthorizedException($request);
}
if ($request->getParam('email') === null) {
if (param($request, 'email') === null) {
$this->session->alert(lang('email_required'), 'danger');
return redirect($response, 'profile');
return redirect($response, route('profile'));
}
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ? AND `email` <> ?', [$request->getParam('email'), $user->email])->fetch()->count > 0) {
if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `email` = ? AND `email` <> ?', [param($request, 'email'), $user->email])->fetch()->count > 0) {
$this->session->alert(lang('email_taken'), 'danger');
return redirect($response, 'profile');
return redirect($response, route('profile'));
}
if ($request->getParam('password') !== null && !empty($request->getParam('password'))) {
if (param($request, 'password') !== null && !empty(param($request, 'password'))) {
$this->database->query('UPDATE `users` SET `email`=?, `password`=? WHERE `id` = ?', [
$request->getParam('email'),
password_hash($request->getParam('password'), PASSWORD_DEFAULT),
param($request, 'email'),
password_hash(param($request, 'password'), PASSWORD_DEFAULT),
$user->id,
]);
} else {
$this->database->query('UPDATE `users` SET `email`=? WHERE `id` = ?', [
$request->getParam('email'),
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.");
$this->logger->info('User '.$this->session->get('username')." updated profile of $user->id.");
return redirect($response, 'profile');
return redirect($response, route('profile'));
}
/**
* @param Request $request
* @param Response $response
* @param $args
* @param int $id
* @return Response
* @throws NotFoundException
* @throws UnauthorizedException
* @throws HttpNotFoundException
* @throws HttpUnauthorizedException
*/
public function refreshToken(Request $request, Response $response, $args): Response
public function refreshToken(Request $request, Response $response, int $id): Response
{
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $id)->fetch();
if (!$user) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request, $response);
}
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
throw new UnauthorizedException();
throw new HttpUnauthorizedException($request);
}
$token = $this->generateNewToken();
@ -321,7 +330,7 @@ class UserController extends Controller
$user->id,
]);
$this->logger->info('User ' . $this->session->get('username') . " refreshed token of user $user->id.");
$this->logger->info('User '.$this->session->get('username')." refreshed token of user $user->id.");
$response->getBody()->write($token);
@ -331,26 +340,26 @@ class UserController extends Controller
/**
* @param Request $request
* @param Response $response
* @param $args
* @param int $id
* @return Response
* @throws NotFoundException
* @throws UnauthorizedException
* @throws HttpNotFoundException
* @throws HttpUnauthorizedException
*/
public function getShareXconfigFile(Request $request, Response $response, $args): Response
public function getShareXconfigFile(Request $request, Response $response, int $id): Response
{
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $id)->fetch();
if (!$user) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request, $response);
}
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
throw new UnauthorizedException();
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 $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
return redirect($response, $request->getHeaderLine('HTTP_REFERER'));
}
$json = [
@ -364,40 +373,42 @@ class UserController extends Controller
],
'URL' => '$json:url$',
'ThumbnailURL' => '$json:url$/raw',
'DeletionURL' => '$json:url$/delete/' . $user->token,
'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);
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 $args
* @param int $id
* @return Response
* @throws NotFoundException
* @throws UnauthorizedException
* @throws HttpNotFoundException
* @throws HttpUnauthorizedException
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function getUploaderScriptFile(Request $request, Response $response, $args): Response
public function getUploaderScriptFile(Request $request, Response $response, int $id): Response
{
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
$user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $id)->fetch();
if (!$user) {
throw new NotFoundException($request, $response);
throw new HttpNotFoundException($request, $response);
}
if ($user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
throw new UnauthorizedException();
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 $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
return redirect($response, $request->getHeaderLine('HTTP_REFERER'));
}
return $this->view->render($response->withHeader('Content-Disposition', 'attachment;filename="xbackbone_uploader_' . $user->username . '.sh"'),
return view()->render($response->withHeader('Content-Disposition', 'attachment;filename="xbackbone_uploader_'.$user->username.'.sh"'),
'scripts/xbackbone_uploader.sh.twig',
[
'username' => $user->username,
@ -413,7 +424,7 @@ class UserController extends Controller
protected function generateNewToken(): string
{
do {
$token = 'token_' . md5(uniqid('', true));
$token = 'token_'.md5(uniqid('', true));
} while ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `token` = ?', $token)->fetch()->count > 0);
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
* @param RequestHandler $handler
* @return Response
* @throws UnauthorizedException
* @throws HttpUnauthorizedException
*/
public function __invoke(Request $request, Response $response, callable $next)
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
* @param RequestHandler $handler
* @return ResponseInterface
*/
public function __invoke(Request $request, Response $response, callable $next)
public function __invoke(Request $request, RequestHandler $handler): ResponseInterface
{
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');
$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');
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
* @param RequestHandler $handler
* @return Response
* @throws MaintenanceException
* @throws UnderMaintenanceException
*/
public function __invoke(Request $request, Response $response, callable $next)
public function __invoke(Request $request, RequestHandler $handler): Response
{
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();
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,9 +2,11 @@
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
{
@ -19,7 +21,8 @@ abstract class Middleware
/**
* @param $name
* @return mixed|null
* @throws \Interop\Container\Exception\ContainerException
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
public function __get($name)
{
@ -31,8 +34,8 @@ abstract class Middleware
/**
* @param Request $request
* @param Response $response
* @param callable $next
* @param RequestHandler $handler
* @return Response
*/
public abstract function __invoke(Request $request, Response $response, callable $next);
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,5 +1,9 @@
<?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');
}
@ -15,7 +19,7 @@ if (!function_exists('humanFileSize')) {
{
for ($i = 0; ($size / 1024) > 0.9; $i++, $size /= 1024) {
}
return round($size, $precision) . ' ' . ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][$i];
return round($size, $precision).' '.['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][$i];
}
}
@ -95,7 +99,7 @@ if (!function_exists('removeDirectory')) {
*/
function removeDirectory($path)
{
$files = glob($path . '/*');
$files = glob($path.'/*');
foreach ($files as $file) {
is_dir($file) ? removeDirectory($file) : unlink($file);
}
@ -121,24 +125,44 @@ if (!function_exists('cleanDirectory')) {
}
}
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);
}
}
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 \Slim\Http\Response $response
* @param string $path
* @param array $args
* @param null $status
* @return \Slim\Http\Response
* @param Response $response
* @param string $url
* @param int $status
* @return Response
*/
function redirect(\Slim\Http\Response $response, string $path, $args = [], $status = null)
function redirect(Response $response, string $url, $status = 302)
{
if (substr($path, 0, 1) === '/' || substr($path, 0, 3) === '../' || substr($path, 0, 2) === './') {
$url = urlFor($path);
} else {
$url = route($path, $args);
}
return $response->withRedirect($url, $status);
return $response
->withHeader('Location', $url)
->withStatus($status);
}
}
@ -150,7 +174,7 @@ if (!function_exists('asset')) {
*/
function asset(string $path): string
{
return urlFor($path, '?' . filemtime(realpath(BASE_DIR . $path)));
return urlFor($path, '?'.filemtime(realpath(BASE_DIR.$path)));
}
}
@ -163,9 +187,8 @@ if (!function_exists('urlFor')) {
*/
function urlFor(string $path, string $append = ''): string
{
global $app;
$baseUrl = $app->getContainer()->get('settings')['base_url'];
return $baseUrl . $path . $append;
$baseUrl = resolve('config')['base_url'];
return $baseUrl.$path.$append;
}
}
@ -180,11 +203,52 @@ if (!function_exists('route')) {
function route(string $path, array $args = [], string $append = ''): string
{
global $app;
$uri = $app->getContainer()->get('router')->relativePathFor($path, $args);
$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
@ -193,8 +257,7 @@ if (!function_exists('lang')) {
*/
function lang(string $key, $args = []): string
{
global $app;
return $app->getContainer()->get('lang')->get($key, $args);
return resolve('lang')->get($key, $args);
}
}
@ -286,17 +349,15 @@ 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');
$serverRequestCreator = ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();
$params = array_replace_recursive($request->getQueryParams(), $replace);
return !empty($params) ? '?' . http_build_query($params) : '';
return !empty($params) ? '?'.http_build_query($params) : '';
}
}
@ -310,8 +371,8 @@ if (!function_exists('glob_recursive')) {
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));
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');
$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');
$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,57 +20,53 @@ 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/')) {
} 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,
'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',
'dsn' => BASE_DIR.'resources/database/xbackbone.db',
'username' => null,
'password' => null,
],
'storage' => [
'driver' => 'local',
'path' => realpath(__DIR__ . '/') . DIRECTORY_SEPARATOR . 'storage',
'path' => realpath(__DIR__.'/').DIRECTORY_SEPARATOR.'storage',
],
], require BASE_DIR . 'config.php');
], require BASE_DIR.'config.php');
if (!$config['displayErrorDetails']) {
$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),
$container = new Container(['settings' => $config]);
$container['config'] = function ($container) use ($config) {
return $config;
};
$container['logger'] = function ($container) {
'logger' => factory(function (Container $container) {
$logger = new Logger('app');
$streamHandler = new RotatingFileHandler(BASE_DIR . 'logs/log.txt', 10, Logger::DEBUG);
$streamHandler = new RotatingFileHandler(BASE_DIR.'logs/log.txt', 10, Logger::DEBUG);
$lineFormatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", "Y-m-d H:i:s");
$lineFormatter->includeStacktraces(true);
@ -74,19 +76,20 @@ $container['logger'] = function ($container) {
$logger->pushHandler($streamHandler);
return $logger;
};
}),
$container['session'] = function ($container) {
return new Session('xbackbone_session', BASE_DIR . 'resources/sessions');
};
'session' => factory(function (Container $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) {
'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']));
@ -124,102 +127,60 @@ $container['storage'] = function ($container) use (&$config) {
default:
throw new InvalidArgumentException('The driver specified is not supported.');
}
};
}),
$container['lang'] = function ($container) use (&$config) {
'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($config['lang'], BASE_DIR.'resources/lang/');
}
return Lang::build(Lang::recognize(), BASE_DIR . 'resources/lang/');
};
return Lang::build(Lang::recognize(), BASE_DIR.'resources/lang/');
}),
$container['view'] = function ($container) use (&$config) {
$view = new Twig(BASE_DIR . 'resources/templates', [
'cache' => BASE_DIR . 'resources/cache',
'autoescape' => 'html',
'debug' => $config['displayErrorDetails'],
'auto_reload' => $config['displayErrorDetails'],
]);
'view' => factory(function ($container) {
return new View($container);
}),
]);
// Instantiate and add Slim specific extension
$router = $container->get('router');
$uri = Uri::createFromEnvironment(new Environment($_SERVER));
$view->addExtension(new Slim\Views\TwigExtension($router, $uri));
$app = Bridge::create($builder->build());
$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);
if (!$config['debug']) {
$app->getRouteCollector()->setCacheFile(BASE_DIR.'resources/cache/routes.cache.php');
}
$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) {
$app->add(function (Request $request, RequestHandler $handler) {
$uri = $request->getUri();
$path = $uri->getPath();
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);
if ($request->getMethod() == 'GET') {
$response = new Response();
return $response->withStatus(301)
->withHeader('Location', (string)$uri);
} else {
return $next($request->withUri($uri), $response);
$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);
});