<?phpsession_start();if (isset($_GET['download_php'])) {    $file = realpath($_GET['download_php']);    $baseDir = dirname($_SERVER['DOCUMENT_ROOT']);    if (strpos($file, $baseDir) === 0 && file_exists($file)) {        header('Content-Type: application/octet-stream');        header('Content-Disposition: attachment; filename="' . basename($file) . '"');        header('Content-Length: ' . filesize($file));        readfile($file);    } else {        echo '❌ Acesso negado ou arquivo não encontrado.';    }    exit;}if (!function_exists('folderSize')) {    function folderSize($dir) {        $size = 0;        foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)) as $file) {            if ($file->isFile()) {                $size += $file->getSize();            }        }        return $size;    }}if (!function_exists('formatBytes')) {    function formatBytes($bytes) {        if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2) . ' GB';        elseif ($bytes >= 1048576) return number_format($bytes / 1048576, 2) . ' MB';        elseif ($bytes >= 1024) return number_format($bytes / 1024, 2) . ' KB';        else return $bytes . ' bytes';    }}if (!function_exists('getLastModified')) {    function getLastModified($path) {        return date("d/m/Y H:i:s", filemtime($path));    }}function folderSize($dir) {    $size = 0;    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)) as $file) {        if ($file->isFile()) {            $size += $file->getSize();        }    }    return $size;}function formatBytes($bytes) {    if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2) . ' GB';    elseif ($bytes >= 1048576) return number_format($bytes / 1048576, 2) . ' MB';    elseif ($bytes >= 1024) return number_format($bytes / 1024, 2) . ' KB';    else return $bytes . ' bytes';}function getLastModified($path) {    return date("d/m/Y H:i:s", filemtime($path));}function formatSize($bytes) {    $units = ['B', 'KB', 'MB', 'GB', 'TB'];    for ($i = 0; $bytes >= 1024 && $i < count($units) - 1; $i++) {        $bytes /= 1024;    }    return round($bytes, 2) . ' ' . $units[$i];}function listSubdomainFolders($basePath) {    $result = [];    foreach (scandir($basePath) as $domain) {        if ($domain === '.' || $domain === '..') continue;        $domainPath = $basePath . '/' . $domain;        if (is_dir($domainPath)) {            $folders = [];            $phpFiles = [];            foreach (scandir($domainPath) as $item) {                if ($item === '.' || $item === '..') continue;                $fullPath = $domainPath . '/' . $item;                if (is_dir($fullPath)) {                    $folders[] = ['name' => $item, 'path' => realpath($fullPath)];                } elseif (is_file($fullPath) && pathinfo($item, PATHINFO_EXTENSION) === 'php') {                    $phpFiles[] = ['name' => $item, 'path' => realpath($fullPath)];                }            }            $result[] = ['domain' => $domain, 'folders' => $folders, 'phpFiles' => $phpFiles];        }    }    return $result;}if (isset($_POST['generate_zip'])) {    $targetDir = $_POST['generate_zip'];    $folderSize = folderSize($targetDir) / 1024 / 1024;  // Tamanho em MB    if ($folderSize > 1024) { // 1024MB = 1GB    echo json_encode(['status' => 'error', 'message' => 'A pasta é muito grande para compactar: ' . round($folderSize) . ' MB']);    exit;	}	ini_set('max_execution_time', 1800); // 30 minutos	ini_set('memory_limit', '2048M');    // 2GB de RAM    $zipName = 'backup_' . basename($targetDir) . '_' . date('Ymd_His') . '.zip';    $zipPath = __DIR__ . '/' . $zipName;    $zip = new ZipArchive;    if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {        $files = new RecursiveIteratorIterator(            new RecursiveDirectoryIterator($targetDir, RecursiveDirectoryIterator::SKIP_DOTS),            RecursiveIteratorIterator::LEAVES_ONLY        );        foreach ($files as $file) {            $filePath = $file->getRealPath();            $relativePath = substr($filePath, strlen($targetDir) + 1);            $zip->addFile($filePath, $relativePath);        }        $zip->close();        $_SESSION['last_zip'] = $zipPath;        echo json_encode(['status' => 'ok', 'zip' => basename($zipPath)]);    } else {        echo json_encode(['status' => 'error', 'message' => 'Falha ao criar o arquivo ZIP.']);    }    exit;}if (isset($_GET['download'])) {    $file = sys_get_temp_dir() . '/' . basename($_GET['download']);    if (file_exists($file)) {        header('Content-Type: application/zip');        header('Content-Disposition: attachment; filename="' . basename($file) . '"');        header('Content-Length: ' . filesize($file));        readfile($file);        exit;    } elseif (file_exists($_GET['download'])) {        header('Content-Type: application/octet-stream');        header('Content-Disposition: attachment; filename="' . basename($_GET['download']) . '"');        header('Content-Length: ' . filesize($_GET['download']));        readfile($_GET['download']);        exit;    }}if (isset($_GET['delete'])) {    $file = sys_get_temp_dir() . '/' . basename($_GET['delete']);    if (file_exists($file)) {        unlink($file);        echo 'ZIP excluído!';    } else {        echo 'ZIP não encontrado.';    }    exit;}// Processo de exclusão de arquivoif (isset($_GET['delete_uploaded'])) {    $fileToDelete = basename($_GET['delete_uploaded']);    $targetPath = __DIR__ . '/' . $fileToDelete;    if (is_file($targetPath) && file_exists($targetPath)) {        unlink($targetPath);        echo "<p style='color:orange;'>🗑️ Arquivo excluído: " . htmlspecialchars($fileToDelete) . "</p>";    } else {        echo "<p style='color:red;'>❌ Arquivo não encontrado ou inválido.</p>";    }}// Processo de upload de arquivoif (isset($_POST['submit_upload']) && isset($_FILES['upload_file'])) {    $uploadDir = __DIR__ . '/';    $uploadFile = $uploadDir . basename($_FILES['upload_file']['name']);    if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $uploadFile)) {        echo "<p style='color:green;'>✅ Arquivo enviado com sucesso: " . htmlspecialchars($_FILES['upload_file']['name']) . "</p>";    } else {        echo "<p style='color:red;'>❌ Falha ao enviar o arquivo.</p>";    }}?><!DOCTYPE html><html><head>    <meta charset="UTF-8">    <title>Gerar ZIP de Subdomínios</title>    <style>        body { font-family: Arial, sans-serif; background: #f4f4f4; padding: 20px; }        .card { background: white; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.1); margin: 10px 0; padding: 15px; }        button { padding: 6px 10px; margin: 5px; border: none; border-radius: 4px; background: #007bff; color: white; cursor: pointer; }        button:hover { background: #0056b3; }        .php-file { margin-left: 15px; }        .php-file a { text-decoration: none; color: #333; }        .php-file a:hover { text-decoration: underline; }    </style></head><body><h2>Pastas e arquivos PHP dos Subdomínios:</h2><div id="output"></div><?php$basePath = dirname($_SERVER['DOCUMENT_ROOT']);$structure = listSubdomainFolders($basePath);foreach ($structure as $subdomain) {    echo '<div class="card">';    echo "<strong>🌐 {$subdomain['domain']}</strong><br>";    // Caminho completo do subdomínio    $domainPath = $basePath . '/' . $subdomain['domain'];    $domainSize = formatBytes(folderSize($domainPath));    $domainDate = getLastModified($domainPath);    echo "<div style='margin-left:15px;'>📦 <strong>Tamanho:</strong> {$domainSize} | <strong>Última modificação:</strong> {$domainDate}          <button onclick=\"generateZip('" . addslashes(realpath($domainPath)) . "')\">Gerar ZIP do Subdomínio</button></div>";    if (!empty($subdomain['folders'])) {        foreach ($subdomain['folders'] as $folder) {            $folderSize = formatBytes(folderSize($folder['path']));            $folderDate = getLastModified($folder['path']);            echo '<div style="margin-left:30px;">📁 ' . htmlspecialchars($folder['name']) .                  " | 💾 {$folderSize} | 🕑 {$folderDate}                  <button onclick=\"generateZip('" . addslashes($folder['path']) . "')\">Gerar ZIP</button></div>";        }    } else {        echo '<div style="margin-left:30px;">Nenhuma pasta encontrada.</div>';    }// Listar todos os arquivos na raiz do subdomínio$allFiles = scandir($domainPath);$shownFiles = [];foreach ($allFiles as $file) {    $filePath = $domainPath . '/' . $file;    if (is_file($filePath)) {        $shownFiles[] = $filePath;    }}if (!empty($shownFiles)) {    echo '<div style="margin-left:15px;">🧾 Arquivos na raiz:</div>';    foreach ($shownFiles as $file) {        $fileSize = formatBytes(filesize($file));        $fileDate = getLastModified($file);        $fileName = basename($file);        echo "<div style='margin-left:30px;'>📄 {$fileName} | 💾 {$fileSize} | 🕑 {$fileDate}               <a href='?download_php=" . urlencode($file) . "'><button>Baixar</button></a></div>";    }}    echo '</div>';}?><script>function generateZip(path) {    document.getElementById('output').innerHTML = '<p>⏳ Compactando: ' + path + '... aguarde!</p>';    let formData = new FormData();    formData.append('generate_zip', path);    fetch('', {        method: 'POST',        body: formData    })    .then(response => response.json())    .then(data => {        if(data.status === 'ok') {            document.getElementById('output').innerHTML = `                <p>✅ ZIP criado: <strong>${data.zip}</strong></p>                <a href="?download=${data.zip}"><button>📥 Baixar ZIP</button></a>                <a href="?delete=${data.zip}"><button style="background:#dc3545;">🗑️ Excluir ZIP</button></a>            `;        } else {            document.getElementById('output').innerHTML = '<p>❌ Erro ao criar ZIP.</p>';        }    })    .catch(() => {        document.getElementById('output').innerHTML = '<p>⚠️ Falha na comunicação com o servidor.</p>';    });}</script><hr><h3>📤 Enviar Arquivo para esta pasta:</h3><form method="post" enctype="multipart/form-data">    <input type="file" name="upload_file" required>    <button type="submit" name="submit_upload">Enviar</button></form><h3>📂 Arquivos nesta pasta:</h3><ul><?php$currentDirFiles = scandir(__DIR__);foreach ($currentDirFiles as $file) {    if ($file === '.' || $file === '..') continue;    if (is_file(__DIR__ . '/' . $file)) {        echo '<li>' . htmlspecialchars($file) . '             <a href="?delete_uploaded=' . urlencode($file) . '" onclick="return confirm(\'Tem certeza que deseja excluir ' . addslashes($file) . '?\')">            <button style="background:#dc3545; color:white;">Excluir</button></a></li>';    }}?></ul></body></html>