Skip to content

Commit

Permalink
Bug fixes
Browse files Browse the repository at this point in the history
added route caching
added helpers
improved redirecting
  • Loading branch information
sergix44 committed Nov 13, 2018
1 parent 945790b commit 5c362d7
Show file tree
Hide file tree
Showing 12 changed files with 145 additions and 105 deletions.
38 changes: 10 additions & 28 deletions app/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use League\Flysystem\FileNotFoundException;
use League\Flysystem\Filesystem;
use Slim\Container;
use Slim\Http\Request;
use Slim\Http\Response;

abstract class Controller
Expand All @@ -34,20 +33,6 @@ public function __get($name)
return null;
}


/**
* Generate a human readable file size
* @param $size
* @param int $precision
* @return string
*/
protected 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];
}

/**
* Get a filesystem instance
* @return Filesystem
Expand All @@ -57,19 +42,6 @@ protected function getStorage(): Filesystem
return new Filesystem(new Local($this->settings['storage_dir']));
}

/**
* @param $path
*/
protected function removeDirectory($path)
{
$files = glob($path . '/*');
foreach ($files as $file) {
is_dir($file) ? $this->removeDirectory($file) : unlink($file);
}
rmdir($path);
return;
}

/**
* @param $id
* @return int
Expand All @@ -90,4 +62,14 @@ protected function getUsedSpaceByUser($id): int

return $totalSize;
}

/**
* @param Response $response
* @param string $path
* @return Response
*/
function redirectTo(Response $response, string $path): Response
{
return $response->withRedirect($this->settings['base_url'] . $path);
}
}
10 changes: 5 additions & 5 deletions app/Controllers/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ public function redirects(Request $request, Response $response): Response

if ($request->getParam('afterInstall') !== null && is_dir('install')) {
Session::alert('Installation completed successfully!', 'success');
$this->removeDirectory('install');
removeDirectory('install');
}

return $response->withRedirect('/home');
return $this->redirectTo($response,'/home');
}

