<?PHP
/**
 * This script offers functionality related to uploading and deleting files.
 *
 * @author Joshua Ramon Enslin <joshua@jrenslin.de>
 */

/*
 * Require files and ensure environment.
 */

require_once __DIR__ . "/inc/functions.php";

ensureEnvironment();                                    // Ensure existence of system files.
$translations = loadLanguage($settings['defaultLang']); // Load translations.
ensureBackendEnv();                                     // Ensure session is started etc.
$pages = loadPages();                                   // Load overview of pages.

/*
 * Load data.
 */

// Check for vars.
loadHttpToGlobals(["subject", "task", "backTo"]);
if (!isset($task)) $task = "list";

define("fileDir", __DIR__ . "/../files");

if ($task == "list") {

    $files = scanDirConts(fileDir);

    $output = [];
    foreach ($files as $file) {
        $output[] = [
            "name"  => $file,
            "type"  => mime_content_type(fileDir . "/$file"),
            "size"  => filesize(fileDir . "/$file"),
            "mtime" => filemtime(fileDir . "/$file"),
        ];
    }

    if (isset($_GET['sort'])) {
        if ($_GET['sort'] == "name") {
            usort($output, function(array $a, array $b) {
                return strnatcmp($a['name'], $b['name']);
            });
        }
        else if ($_GET['sort'] == "type") {
            usort($output, function(array $a, array $b) {
                return strnatcmp($a['type'], $b['type']);
            });
        }
        else if ($_GET['sort'] == "size") {
            usort($output, function(array $a, array $b) {
                if ($a['size'] == $b['size']) return 0;
                return ($a['size'] > $b['size']) ? -1 : 1;
            });
        }
        else if ($_GET['sort'] == "mtime") {
            usort($output, function(array $a, array $b) {
                if ($a['mtime'] == $b['mtime']) return 0;
                return ($a['mtime'] > $b['mtime']) ? -1 : 1;
            });
        }
    }

    echo json_encode($output);
    return;

}
else if ($task == "upload") {

    $allowedFiletypes = [
        "image/png",
        "image/jpeg",
    ];

    $uploaddir = fileDir . '/';
    $uploadfile = $uploaddir . basename($_FILES['file']['name']);

    // Whitelist of allowed types.
    if (!in_array($_FILES['file']['type'], $allowedFiletypes)) {
        printErrorPage($translations['filetypeNotWhitelisted']);
        return;
    }

    if (filesize($_FILES['file']['tmp_name']) > 300000) {
        printErrorPage($translations['fileTooLarge']);
        return;
    }

    if (!(move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile))) {
        printErrorPage($translations['fileUploadError']);
        return;
    }

    $_SESSION["editHistory"] = ["changesStored", $translations['uploadedFile']];

    // Refer back
    if (isset($backTo)) header('Location: ' . $backTo);
    else header('Location: ./');
    return;

}
else if ($task == "delete") {

    if (!is_file(fileDir . "/$subject")) {
        printErrorPage($translations['fileDoesNotExist']); return;
    }

    unlink(fileDir . "/$subject");

    $_SESSION["editHistory"] = ["changesDeleted", $translations['deletedFile'] . " $subject"];

    // Refer back
    if (isset($backTo)) header('Location: ' . $backTo);
    else header('Location: ./');
    return;

}


?>