Vis: 000test.php

Retour

<?php
// Henter automatisk det gjeldende filnavnet
$scriptName = basename(__FILE__);

/*
================================================================================
KONFIGURASJON OG PASSORDBESKYTTELSE
================================================================================
*/

$title = 'Arkivet til Trondhjems Turnforening';

// --- PASSORDBESKYTTELSE ---
$enableAuth = false;          // true for å kreve passord, false for å slå av
$authUser   = 'TT';       // Brukernavn
$authPass   = 'tt70131858'; // Passord

// --- TILLATELSER FOR HANDLINGER ---
$allowUpload       = true;   // Tillat opplasting av filer (true / false)
$allowDelete       = false;   // Tillat sletting av filer og tomme mapper (true = på, false = av)
$allowCreateFolder = true;   // Tillat oppretting av nye mapper (true / false)

// Visningsvalg
$showThumbnails    = true;  
$showFileSize      = true;  
$showLastModified  = true;  
$showHiddenFiles   = false; 
$forceDownload     = false; 

$defaultSortBy     = 'name';
$defaultSortOrder  = 'asc';

$ignoredFiles = array(
    $scriptName,
    '.htaccess',
    '.htpasswd',
    '.DS_Store',
    'Thumbs.db',
    'error_log'
);

$ignoredFolders = array(
    '.git',
    'cgi-bin'
);

$restrictFileTypes = true;
$allowableFileTypes = array(
    'pdf', 'doc', 'docx', 'odt', 'rtf', 'txt',
    'xls', 'xlsx', 'ods', 'csv', 'ppt', 'pptx',
    'jpg', 'jpeg', 'png', 'gif', 'webp', 'zip'
);

/*
================================================================================
AUTENTISERINGS- OG SESJONSLOGIKK
================================================================================
*/
session_start();

if (isset($_GET['logout'])) {
    unset($_SESSION['tt_logged_in']);
    header('Location: ' . $scriptName);
    exit;
}

if ($enableAuth && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login_pass'])) {
    if ($_POST['login_user'] === $authUser && $_POST['login_pass'] === $authPass) {
        $_SESSION['tt_logged_in'] = true;
        header('Location: ' . $scriptName . (isset($_GET['dir']) ? '?dir=' . urlencode($_GET['dir']) : ''));
        exit;
    } else {
        $loginError = 'Feil brukernavn eller passord.';
    }
}

$isLoggedIn = !$enableAuth || (isset($_SESSION['tt_logged_in']) && $_SESSION['tt_logged_in'] === true);

/*
================================================================================
SYSTEMLOGIKK
================================================================================
*/
$message = '';
$error = '';
$baseDir = realpath(__DIR__);
$relPath = isset($_GET['dir']) ? trim($_GET['dir'], '/\\') : '';
$currentDir = realpath($baseDir . ($relPath !== '' ? DIRECTORY_SEPARATOR . $relPath : ''));

