Apply fixes from StyleCI

[ci skip] [skip ci]
This commit is contained in:
Sergio Brighenti 2020-04-04 10:37:13 +00:00 committed by StyleCI Bot
parent 303e607f7d
commit c0c4729698
23 changed files with 2275 additions and 2310 deletions

View file

@ -2,7 +2,6 @@
namespace App\Controllers;
use League\Flysystem\FileNotFoundException;
use Slim\Http\Request;
use Slim\Http\Response;
@ -10,84 +9,84 @@ use Slim\Http\Response;
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 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;
$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 $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(),
]);
}
/**
* @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(Request $request, 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, '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 ($request->getParam('lang') !== 'auto') {
$config['lang'] = $request->getParam('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', [$request->getParam('lang')]));
return redirect($response, 'system');
}
}
return redirect($response, 'system');
}
}

View file

@ -22,46 +22,46 @@ use Slim\Container;
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 \Interop\Container\Exception\ContainerException
*/
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

@ -9,72 +9,72 @@ use Slim\Http\Response;
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');
}
/**
* @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');
}
return redirect($response, 'home');
}
return redirect($response, '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 $args
* @return Response
*/
public function home(Request $request, Response $response, $args): 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);
$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 ($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;
}
$query->orderBy($order, $request->getParam('order', 'DESC'))
->withUserId($this->session->get('user_id'))
->search($request->getParam('search', null))
->run($page);
$query->orderBy($order, $request->getParam('order', 'DESC'))
->withUserId($this->session->get('user_id'))
->search($request->getParam('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 $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,
]
);
}
/**
* @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 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');
}
}

View file

@ -2,78 +2,75 @@
namespace App\Controllers;
use Slim\Http\Request;
use Slim\Http\Response;
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 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 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
{
$result = $this->database->query('SELECT `id`, `email`, `username`, `password`,`is_admin`, `active` FROM `users` WHERE `username` = ? OR `email` = ? LIMIT 1', [$request->getParam('username'), $request->getParam('username')])->fetch();
$result = $this->database->query('SELECT `id`, `email`, `username`, `password`,`is_admin`, `active` FROM `users` WHERE `username` = ? OR `email` = ? LIMIT 1', [$request->getParam('username'), $request->getParam('username')])->fetch();
if (!$result || !password_verify($request->getParam('password'), $result->password)) {
$this->session->alert(lang('bad_login'), 'danger');
return redirect($response, 'login');
}
if (!$result || !password_verify($request->getParam('password'), $result->password)) {
$this->session->alert(lang('bad_login'), 'danger');
return redirect($response, '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 (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, '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 $response->withRedirect($this->session->get('redirectTo'));
}
if ($this->session->has('redirectTo')) {
return $response->withRedirect($this->session->get('redirectTo'));
}
return redirect($response, '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 Request $request
* @param Response $response
* @return Response
*/
public function logout(Request $request, Response $response): Response
{
$this->session->clear();
$this->session->set('logged', false);
$this->session->alert(lang('goodbye'), 'warning');
return redirect($response, 'login.show');
}
}

View file

@ -7,35 +7,34 @@ use Slim\Http\Response;
class ThemeController extends Controller
{
/**
* @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 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'));
$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 $response->withJson($out);
}
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');
}
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($request->getParam('css')));
return redirect($response, 'system');
}
}

View file

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

View file

@ -15,398 +15,392 @@ use Slim\Http\Stream;
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->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);
}
}
}

View file

@ -2,7 +2,6 @@
namespace App\Controllers;
use App\Exceptions\UnauthorizedException;
use Slim\Exception\NotFoundException;
use Slim\Http\Request;
@ -10,412 +9,411 @@ use Slim\Http\Response;
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 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;
}
}

View file

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

View file

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

View file

@ -2,14 +2,13 @@
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);
}
}
public function __construct(string $message = 'Under Maintenance', int $code = 503, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View file

@ -2,14 +2,13 @@
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);
}
}
public function __construct(string $message = 'Forbidden', int $code = 403, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View file

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

View file

@ -8,27 +8,26 @@ use Slim\Http\Response;
class AuthMiddleware extends Middleware
{
/**
* @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 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');
}
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);
$this->session->set('redirectTo', (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
return redirect($response, 'login.show');
}
return $next($request, $response);
}
}
return $next($request, $response);
}
}

View file

@ -8,19 +8,19 @@ use Slim\Http\Response;
class CheckForMaintenanceMiddleware extends Middleware
{
/**
* @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 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();
}
return $next($request, $response);
}
}
return $next($request, $response);
}
}

View file

@ -8,31 +8,31 @@ use Slim\Http\Response;
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 \Interop\Container\Exception\ContainerException
*/
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 Response $response
* @param callable $next
*/
abstract public function __invoke(Request $request, Response $response, callable $next);
}

