<?php
declare(strict_types=1);

/*
 * Hosting Provider Check Monthly
 * PHP 7.4+ with the ZIP extension.
 * Install only on a server you administer. Use HTTPS.
 */

const ADMIN_PASSWORD = '9090'; // Replace with your own strong password.
const MAX_EDIT_BYTES = 1048576;          // 1 MiB
const MAX_UPLOAD_BYTES = 536870912;      // 512 MiB per file
const MAX_EXTRACT_BYTES = 536870912;     // 512 MiB total uncompressed
const MAX_ZIP_ENTRIES = 10000;

ini_set('session.use_strict_mode', '1');
session_set_cookie_params([
    'httponly' => true,
    'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
    'samesite' => 'Strict',
]);
session_start();

header('Content-Type: text/html; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('Referrer-Policy: no-referrer');

function h($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function validName($name): bool
{
    return is_string($name)
        && $name !== ''
        && $name !== '.'
        && $name !== '..'
        && !preg_match('/[\/\\\\\x00-\x1F\x7F]/', $name);
}

function isAbsolutePath(string $path): bool
{
    return isset($path[0]) && (
        $path[0] === '/'
        || preg_match('~^[A-Za-z]:[\\\\/]~', $path) === 1
        || substr($path, 0, 2) === '\\\\'
    );
}

function resolveDirectory(string $path, string $base): string
{
    $path = trim($path);
    if ($path === '') {
        $path = '.';
    }

    $candidate = isAbsolutePath($path)
        ? $path
        : $base . DIRECTORY_SEPARATOR . $path;

    $resolved = realpath($candidate);

    if ($resolved === false || !is_dir($resolved)) {
        throw new RuntimeException('Destination directory does not exist or is inaccessible.');
    }

    return $resolved;
}

function childPath(string $directory, $name): ?string
{
    if (!validName($name)) {
        return null;
    }

    $path = $directory . DIRECTORY_SEPARATOR . $name;
    return (file_exists($path) || is_link($path)) ? $path : null;
}

function pageUrl(string $directory, ?string $edit = null): string
{
    $query = ['dir' => $directory];
    if ($edit !== null) {
        $query['edit'] = $edit;
    }
    return '?' . http_build_query($query);
}

function isManagerFile(string $path): bool
{
    $a = realpath($path);
    $b = realpath(__FILE__);
    return $a !== false && $b !== false && $a === $b;
}

function editableFile(string $path): bool
{
    $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    $size = @filesize($path);

    return is_file($path)
        && !is_link($path)
        && !isManagerFile($path)
        && $size !== false
        && $size <= MAX_EDIT_BYTES
        && in_array($extension, [
            'txt', 'md', 'log', 'csv', 'json', 'xml',
            'html', 'htm', 'css', 'js', 'php',
            'ini', 'conf', 'yaml', 'yml', 'sql', 'py'
        ], true);
}

function deleteTree(string $path): void
{
    if (is_link($path) || is_file($path)) {
        if (!@unlink($path)) {
            throw new RuntimeException('Could not delete: ' . $path);
        }
        return;
    }

    if (!is_dir($path)) {
        throw new RuntimeException('Unsupported item: ' . $path);
    }

    $children = @scandir($path);
    if ($children === false) {
        throw new RuntimeException('Could not read: ' . $path);
    }

    foreach ($children as $child) {
        if ($child !== '.' && $child !== '..') {
            deleteTree($path . DIRECTORY_SEPARATOR . $child);
        }
    }

    if (!@rmdir($path)) {
        throw new RuntimeException('Could not remove directory: ' . $path);
    }
}

function applyBulkPermissions(string $directory): array
{
    $stack = [$directory];
    $changed = 0;
    $failed = 0;
    $skippedLinks = 0;

    while ($stack) {
        $current = array_pop($stack);

        if (is_link($current)) {
            $skippedLinks++;
            continue;
        }

        if (@chmod($current, 0775)) {
            $changed++;
        } else {
            $failed++;
        }

        if (!is_dir($current)) {
            continue;
        }

        $items = @scandir($current);
        if ($items === false) {
            $failed++;
            continue;
        }

        foreach ($items as $item) {
            if ($item !== '.' && $item !== '..') {
                $stack[] = $current . DIRECTORY_SEPARATOR . $item;
            }
        }
    }

    return [$changed, $failed, $skippedLinks];
}

function saveTextFile(string $path, string $content): void
{
    if (strlen($content) > MAX_EDIT_BYTES) {
        throw new RuntimeException('Edited file exceeds the size limit.');
    }

    $temp = @tempnam(dirname($path), '.fm-');
    if ($temp === false) {
        throw new RuntimeException('Could not create a temporary file.');
    }

    try {
        $written = @file_put_contents($temp, $content, LOCK_EX);
        if ($written === false || $written !== strlen($content)) {
            throw new RuntimeException('Could not write the complete file.');
        }

        $oldMode = @fileperms($path);
        $mode = $oldMode === false ? 0644 : ($oldMode & 0777);

        if (!@chmod($temp, $mode) || !@rename($temp, $path)) {
            throw new RuntimeException('Could not replace the edited file.');
        }
    } finally {
        if (file_exists($temp)) {
            @unlink($temp);
        }
    }
}

function zipEntryParts(string $name): array
{
    if ($name === ''
        || $name[0] === '/'
        || preg_match('/[\\\\:\x00-\x1F\x7F]/', $name)
    ) {
        throw new RuntimeException('Unsafe ZIP entry: ' . $name);
    }

    $isDirectory = substr($name, -1) === '/';
    $trimmed = $isDirectory ? substr($name, 0, -1) : $name;
    $parts = explode('/', $trimmed);

    foreach ($parts as $part) {
        if ($part === '' || $part === '.' || $part === '..') {
            throw new RuntimeException('Unsafe ZIP entry: ' . $name);
        }
    }

    return [$parts, $isDirectory];
}

function checkExistingTarget(string $base, array $parts, bool $isDirectory): void
{
    $path = $base;
    $last = count($parts) - 1;

    foreach ($parts as $index => $part) {
        $path .= DIRECTORY_SEPARATOR . $part;

        if (is_link($path)) {
            throw new RuntimeException('ZIP destination contains a symbolic link: ' . $path);
        }

        if (!file_exists($path)) {
            continue;
        }

        if ($index < $last || $isDirectory) {
            if (!is_dir($path)) {
                throw new RuntimeException('A directory conflicts with: ' . $path);
            }
        } elseif (!is_file($path)) {
            throw new RuntimeException('A file conflicts with: ' . $path);
        }
    }
}

function ensureDirectories(string $base, array $parts): void
{
    $path = $base;

    foreach ($parts as $part) {
        $path .= DIRECTORY_SEPARATOR . $part;

        if (is_link($path)) {
            throw new RuntimeException('Symbolic link in destination: ' . $path);
        }

        if (is_dir($path)) {
            continue;
        }

        if (file_exists($path) || !@mkdir($path, 0775)) {
            throw new RuntimeException('Could not create directory: ' . $path);
        }
    }
}

/*
 * Extract directly into the selected existing directory.
 * Matching regular files are replaced; no "-unpacked" folder is added.
 */
function extractZipSafely(string $archivePath, string $destination): array
{
    if (!class_exists('ZipArchive')) {
        throw new RuntimeException('The PHP ZIP extension is not installed.');
    }

    $zip = new ZipArchive();
    if ($zip->open($archivePath) !== true) {
        throw new RuntimeException('Could not open the ZIP archive.');
    }

    try {
        if ($zip->numFiles > MAX_ZIP_ENTRIES) {
            throw new RuntimeException('ZIP contains too many entries.');
        }

        $entries = [];
        $seen = [];
        $types = [];
        $totalSize = 0;

        // Preflight: check every entry before changing any destination file.
        for ($i = 0; $i < $zip->numFiles; $i++) {
            $stat = $zip->statIndex($i);
            if ($stat === false || !isset($stat['name'], $stat['size'])) {
                throw new RuntimeException('Could not inspect a ZIP entry.');
            }

            $name = (string)$stat['name'];
            [$parts, $isDirectory] = zipEntryParts($name);
            $size = (int)$stat['size'];

            if ($size < 0 || $size > MAX_EXTRACT_BYTES - $totalSize) {
                throw new RuntimeException('ZIP exceeds the extraction size limit.');
            }
            $totalSize += $size;

            $key = implode('/', $parts);
            if (DIRECTORY_SEPARATOR === '\\') {
                $key = strtolower($key);
            }

            if (isset($seen[$key])) {
                throw new RuntimeException('Duplicate ZIP entry: ' . $name);
            }
            $seen[$key] = true;
            $types[$key] = $isDirectory ? 'directory' : 'file';

            $opsys = 0;
            $attributes = 0;
            if ($zip->getExternalAttributesIndex($i, $opsys, $attributes)
                && $opsys === ZipArchive::OPSYS_UNIX
            ) {
                $kind = ($attributes >> 16) & 0170000;
                $expected = $isDirectory ? 0040000 : 0100000;

                if ($kind !== 0 && $kind !== $expected) {
                    throw new RuntimeException('ZIP contains a link or special file: ' . $name);
                }
            }

            checkExistingTarget($destination, $parts, $isDirectory);

            $target = $destination . DIRECTORY_SEPARATOR
                . implode(DIRECTORY_SEPARATOR, $parts);

            if (!$isDirectory
                && (isManagerFile($target) || isManagerFile($archivePath)
                    && realpath($target) === realpath($archivePath))
            ) {
                throw new RuntimeException('ZIP cannot replace this manager or its own archive.');
            }

            $entries[] = [
                'name' => $name,
                'parts' => $parts,
                'directory' => $isDirectory,
                'size' => $size,
            ];
        }

        // Reject an archive that declares a file as another entry's parent.
        foreach ($entries as $entry) {
            $parts = $entry['parts'];
            for ($n = 1; $n < count($parts); $n++) {
                $parentKey = implode('/', array_slice($parts, 0, $n));
                if (DIRECTORY_SEPARATOR === '\\') {
                    $parentKey = strtolower($parentKey);
                }
                if (($types[$parentKey] ?? null) === 'file') {
                    throw new RuntimeException('ZIP has a file/directory conflict.');
                }
            }
        }

        $created = 0;
        $overwritten = 0;
        $directories = 0;
        $actualTotal = 0;

        foreach ($entries as $entry) {
            $parts = $entry['parts'];

            if ($entry['directory']) {
                ensureDirectories($destination, $parts);
                $directories++;
                continue;
            }

            ensureDirectories($destination, array_slice($parts, 0, -1));

            $target = $destination . DIRECTORY_SEPARATOR
                . implode(DIRECTORY_SEPARATOR, $parts);

            // Check again in case the filesystem changed after preflight.
            checkExistingTarget($destination, $parts, false);

            $alreadyExists = is_file($target);
            $oldMode = $alreadyExists ? @fileperms($target) : false;
            $mode = $oldMode === false ? 0644 : ($oldMode & 0777);

            $input = $zip->getStream($entry['name']);
            if ($input === false) {
                throw new RuntimeException('Could not read ZIP entry: ' . $entry['name']);
            }

            $temp = @tempnam(dirname($target), '.fm-');
            if ($temp === false) {
                fclose($input);
                throw new RuntimeException('Could not create a temporary extraction file.');
            }

            try {
                $output = @fopen($temp, 'wb');
                if ($output === false) {
                    throw new RuntimeException('Could not open the temporary file.');
                }

                try {
                    $fileBytes = 0;

                    while (!feof($input)) {
                        $chunk = fread($input, 65536);
                        if ($chunk === false || ($chunk === '' && !feof($input))) {
                            throw new RuntimeException('ZIP read failed.');
                        }

                        $length = strlen($chunk);
                        $fileBytes += $length;
                        $actualTotal += $length;

                        if ($fileBytes > $entry['size']
                            || $actualTotal > MAX_EXTRACT_BYTES
                        ) {
                            throw new RuntimeException('ZIP exceeds its declared size limit.');
                        }

                        $offset = 0;
                        while ($offset < $length) {
                            $written = fwrite($output, substr($chunk, $offset));
                            if ($written === false || $written === 0) {
                                throw new RuntimeException('Extraction write failed.');
                            }
                            $offset += $written;
                        }
                    }

                    if ($fileBytes !== $entry['size'] || !fflush($output)) {
                        throw new RuntimeException('ZIP entry is incomplete.');
                    }
                } finally {
                    fclose($output);
                }

                if (!@chmod($temp, $mode)) {
                    throw new RuntimeException('Could not set extracted file permissions.');
                }

                // On platforms where replacement is permitted, rename replaces
                // the existing regular file only after the new file is complete.
                if (!@rename($temp, $target)) {
                    throw new RuntimeException('Could not replace file: ' . $target);
                }

                if ($alreadyExists) {
                    $overwritten++;
                } else {
                    $created++;
                }
            } finally {
                fclose($input);
                if (file_exists($temp)) {
                    @unlink($temp);
                }
            }
        }

        return [$created, $overwritten, $directories];
    } finally {
        $zip->close();
    }
}

// Authentication
$loginError = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    $blockedUntil = (int)($_SESSION['blocked_until'] ?? 0);

    if ($blockedUntil > time()) {
        $loginError = 'Too many attempts. Try again later.';
    } elseif (hash_equals(ADMIN_PASSWORD, (string)($_POST['password'] ?? ''))) {
        session_regenerate_id(true);
        $_SESSION['authorized'] = true;
        $_SESSION['last_activity'] = time();
        $_SESSION['csrf'] = bin2hex(random_bytes(32));
        unset($_SESSION['failures'], $_SESSION['blocked_until']);

        header('Location: ' . $_SERVER['SCRIPT_NAME']);
        exit;
    } else {
        $_SESSION['failures'] = (int)($_SESSION['failures'] ?? 0) + 1;

        if ($_SESSION['failures'] >= 5) {
            $_SESSION['blocked_until'] = time() + 900;
            $_SESSION['failures'] = 0;
        }

        $loginError = 'Incorrect password.';
    }
}

if (!empty($_SESSION['authorized'])
    && time() - (int)($_SESSION['last_activity'] ?? 0) > 1800
) {
    $_SESSION = [];
    session_destroy();
    header('Location: ' . $_SERVER['SCRIPT_NAME']);
    exit;
}

if (empty($_SESSION['authorized'])):
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Manager Login</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f3f6fa; min-height: 90vh;
               display: flex; justify-content: center; align-items: center; }
        .box { width: min(380px, 92%); background: white; padding: 28px;
               border-radius: 12px; box-shadow: 0 4px 18px #0001; text-align: center; }
        input, button { box-sizing: border-box; width: 100%; padding: 12px;
                        margin-top: 12px; border: 1px solid #ccd5df; border-radius: 6px; }
        button { background: #1769d2; color: white; border: 0; cursor: pointer; }
        .error { color: #b42318; }
    </style>
</head>
<body>
<div class="box">
    <h2>hosting provider check montly</h2>
    <p>Log in to manage files and restore backups.</p>
    <?php if ($loginError !== ''): ?>
        <p class="error"><?= h($loginError) ?></p>
    <?php endif; ?>
    <form method="post">
        <input type="password" name="password" placeholder="Password" required autofocus>
        <button type="submit" name="login" value="1">Log in</button>
    </form>
</div>
</body>
</html>
<?php
exit;
endif;

$_SESSION['last_activity'] = time();
$notice = (string)($_SESSION['notice'] ?? '');
unset($_SESSION['notice']);

try {
    $requestedDir = $_POST['dir'] ?? $_GET['dir'] ?? __DIR__;
    if (!is_string($requestedDir)) {
        throw new RuntimeException('Invalid directory.');
    }
    $directory = resolveDirectory($requestedDir, __DIR__);
} catch (Throwable $e) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        http_response_code(400);
        exit('Invalid current directory.');
    }
    $directory = resolveDirectory(__DIR__, __DIR__);
    $notice = 'Error: ' . $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sentToken = $_POST['csrf'] ?? null;

    if (!is_string($sentToken)
        || !hash_equals((string)$_SESSION['csrf'], $sentToken)
    ) {
        http_response_code(403);
        exit('Invalid security token.');
    }

    $action = (string)($_POST['action'] ?? '');

    try {
        if ($action === 'logout') {
            $_SESSION = [];
            session_destroy();
            header('Location: ' . $_SERVER['SCRIPT_NAME']);
            exit;
        }

        if ($action === 'go') {
            $destination = resolveDirectory((string)($_POST['path'] ?? ''), $directory);
            header('Location: ' . pageUrl($destination));
            exit;
        }

        if ($action === 'bulk') {
            [$changed, $failed, $links] = applyBulkPermissions($directory);
            $notice = "Permissions: {$changed} changed, {$failed} failed, {$links} links skipped.";
        } elseif ($action === 'chmod') {
            $path = childPath($directory, $_POST['name'] ?? null);
            $permission = (string)($_POST['permission'] ?? '');

            if ($path === null || is_link($path)
                || !preg_match('/^0?[0-7]{3}$/', $permission)
                || !@chmod($path, octdec($permission))
            ) {
                throw new RuntimeException('Permission change failed.');
            }

            $notice = 'Permissions updated: ' . basename($path);
        } elseif ($action === 'rename') {
            $path = childPath($directory, $_POST['name'] ?? null);
            $newName = $_POST['new_name'] ?? null;

            if ($path === null || isManagerFile($path) || !validName($newName)) {
                throw new RuntimeException('Invalid rename request.');
            }

            $target = $directory . DIRECTORY_SEPARATOR . $newName;

            if (file_exists($target) || is_link($target) || !@rename($path, $target)) {
                throw new RuntimeException('Destination exists or rename failed.');
            }

            $notice = 'Renamed to: ' . $newName;
        } elseif ($action === 'delete') {
            $path = childPath($directory, $_POST['name'] ?? null);

            if ($path === null || isManagerFile($path)) {
                throw new RuntimeException('Invalid delete request.');
            }

            deleteTree($path);
            $notice = 'Deleted: ' . basename($path);
        } elseif ($action === 'save') {
            $path = childPath($directory, $_POST['name'] ?? null);

            if ($path === null || !editableFile($path)) {
                throw new RuntimeException('File is not editable.');
            }

            $content = $_POST['content'] ?? null;
            if (!is_string($content)) {
                throw new RuntimeException('Invalid file content.');
            }

            saveTextFile($path, $content);
            $notice = 'Saved: ' . basename($path);
        } elseif ($action === 'upload') {
            $files = $_FILES['files'] ?? null;

            if (!is_array($files)
                || !isset($files['name'], $files['error'])
                || !is_array($files['name'])
            ) {
                throw new RuntimeException('No files received. Check PHP upload limits.');
            }

            $uploaded = 0;

            foreach ($files['name'] as $i => $originalName) {
                $error = (int)($files['error'][$i] ?? UPLOAD_ERR_NO_FILE);
                if ($error === UPLOAD_ERR_NO_FILE) {
                    continue;
                }
                if ($error !== UPLOAD_ERR_OK) {
                    throw new RuntimeException('Upload failed (PHP error ' . $error . ').');
                }

                $name = basename(str_replace('\\', '/', (string)$originalName));
                $size = (int)($files['size'][$i] ?? -1);
                $temp = (string)($files['tmp_name'][$i] ?? '');
                $target = $directory . DIRECTORY_SEPARATOR . $name;

                if (!validName($name) || $size < 0 || $size > MAX_UPLOAD_BYTES) {
                    throw new RuntimeException('Invalid upload name or file size.');
                }

                // Upload does not overwrite. ZIP extraction has its own overwrite flow.
                if (file_exists($target) || is_link($target)) {
                    throw new RuntimeException('Upload destination already exists: ' . $name);
                }

                if (!@move_uploaded_file($temp, $target)) {
                    throw new RuntimeException('Could not upload: ' . $name);
                }

                $uploaded++;
            }

            $notice = "Uploaded {$uploaded} file(s).";
        } elseif ($action === 'unzip') {
            $archive = childPath($directory, $_POST['name'] ?? null);
            $targetInput = $_POST['target_path'] ?? '.';

            if ($archive === null || is_link($archive)
                || !is_file($archive)
                || !preg_match('/\.zip$/i', $archive)
                || !is_string($targetInput)
            ) {
                throw new RuntimeException('Select a valid ZIP file.');
            }

            $targetDir = resolveDirectory($targetInput, $directory);

            try {
                [$created, $overwritten, $folders] =
                    extractZipSafely($archive, $targetDir);
            } catch (Throwable $e) {
                throw new RuntimeException(
                    'Extraction stopped. Some earlier files may already have changed. '
                    . $e->getMessage()
                );
            }

            $notice = "Extracted to {$targetDir}: {$created} new files, "
                . "{$overwritten} overwritten files, {$folders} directory entries.";
        } else {
            throw new RuntimeException('Unknown action.');
        }
    } catch (Throwable $e) {
        $notice = 'Error: ' . $e->getMessage();
    }

    $_SESSION['notice'] = $notice;
    header('Location: ' . pageUrl($directory));
    exit;
}

$editName = $_GET['edit'] ?? null;
$editContent = null;

if (is_string($editName)) {
    $editPath = childPath($directory, $editName);
    if ($editPath !== null && editableFile($editPath)) {
        $editContent = @file_get_contents($editPath);
    }
}

$items = @scandir($directory);

if ($items !== false) {
    $items = array_values(array_filter(
        $items,
        static function ($name): bool {
            return $name !== '.' && $name !== '..';
        }
    ));

    usort($items, static function ($a, $b) use ($directory): int {
        $aDir = is_dir($directory . DIRECTORY_SEPARATOR . $a);
        $bDir = is_dir($directory . DIRECTORY_SEPARATOR . $b);

        if ($aDir !== $bDir) {
            return $aDir ? -1 : 1;
        }

        return strnatcasecmp($a, $b);
    });
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Hosting Provider Check Monthly</title>
    <style>
        * { box-sizing: border-box; }
        body { margin: 0; padding: 20px; background: #f3f6fa;
               color: #263449; font: 14px Arial, sans-serif; }
        .container { max-width: 1200px; margin: auto; padding: 22px;
                     background: #fff; border-radius: 12px;
                     box-shadow: 0 4px 20px #0001; }
        h1 { font-size: 21px; margin-top: 0; }
        h2 { font-size: 16px; }
        .path, .notice { padding: 11px; margin: 12px 0; border-radius: 6px;
                         background: #eef3fa; word-break: break-all; }
        .notice { background: #e8f6ec; }
        .notice.error { background: #ffe9e9; color: #9d2323; }
        .row { display: flex; flex-wrap: wrap; align-items: center;
               gap: 8px; margin: 8px 0; }
        .grow { flex: 1; }
        input[type=text], input[type=password], textarea {
            border: 1px solid #ccd5df; border-radius: 5px;
            padding: 7px; font: inherit;
        }
        input.permission { width: 60px; text-align: center; }
        input.new-name { width: 140px; }
        input.destination { width: 180px; }
        textarea { width: 100%; min-height: 360px;
                   font: 13px monospace; }
        button, .button { display: inline-block; padding: 7px 11px;
                          border: 0; border-radius: 5px;
                          background: #1769d2; color: #fff;
                          text-decoration: none; cursor: pointer;
                          font: 13px Arial, sans-serif; }
        .secondary { background: #657287; }
        .danger { background: #cf3636; }
        .success { background: #208552; }
        .upload { padding: 12px; background: #f4f7fb;
                  border-radius: 6px; margin: 12px 0; }
        .table-wrap { overflow-x: auto; }
        table { width: 100%; min-width: 900px; border-collapse: collapse; }
        th, td { padding: 9px; border-bottom: 1px solid #e5eaf0;
                 text-align: left; vertical-align: middle; }
        th { background: #f5f7fa; }
        a { color: #1769d2; }
        .actions { display: flex; gap: 7px; flex-wrap: wrap;
                   align-items: center; }
        .actions form { display: inline-flex; align-items: center;
                        gap: 5px; margin: 0; }
        .hint { color: #667; font-size: 12px; }
    </style>
</head>
<body>
<div class="container">
    <h1>hosting provider check montly</h1>

    <div class="path"><strong>Current directory:</strong> <?= h($directory) ?></div>

    <?php if ($notice !== ''): ?>
        <div class="notice <?= strpos($notice, 'Error:') === 0 ? 'error' : '' ?>">
            <?= h($notice) ?>
        </div>
    <?php endif; ?>

    <form method="post" class="row">
        <input type="hidden" name="csrf" value="<?= h($_SESSION['csrf']) ?>">
        <input type="hidden" name="dir" value="<?= h($directory) ?>">
        <label for="path">Go to directory:</label>
        <input id="path" type="text" name="path" class="grow"
               placeholder="/home/account/public_html or ../another-folder">
        <button name="action" value="go" type="submit">Go</button>
        <?php if (dirname($directory) !== $directory): ?>
            <a class="button secondary"
               href="<?= h(pageUrl(dirname($directory))) ?>">Parent directory</a>
        <?php endif; ?>
    </form>

    <div class="row">
        <form method="post"
              onsubmit="return confirm('Apply 0775 recursively to this directory?');">
            <input type="hidden" name="csrf" value="<?= h($_SESSION['csrf']) ?>">
            <input type="hidden" name="dir" value="<?= h($directory) ?>">
            <button class="success" name="action" value="bulk" type="submit">
                Apply 0775 to All Here
            </button>
        </form>
        <span class="grow"></span>
        <form method="post">
            <input type="hidden" name="csrf" value="<?= h($_SESSION['csrf']) ?>">
            <input type="hidden" name="dir" value="<?= h($directory) ?>">
            <button class="secondary" name="action" value="logout"
                    type="submit">Log out</button>
        </form>
    </div>

    <div class="upload">
        <form method="post" enctype="multipart/form-data" class="row">
            <input type="hidden" name="csrf" value="<?= h($_SESSION['csrf']) ?>">
            <input type="hidden" name="dir" value="<?= h($directory) ?>">
            <input type="file" name="files[]" multiple required>
            <button name="action" value="upload" type="submit">
                Upload Files
            </button>
            <span class="hint">Upload does not overwrite existing files.</span>
        </form>
    </div>

    <?php if ($editContent !== null && $editContent !== false): ?>
        <h2>Edit: <?= h($editName) ?></h2>
        <form method="post">
            <input type="hidden" name="csrf" value="<?= h($_SESSION['csrf']) ?>">
            <input type="hidden" name="dir" value="<?= h($directory) ?>">
            <input type="hidden" name="name" value="<?= h($editName) ?>">
            <textarea name="content"><?= h($editContent) ?></textarea>
            <div class="row">
                <button name="action" value="save" type="submit">
                    Save Changes
                </button>
                <a class="button secondary"
                   href="<?= h(pageUrl($directory)) ?>">Cancel</a>
            </div>
        </form>
    <?php endif; ?>

    <div class="table-wrap">
        <table>
            <thead>
            <tr>
                <th>Name</th>
                <th>Type</th>
                <th>Permissions</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php if ($items === false): ?>
                <tr><td colspan="4">Cannot read this directory.</td></tr>
            <?php else: foreach ($items as $name):
                $path = $directory . DIRECTORY_SEPARATOR . $name;
                $isDirectory = is_dir($path);
                $isLink = is_link($path);
                $mode = @fileperms($path);
                $permissions = $mode === false
                    ? '----'
                    : sprintf('%04o', $mode & 07777);
                $realChild = $isDirectory ? realpath($path) : false;
            ?>
                <tr>
                    <td>
                        <?php if ($isDirectory && $realChild !== false): ?>
                            <a href="<?= h(pageUrl($realChild)) ?>">
                                <strong><?= h($name) ?></strong>
                            </a>
                        <?php else: ?>
                            <?= h($name) ?>
                        <?php endif; ?>
                    </td>
                    <td><?= $isLink ? 'Link' : ($isDirectory ? 'Folder' : 'File') ?></td>
                    <td><code><?= h($permissions) ?></code></td>
                    <td>
                        <div class="actions">
                            <?php if (!$isLink): ?>
                                <form method="post">
                                    <input type="hidden" name="csrf"
                                           value="<?= h($_SESSION['csrf']) ?>">
                                    <input type="hidden" name="dir"
                                           value="<?= h($directory) ?>">
                                    <input type="hidden" name="name"
                                           value="<?= h($name) ?>">
                                    <input type="text" name="permission"
                                           class="permission"
                                           value="<?= h($permissions) ?>"
                                           maxlength="4" required>
                                    <button class="success" name="action"
                                            value="chmod" type="submit">Set</button>
                                </form>
                            <?php endif; ?>

                            <?php if (!isManagerFile($path)): ?>
                                <form method="post">
                                    <input type="hidden" name="csrf"
                                           value="<?= h($_SESSION['csrf']) ?>">
                                    <input type="hidden" name="dir"
                                           value="<?= h($directory) ?>">
                                    <input type="hidden" name="name"
                                           value="<?= h($name) ?>">
                                    <input type="text" name="new_name"
                                           class="new-name"
                                           value="<?= h($name) ?>" required>
                                    <button class="secondary" name="action"
                                            value="rename" type="submit">Rename</button>
                                </form>

                                <?php if (editableFile($path)): ?>
                                    <a class="button"
                                       href="<?= h(pageUrl($directory, $name)) ?>">
                                        Edit
                                    </a>
                                <?php endif; ?>

                                <?php if (is_file($path) && !$isLink
                                    && preg_match('/\.zip$/i', $name)): ?>
                                    <form method="post"
                                          onsubmit="return confirm('Extract and overwrite matching files at: ' + this.elements.namedItem('target_path').value + ' ?');">
                                        <input type="hidden" name="csrf"
                                               value="<?= h($_SESSION['csrf']) ?>">
                                        <input type="hidden" name="dir"
                                               value="<?= h($directory) ?>">
                                        <input type="hidden" name="name"
                                               value="<?= h($name) ?>">
                                        <input type="text" name="target_path"
                                               class="destination" value="."
                                               title="Existing destination directory: . means current">
                                        <button name="action" value="unzip"
                                                type="submit">Unzip</button>
                                    </form>
                                <?php endif; ?>

                                <form method="post"
                                      onsubmit="return confirm('Permanently delete ' + this.elements.namedItem('name').value + ' ?');">
                                    <input type="hidden" name="csrf"
                                           value="<?= h($_SESSION['csrf']) ?>">
                                    <input type="hidden" name="dir"
                                           value="<?= h($directory) ?>">
                                    <input type="hidden" name="name"
                                           value="<?= h($name) ?>">
                                    <button class="danger" name="action"
                                            value="delete" type="submit">
                                        Delete
                                    </button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>