if ($isLoggedIn) {
    if ($currentDir === false || strpos($currentDir, $baseDir) !== 0) {
        $currentDir = $baseDir;
        $relPath = '';
    }

    // Opprett ny mappe
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_folder']) && $allowCreateFolder) {
        $folderName = preg_replace('/[^a-zA-Z0-9æøåÆØÅ _-]/u', '', trim($_POST['new_folder']));
        if ($folderName !== '' && !in_array($folderName, $ignoredFolders)) {
            $targetFolder = $currentDir . DIRECTORY_SEPARATOR . $folderName;
            if (!file_exists($targetFolder)) {
                if (mkdir($targetFolder, 0755)) {
                    $message = "Mappen «" . htmlspecialchars($folderName) . "» ble opprettet.";
                } else {
                    $error = "Kunne ikke opprette mappen. Sjekk skriverettigheter.";
                }
            } else {
                $error = "En mappe eller fil med dette navnet finnes allerede.";
            }
        }
    }

    // Last opp fil
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload_file']) && $allowUpload) {
        if ($_FILES['upload_file']['error'] === UPLOAD_ERR_OK) {
            $fileName = basename($_FILES['upload_file']['name']);
            $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

            if ($fileName === $scriptName) {
                $error = "Du kan ikke overskrive selve filbehandleren.";
            } elseif ($restrictFileTypes && !in_array($ext, $allowableFileTypes)) {
                $error = "Filtypen ." . htmlspecialchars($ext) . " er ikke tillatt.";
            } else {
                $targetFile = $currentDir . DIRECTORY_SEPARATOR . $fileName;
                if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $targetFile)) {
                    $message = "Filen «" . htmlspecialchars($fileName) . "» ble lastet opp.";
                } else {
                    $error = "Feil ved opplasting av fil.";
                }
            }
        } else {
            $error = "Feil under opplasting.";
        }
    }

    // Slett fil eller mappe (Kjører kun hvis $allowDelete er satt til true)
    if (isset($_GET['delete']) && $allowDelete) {
        $deleteItem = basename($_GET['delete']);
        if (!in_array($deleteItem, $ignoredFiles) && !in_array($deleteItem, $ignoredFolders)) {
            $targetDelete = $currentDir . DIRECTORY_SEPARATOR . $deleteItem;
            if (file_exists($targetDelete)) {
                if (is_dir($targetDelete)) {
                    @rmdir($targetDelete) ? $message = "Mappen ble slettet." : $error = "Kunne ikke slette mappen (må være tom).";
                } else {
                    @unlink($targetDelete) ? $message = "Filen ble slettet." : $error = "Kunne ikke slette filen.";
                }
            }
        }
    }
}

function formatSize($bytes) {
    if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2, ',', ' ') . ' GB';
    if ($bytes >= 1048576) return number_format($bytes / 1048576, 2, ',', ' ') . ' MB';
    if ($bytes >= 1024) return number_format($bytes / 1024, 1, ',', ' ') . ' KB';
    return $bytes . ' B';
}

$sortBy    = isset($_GET['sort']) && in_array($_GET['sort'], ['name', 'size', 'date']) ? $_GET['sort'] : $defaultSortBy;
$sortOrder = isset($_GET['order']) && in_array($_GET['order'], ['asc', 'desc']) ? $_GET['order'] : $defaultSortOrder;

$folders = [];
$files = [];

if ($isLoggedIn) {
    $items = scandir($currentDir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        if (!$showHiddenFiles && strpos($item, '.') === 0) continue;

        $fullPath = $currentDir . DIRECTORY_SEPARATOR . $item;

        if (is_dir($fullPath)) {
            if (in_array($item, $ignoredFolders)) continue;
            $folders[] = ['name' => $item, 'date' => filemtime($fullPath), 'size' => 0];
        } else {
            if (in_array($item, $ignoredFiles)) continue;
            $ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
            if ($restrictFileTypes && !in_array($ext, $allowableFileTypes)) continue;

            $files[] = ['name' => $item, 'ext' => $ext, 'date' => filemtime($fullPath), 'size' => filesize($fullPath)];
        }
    }

    $sorter = function($a, $b) use ($sortBy, $sortOrder) {
        if ($sortBy === 'size') $cmp = $a['size'] <=> $b['size'];
        elseif ($sortBy === 'date') $cmp = $a['date'] <=> $b['date'];
        else $cmp = strnatcasecmp($a['name'], $b['name']);
        return ($sortOrder === 'desc') ? -$cmp : $cmp;
    };

    usort($folders, $sorter);
    usort($files, $sorter);
}