View file

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

View file

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

View file

@ -1,318 +1,318 @@
<?php
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);
}
/**
* 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);
}
return $response->withRedirect($url, $status);
}
return $response->withRedirect($url, $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
{
global $app;
$baseUrl = $app->getContainer()->get('settings')['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->getContainer()->get('router')->relativePathFor($path, $args);
return urlFor($uri, $append);
}
}
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
{
global $app;
return $app->getContainer()->get('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
* @throws \Interop\Container\Exception\ContainerException
*/
function queryParams(array $replace = [])
{
global $container;
/** @var \Slim\Http\Request $request */
$request = $container->get('request');
$params = array_replace_recursive($request->getQueryParams(), $replace);
$params = array_replace_recursive($request->getQueryParams(), $replace);
return !empty($params) ? '?' . http_build_query($params) : '';
}
return !empty($params) ? '?' . http_build_query($params) : '';
}
}
if (!function_exists('glob_recursive')) {
/**
* 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

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

View file

@ -27,199 +27,197 @@ use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter;
use Twig\TwigFunction;
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();
} elseif (!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',
],
'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');
if (!$config['displayErrorDetails']) {
$config['routerCacheFile'] = BASE_DIR . 'resources/cache/routes.cache.php';
$config['routerCacheFile'] = BASE_DIR . 'resources/cache/routes.cache.php';
}
$container = new Container(['settings' => $config]);
$container['config'] = function ($container) use ($config) {
return $config;
return $config;
};
$container['logger'] = function ($container) {
$logger = new Logger('app');
$logger = new Logger('app');
$streamHandler = new RotatingFileHandler(BASE_DIR . 'logs/log.txt', 10, Logger::DEBUG);
$streamHandler = new RotatingFileHandler(BASE_DIR . 'logs/log.txt', 10, Logger::DEBUG);
$lineFormatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", "Y-m-d H:i:s");
$lineFormatter->includeStacktraces(true);
$lineFormatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", "Y-m-d H:i:s");
$lineFormatter->includeStacktraces(true);
$streamHandler->setFormatter($lineFormatter);
$streamHandler->setFormatter($lineFormatter);
$logger->pushHandler($streamHandler);
$logger->pushHandler($streamHandler);
return $logger;
return $logger;
};
$container['session'] = function ($container) {
return new Session('xbackbone_session', BASE_DIR . 'resources/sessions');
return new Session('xbackbone_session', BASE_DIR . 'resources/sessions');
};
$container['database'] = function ($container) use (&$config) {
$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']);
$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',
]);
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.');
}
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/');
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'],
]);
$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));
// 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()->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;
$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]);
};
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) {
return function (Request $request, Response $response, Exception $exception) use (&$container) {
if ($exception instanceof MaintenanceException) {
return $container->view->render($response->withStatus(503), 'errors/maintenance.twig');
}
if ($exception instanceof MaintenanceException) {
return $container->view->render($response->withStatus(503), 'errors/maintenance.twig');
}
if ($exception instanceof UnauthorizedException) {
return $container->view->render($response->withStatus(403), 'errors/403.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->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');
};
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');
};
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);
// 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();
$uri = $request->getUri();
$path = $uri->getPath();
if ($path !== '/' && substr($path, -1) === '/') {
$uri = $uri->withPath(substr($path, 0, -1));
if ($path !== '/' && substr($path, -1) === '/') {
$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') {
return $response->withRedirect((string)$uri, 301);
} else {
return $next($request->withUri($uri), $response);
}
}
return $next($request, $response);
return $next($request, $response);
});
// Load the application routes
require BASE_DIR . 'app/routes.php';
return $app;
return $app;

View file

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

View file

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