/**
Expand Down Expand Up @@ -61,7 +61,7 @@ public function home(Request $request, Response $response, $args): Response
}
$media->mimetype = $mime;
$media->extension = $extension;
$media->size = $this->humanFilesize($size);
$media->size = humanFileSize($size);
}

return $this->view->render(
Expand Down Expand Up @@ -101,7 +101,7 @@ public function system(Request $request, Response $response): Response
'usersCount' => $usersCount,
'mediasCount' => $mediasCount,
'orphanFilesCount' => $orphanFilesCount,
'totalSize' => $this->humanFilesize($totalSize),
'totalSize' => humanFileSize($totalSize),
'post_max_size' => ini_get('post_max_size'),
'upload_max_filesize' => ini_get('upload_max_filesize'),
]);
Expand Down Expand Up @@ -129,6 +129,6 @@ public function getThemes(Request $request, Response $response): Response
public function applyTheme(Request $request, Response $response): Response
{
file_put_contents('static/bootstrap/css/bootstrap.min.css', file_get_contents($request->getParam('css')));
return $response->withRedirect('/system')->withAddedHeader('Cache-Control', 'no-cache, must-revalidate');
return $this->redirectTo($response,'/system')->withAddedHeader('Cache-Control', 'no-cache, must-revalidate');
}
}
12 changes: 6 additions & 6 deletions app/Controllers/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class LoginController extends Controller
public function show(Request $request, Response $response): Response
{
if (Session::get('logged', false)) {
return $response->withRedirect('/home');
return $this->redirectTo($response, '/home');
}
return $this->view->render($response, 'auth/login.twig');
}
Expand All @@ -36,19 +36,19 @@ public function login(Request $request, Response $response): Response

if (!$result || !password_verify($request->getParam('password'), $result->password)) {
Session::alert('Wrong credentials', 'danger');
return $response->withRedirect('/login');
return $this->redirectTo($response, '/login');
}

if (!$result->active) {
Session::alert('Your account is disabled.', 'danger');
return $response->withRedirect('/login');
return $this->redirectTo($response, '/login');
}

Session::set('logged', true);
Session::set('user_id', $result->id);
Session::set('username', $result->username);
Session::set('admin', $result->is_admin);
Session::set('used_space', $this->humanFilesize($this->getUsedSpaceByUser($result->id)));
Session::set('used_space', humanFileSize($this->getUsedSpaceByUser($result->id)));

Session::alert("Welcome, $result->username!", 'info');
$this->logger->info("User $result->username logged in.");
Expand All @@ -57,7 +57,7 @@ public function login(Request $request, Response $response): Response
return $response->withRedirect(Session::get('redirectTo'));
}

return $response->withRedirect('/home');
return $this->redirectTo($response,'/home');
}

/**
Expand All @@ -70,7 +70,7 @@ public function logout(Request $request, Response $response): Response
Session::clear();
Session::set('logged', false);
Session::alert('Goodbye!', 'warning');
return $response->withRedirect('/login');
return $this->redirectTo($response,'/login');
}

}
2 changes: 1 addition & 1 deletion app/Controllers/UploadController.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ public function delete(Request $request, Response $response, $args): Response
} finally {
$this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $args['id']);
$this->logger->info('User ' . Session::get('username') . ' deleted a media.', [$args['id']]);
Session::set('used_space', $this->humanFilesize($this->getUsedSpaceByUser(Session::get('user_id'))));
Session::set('used_space', humanFileSize($this->getUsedSpaceByUser(Session::get('user_id'))));
}
} else {
throw new UnauthorizedException();
Expand Down
28 changes: 14 additions & 14 deletions app/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,22 @@ public function store(Request $request, Response $response): Response
{
if ($request->getParam('email') === null) {
Session::alert('The email is required.', 'danger');
return $response->withRedirect('/user/create');
return $this->redirectTo($response,'/user/create');
}

if ($request->getParam('username') === null) {
Session::alert('The username is required.', 'danger');
return $response->withRedirect('/user/create');
return $this->redirectTo($response,'/user/create');
}

if ($request->getParam('password') === null) {
Session::alert('The password is required.', 'danger');
return $response->withRedirect('/user/create');
return $this->redirectTo($response,'/user/create');
}

if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ?', $request->getParam('username'))->fetch()->count > 0) {
Session::alert('The username already taken.', 'danger');
return $response->withRedirect('/user/create');
return $this->redirectTo($response,'/user/create');
}

do {
Expand All @@ -95,7 +95,7 @@ public function store(Request $request, Response $response): Response
Session::alert("User '{$request->getParam('username')}' created!", 'success');
$this->logger->info('User ' . Session::get('username') . ' created a new user.', [array_diff($request->getParams(), ['password'])]);

return $response->withRedirect('/users');
return $this->redirectTo($response,'/users');
}

/**
Expand Down Expand Up @@ -135,22 +135,22 @@ public function update(Request $request, Response $response, $args): Response

if ($request->getParam('email') === null) {
Session::alert('The email is required.', 'danger');
return $response->withRedirect('/user/' . $args['id'] . '/edit');
return $this->redirectTo($response,'/user/' . $args['id'] . '/edit');
}

if ($request->getParam('username') === null) {
Session::alert('The username is required.', 'danger');
return $response->withRedirect('/user/' . $args['id'] . '/edit');
return $this->redirectTo($response,'/user/' . $args['id'] . '/edit');
}

if ($this->database->query('SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ? AND `username` <> ?', [$request->getParam('username'), $user->username])->fetch()->count > 0) {
Session::alert('The username already taken.', 'danger');
return $response->withRedirect('/user/' . $args['id'] . '/edit');
return $this->redirectTo($response,'/user/' . $args['id'] . '/edit');
}

if ($user->id === Session::get('user_id') && $request->getParam('is_admin') === null) {
Session::alert('You cannot demote yourself.', 'danger');
return $response->withRedirect('/user/' . $args['id'] . '/edit');
return $this->redirectTo($response,'/user/' . $args['id'] . '/edit');
}

if ($request->getParam('password') !== null && !empty($request->getParam('password'))) {
Expand All @@ -175,7 +175,7 @@ public function update(Request $request, Response $response, $args): Response
Session::alert("User '{$request->getParam('username')}' updated!", 'success');
$this->logger->info('User ' . Session::get('username') . " updated $user->id.", [$user, array_diff($request->getParams(), ['password'])]);

return $response->withRedirect('/users');
return $this->redirectTo($response,'/users');

}

Expand All @@ -196,15 +196,15 @@ public function delete(Request $request, Response $response, $args): Response

if ($user->id === Session::get('user_id')) {
Session::alert('You cannot delete yourself.', 'danger');
return $response->withRedirect('/users');
return $this->redirectTo($response,'/users');
}

$this->database->query('DELETE FROM `users` WHERE `id` = ?', $user->id);

Session::alert('User deleted.', 'success');
$this->logger->info('User ' . Session::get('username') . " deleted $user->id.");

return $response->withRedirect('/users');
return $this->redirectTo($response,'/users');
}

/**
Expand Down Expand Up @@ -253,7 +253,7 @@ public function profileEdit(Request $request, Response $response, $args): Respon

if ($request->getParam('email') === null) {
Session::alert('The email is required.', 'danger');
return $response->withRedirect('/profile');
return $this->redirectTo($response,'/profile');
}

if ($request->getParam('password') !== null && !empty($request->getParam('password'))) {
Expand All @@ -272,7 +272,7 @@ public function profileEdit(Request $request, Response $response, $args): Respon
Session::alert('Profile updated successfully!', 'success');
$this->logger->info('User ' . Session::get('username') . " updated profile of $user->id.");

return $response->withRedirect('/profile');
return $this->redirectTo($response,'/profile');
}

/**
Expand Down
4 changes: 2 additions & 2 deletions app/Middleware/AuthMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ public function __invoke(Request $request, Response $response, callable $next)
{
if (!Session::get('logged', false)) {
Session::set('redirectTo', (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
return $response->withRedirect('/login');
return $response->withRedirect($this->container->settings['base_url'] . '/login');
}

if (!$this->container->database->query('SELECT `id`, `active` FROM `users` WHERE `id` = ? LIMIT 1', [Session::get('user_id')])->fetch()->active) {
Session::alert('Your account is not active anymore.', 'danger');
Session::set('logged', false);
Session::set('redirectTo', (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
return $response->withRedirect('/login');
return $response->withRedirect($this->container->settings['base_url'] . '/login');
}

return $next($request, $response);
Expand Down
51 changes: 51 additions & 0 deletions app/helpers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

require __DIR__ . '/../vendor/autoload.php';

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];
}
}

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;
}
}

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);
}
}
}
}
19 changes: 4 additions & 15 deletions bin/clean
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,18 @@ if (php_sapi_name() !== 'cli') {
die();
}

function cleanDir($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);
}
}
}

$action = isset($argv[1]) ? $argv[1] : 'all';

switch ($action) {
case 'cache':
cleanDir(__DIR__ . '/../resources/cache');
cleanDirectory(__DIR__ . '/../resources/cache');
break;
case 'sessions':
cleanDir(__DIR__ . '/../resources/sessions');
cleanDirectory(__DIR__ . '/../resources/sessions');
break;
case 'all':
cleanDir(__DIR__ . '/../resources/cache');
cleanDir(__DIR__ . '/../resources/sessions');
cleanDirectory(__DIR__ . '/../resources/cache');
cleanDirectory(__DIR__ . '/../resources/sessions');
break;
case 'help':
default:
Expand Down
Loading

0 comments on commit 5c362d7

Please sign in to comment.