$selfUrl = htmlspecialchars($scriptName);
$nextOrder = ($sortOrder === 'asc') ? 'desc' : 'asc';
$dirParam = ($relPath !== '') ? 'dir=' . urlencode($relPath) . '&' : '';
?>
<!DOCTYPE html>
<html lang="no">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($title); ?> – Basert på Evoluted Directory Listing</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: #f4f6f9;
            color: #333;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1050px;
            margin: 0 auto;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        header {
            background-color: #004080;
            color: #fff;
            padding: 20px 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        header h1 { margin: 0; font-size: 1.5rem; }
        header .subtitle { font-size: 0.9rem; opacity: 0.85; }
        .logout-btn {
            background: rgba(255,255,255,0.15);
            color: #fff;
            padding: 6px 12px;
            border-radius: 4px;
            text-decoration: none;
            font-size: 0.85rem;
            border: 1px solid rgba(255,255,255,0.3);
        }
        .logout-btn:hover { background: rgba(255,255,255,0.25); }
        .login-box {
            max-width: 400px;
            margin: 60px auto;
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
            text-align: center;
        }
        .login-box h2 { margin-top: 0; color: #004080; }
        .login-box input {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #ced4da;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .login-box button {
            width: 100%;
            padding: 10px;
            background: #004080;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
        }
        .login-box button:hover { background: #002d5a; }
        .breadcrumb {
            background: #e9ecef;
            padding: 10px 25px;
            font-size: 0.95rem;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 10px;
        }
        .breadcrumb a { color: #004080; text-decoration: none; font-weight: 500; }
        .breadcrumb a:hover { text-decoration: underline; }
        .stats { font-size: 0.85rem; color: #555; }
        .alert { padding: 12px 25px; margin: 15px 25px 0; border-radius: 4px; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .toolbar {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            padding: 15px 25px;
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
        .toolbar form { display: flex; gap: 8px; align-items: center; }
        input[type="text"], input[type="file"], input[type="password"] {
            padding: 6px 10px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 0.9rem;
        }
        button {
            padding: 7px 14px;
            background-color: #004080;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
        }
        button:hover { background-color: #002d5a; }
        table { width: 100%; border-collapse: collapse; }
        th {
            background-color: #e2e8f0;
            color: #1e293b;
            font-weight: 700;
            text-align: left;
            padding: 12px 25px;
            border-bottom: 2px solid #cbd5e1;
        }
        th a { color: #1e293b; text-decoration: none; display: inline-flex; align-items: center; gap: 4px; }
        th a:hover { color: #004080; text-decoration: underline; }
        td { padding: 10px 25px; border-bottom: 1px solid #edf2f7; font-size: 0.95rem; vertical-align: middle; }
        tr:hover { background-color: #f8fafc; }
        a.item-link { color: #1e293b; text-decoration: none; font-weight: 500; display: inline-flex; align-items: center; gap: 8px; }
        a.item-link:hover { color: #004080; text-decoration: underline; }
        .thumb { width: 24px; height: 24px; object-fit: cover; border-radius: 3px; border: 1px solid #cbd5e1; }
        .icon::before { display: inline-block; width: 24px; text-align: center; }
        .icon-folder::before { content: "📁"; }
        .icon-up::before { content: "⬆️"; }
        .icon-pdf::before { content: "📕"; }
        .icon-doc::before { content: "📘"; }
        .icon-xls::before, .icon-csv::before { content: "📗"; }
        .icon-ppt::before { content: "📙"; }
        .icon-img::before { content: "🖼️"; }
        .icon-media::before { content: "🎬"; }
        .icon-zip::before { content: "📦"; }
        .icon-code::before { content: "💻"; }
        .icon-file::before { content: "📄"; }
        .btn-delete {
            color: #dc3545;
            text-decoration: none;
            font-size: 0.85rem;
            padding: 3px 8px;
            border: 1px solid #dc3545;
            border-radius: 4px;
        }
        .btn-delete:hover { background: #dc3545; color: #fff; }
        footer {
            text-align: center;
            padding: 15px;
            font-size: 0.85rem;
            color: #6c757d;
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }
    </style>
</head>
<body>

<?php if (!$isLoggedIn): ?>
    <!-- INNLOGGINGSSIDE -->
    <div class="login-box">
        <h2>Logg inn i arkivet</h2>
        <div style="font-size: 0.85rem; color: #666; margin-bottom: 15px;"><?php echo htmlspecialchars($title); ?></div>
        
        <?php if (isset($loginError)): ?>
            <div class="alert alert-error" style="margin: 0 0 15px 0;"><?php echo $loginError; ?></div>
        <?php endif; ?>

        <form method="post" action="">
            <input type="text" name="login_user" placeholder="Brukernavn" required autofocus>
            <input type="password" name="login_pass" placeholder="Passord" required>
            <button type="submit">Logg inn</button>
        </form>
    </div>
<?php else: ?>
    <!-- HOVEDINNHOLD (FILBEHANDLER) -->
    <div class="container">
        <header>
            <div>
                <h1><?php echo htmlspecialchars($title); ?></h1>
                <div class="subtitle">Basert på Evoluted Directory Listing</div>
            </div>
            <?php if ($enableAuth): ?>
                <div>
                    <a class="logout-btn" href="<?php echo $selfUrl; ?>?logout=1">Logg ut</a>
                </div>
            <?php endif; ?>
        </header>

        <div class="breadcrumb">
            <div>
                <strong>Sti:</strong> <a href="<?php echo $selfUrl; ?>">Hovedmappe</a>
                <?php
                if ($relPath !== '') {
                    $parts = explode('/', str_replace('\\', '/', $relPath));
                    $accPath = '';
                    foreach ($parts as $part) {
                        $accPath .= ($accPath === '' ? '' : '/') . $part;
                        echo ' / <a href="' . $selfUrl . '?dir=' . urlencode($accPath) . '">' . htmlspecialchars($part) . '</a>';
                    }
                }
                ?>
            </div>
            <div class="stats">
                <?php echo count($folders); ?> mapper, <?php echo count($files); ?> filer
            </div>
        </div>

        <?php if ($message !== ''): ?>
            <div class="alert alert-success"><?php echo $message; ?></div>
        <?php endif; ?>
        <?php if ($error !== ''): ?>
            <div class="alert alert-error"><?php echo $error; ?></div>
        <?php endif; ?>

        <?php if ($allowUpload || $allowCreateFolder): ?>
        <div class="toolbar">
            <?php if ($allowUpload): ?>
            <form method="post" enctype="multipart/form-data">
                <input type="file" name="upload_file" required>
                <button type="submit">Last opp fil</button>
            </form>
            <?php endif; ?>

            <?php if ($allowCreateFolder): ?>
            <form method="post">
                <input type="text" name="new_folder" placeholder="Nytt mappenavn..." required>
                <button type="submit">Opprett mappe</button>
            </form>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <table>
            <thead>
                <tr>
                    <th>
                        <a href="<?php echo $selfUrl . '?' . $dirParam . 'sort=name&order=' . ($sortBy === 'name' ? $nextOrder : 'asc'); ?>">
                            Navn <?php echo $sortBy === 'name' ? ($sortOrder === 'asc' ? '▲' : '▼') : ''; ?>
                        </a>
                    </th>
                    <?php if ($showFileSize): ?>
                    <th>
                        <a href="<?php echo $selfUrl . '?' . $dirParam . 'sort=size&order=' . ($sortBy === 'size' ? $nextOrder : 'asc'); ?>">
                            Størrelse <?php echo $sortBy === 'size' ? ($sortOrder === 'asc' ? '▲' : '▼') : ''; ?>
                        </a>
                    </th>
                    <?php endif; ?>
                    <?php if ($showLastModified): ?>
                    <th>
                        <a href="<?php echo $selfUrl . '?' . $dirParam . 'sort=date&order=' . ($sortBy === 'date' ? $nextOrder : 'desc'); ?>">
                            Sist endret <?php echo $sortBy === 'date' ? ($sortOrder === 'asc' ? '▲' : '▼') : ''; ?>
                        </a>
                    </th>
                    <?php endif; ?>
                    <?php if ($allowDelete): ?><th>Handling</th><?php endif; ?>
                </tr>
            </thead>
            <tbody>
                <?php
                $colCount = 1 + ($showFileSize ? 1 : 0) + ($showLastModified ? 1 : 0) + ($allowDelete ? 1 : 0);
                if ($relPath !== ''):
                    $parentDir = dirname($relPath);
                    $parentUrl = ($parentDir === '.' || $parentDir === '') ? $selfUrl : $selfUrl . '?dir=' . urlencode($parentDir);
                ?>
                <tr>
                    <td colspan="<?php echo $colCount; ?>">
                        <a class="item-link icon icon-up" href="<?php echo $parentUrl; ?>">.. (Tilbake ett nivå)</a>
                    </td>
                </tr>
                <?php endif; ?>

                <?php foreach ($folders as $folder):
                    $fName = $folder['name'];
                    $nextDir = ($relPath === '' ? '' : $relPath . '/') . $fName;
                    $folderUrl = $selfUrl . '?dir=' . urlencode($nextDir);
                ?>
                <tr>
                    <td><a class="item-link icon icon-folder" href="<?php echo $folderUrl; ?>"><?php echo htmlspecialchars($fName); ?></a></td>
                    <?php if ($showFileSize): ?><td>Mappe</td><?php endif; ?>
                    <?php if ($showLastModified): ?><td><?php echo date("d.m.Y H:i", $folder['date']); ?></td><?php endif; ?>
                    <?php if ($allowDelete): ?>
                    <td>
                        <a class="btn-delete" href="<?php echo $selfUrl . '?dir=' . urlencode($relPath) . '&delete=' . urlencode($fName); ?>" onclick="return confirm('Slette tom mappe?');">Slett</a>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endforeach; ?>

                <?php foreach ($files as $file):
                    $fName = $file['name'];
                    $ext = $file['ext'];
                    $fileHref = ($relPath === '' ? '' : rawurlencode($relPath) . '/') . rawurlencode($fName);
                    $fileHref = str_replace('%2F', '/', $fileHref);

                    $isImage = in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp']);
                    $iconClass = 'icon-file';
                    if ($ext === 'pdf') $iconClass = 'icon-pdf';
                    elseif (in_array($ext, ['doc', 'docx', 'odt', 'rtf', 'txt'])) $iconClass = 'icon-doc';
                    elseif (in_array($ext, ['xls', 'xlsx', 'ods', 'csv'])) $iconClass = 'icon-xls';
                    elseif (in_array($ext, ['ppt', 'pptx', 'odp'])) $iconClass = 'icon-ppt';
                    elseif ($isImage || $ext === 'svg') $iconClass = 'icon-img';
                    elseif (in_array($ext, ['mp3', 'wav', 'mp4', 'mov'])) $iconClass = 'icon-media';
                    elseif (in_array($ext, ['zip', 'rar', '7z', 'tar', 'gz'])) $iconClass = 'icon-zip';
                    elseif (in_array($ext, ['html', 'htm', 'php', 'pl', 'css', 'js'])) $iconClass = 'icon-code';
                ?>
                <tr>
                    <td>
                        <?php if ($showThumbnails && $isImage): ?>
                            <a class="item-link" href="<?php echo $fileHref; ?>" <?php echo $forceDownload ? 'download' : 'target="_blank"'; ?>>
                                <img class="thumb" src="<?php echo $fileHref; ?>" alt="">
                                <?php echo htmlspecialchars($fName); ?>
                            </a>
                        <?php else: ?>
                            <a class="item-link icon <?php echo $iconClass; ?>" href="<?php echo $fileHref; ?>" <?php echo $forceDownload ? 'download' : 'target="_blank"'; ?>>
                                <?php echo htmlspecialchars($fName); ?>
                            </a>
                        <?php endif; ?>
                    </td>
                    <?php if ($showFileSize): ?><td><?php echo formatSize($file['size']); ?></td><?php endif; ?>
                    <?php if ($showLastModified): ?><td><?php echo date("d.m.Y H:i", $file['date']); ?></td><?php endif; ?>
                    <?php if ($allowDelete): ?>
                    <td>
                        <a class="btn-delete" href="<?php echo $selfUrl . '?dir=' . urlencode($relPath) . '&delete=' . urlencode($fName); ?>" onclick="return confirm('Er du sikker på at du vil slette filen?');">Slett</a>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endforeach; ?>

                <?php if (empty($folders) && empty($files)): ?>
                <tr>
                    <td colspan="<?php echo $colCount; ?>" style="text-align:center; color:#6c757d; padding: 25px;">Ingen filer eller mapper å vise.</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <footer>
            Modified 2026 Harald Bjerkan &ndash; Trondhjems Turnforening<br>
            <small>Based on Evoluted Directory Listing</small>
        </footer>
    </div>
<?php endif; ?>

</body>
</html>