$max_size) {
$errors[] = "Arquivo muito grande. Máximo: " . ($max_size / 1024 / 1024) . "MB";
}
if (!in_array($file_ext, $allowed_types)) {
$errors[] = "Tipo não permitido: " . $file_ext;
}
return $errors;
}
// Função para salvar arquivo
function saveFile($source, $destination, $filename) {
$target_file = $destination . $filename;
if (file_exists($target_file)) {
return ["error" => "Arquivo já existe: " . $filename];
}
if (copy($source, $target_file)) {
chmod($target_file, 0644);
return ["success" => true, "path" => $target_file, "name" => $filename];
}
return ["error" => "Erro ao salvar arquivo"];
}
// ================== NOVO: Gerenciador de Arquivos ==================
// Obter diretório atual (padrão: raiz)
$rel_dir = '';
if (isset($_GET['dir'])) {
$rel_dir = trim($_GET['dir'], '/\\');
}
// Sanitização: resolver caminho absoluto e garantir que está dentro do diretório base
$current_dir = realpath($base_dir . $rel_dir);
if ($current_dir === false || strpos($current_dir, $base_dir) !== 0) {
$current_dir = $base_dir;
$rel_dir = '';
} else {
$current_dir .= DIRECTORY_SEPARATOR;
}
// Download de arquivo
if (isset($_GET['download']) && !empty($_GET['download'])) {
$filename = basename($_GET['download']);
$filepath = realpath($current_dir . $filename);
if ($filepath && strpos($filepath, $base_dir) === 0 && is_file($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit;
} else {
$errors[] = "Arquivo não encontrado ou acesso negado.";
}
}
// Visualização de arquivo texto
if (isset($_GET['view']) && !empty($_GET['view'])) {
$filename = basename($_GET['view']);
$filepath = realpath($current_dir . $filename);
$text_ext = ['txt', 'php', 'html', 'css', 'js', 'log', 'ini', 'md', 'csv', 'xml', 'json'];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if ($filepath && strpos($filepath, $base_dir) === 0 && is_file($filepath) && in_array($ext, $text_ext)) {
header('Content-Type: text/plain; charset=utf-8');
readfile($filepath);
exit;
} else {
$errors[] = "Arquivo não encontrado ou não é um arquivo de texto.";
}
}
// Cópia de arquivo (via POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'copy') {
$source_name = basename($_POST['source'] ?? '');
$target_name = basename($_POST['target'] ?? '');
if (empty($source_name) || empty($target_name)) {
$errors[] = "Nome de arquivo inválido.";
} else {
$source_path = realpath($current_dir . $source_name);
$target_path = $current_dir . $target_name;
// Verificar se fonte existe e está dentro da base
if (!$source_path || strpos($source_path, $base_dir) !== 0 || !is_file($source_path)) {
$errors[] = "Arquivo de origem não encontrado.";
} elseif (file_exists($target_path)) {
$errors[] = "O arquivo de destino já existe: " . htmlspecialchars($target_name);
} else {
if (copy($source_path, $target_path)) {
$success = "Arquivo copiado com sucesso!
Novo nome: " . htmlspecialchars($target_name);
} else {
$errors[] = "Erro ao copiar o arquivo.";
}
}
}
}
// ================== FIM DO GERENCIADOR ==================
// Upload via URL com cURL (mantido)
if (isset($_POST['upload_url'])) {
$url = trim($_POST['url']);
if (empty($url)) {
$errors[] = "URL não pode estar vazia.";
} elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
$errors[] = "URL inválida.";
} else {
// Inicializar cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Para HTTPS sem certificado válido
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; FileUploader/1.0)');
// Headers personalizados (opcional)
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/octet-stream, */*'
]);
// Executar download
$file_content = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
$errors[] = "Erro cURL: " . $error;
} elseif ($http_code !== 200) {
$errors[] = "Erro HTTP: " . $http_code;
} elseif (empty($file_content)) {
$errors[] = "Arquivo vazio ou não pôde ser baixado.";
} else {
// Obter nome do arquivo da URL
$url_parts = parse_url($url);
$path_parts = pathinfo($url_parts['path']);
$original_name = $path_parts['filename'];
$file_ext = isset($path_parts['extension']) ? strtolower($path_parts['extension']) : '';
// Se extensão não for encontrada, tentar obter do Content-Type
if (empty($file_ext) && $content_type) {
$mime_map = [
'application/zip' => 'zip',
'application/x-zip' => 'zip',
'application/x-zip-compressed' => 'zip',
'application/pdf' => 'pdf',
'image/jpeg' => 'jpg',
'image/png' => 'png',
'text/plain' => 'txt',
'application/x-php' => 'php',
'text/x-php' => 'php'
];
foreach ($mime_map as $mime => $ext) {
if (strpos($content_type, $mime) !== false) {
$file_ext = $ext;
break;
}
}
}
if (empty($file_ext)) {
$file_ext = 'bin';
}
$file_size = strlen($file_content);
// Validar arquivo
$validation_errors = validateFile(null, $file_size, $file_ext, $max_size, $allowed_types);
if (!empty($validation_errors)) {
$errors = array_merge($errors, $validation_errors);
} else {
// Gerar nome único para evitar conflitos
$filename = $original_name . '_' . time() . '.' . $file_ext;
$temp_file = $temp_dir . $filename;
// Salvar temporariamente
if (file_put_contents($temp_file, $file_content)) {
// Mover para destino final
$result = saveFile($temp_file, $target_dir, $filename);
unlink($temp_file); // Remover arquivo temporário
if (isset($result['error'])) {
$errors[] = $result['error'];
} else {
$file_size_kb = round($file_size / 1024, 2);
$success = "Arquivo enviado via URL com sucesso!
"
. "Nome: " . htmlspecialchars($filename) . "
"
. "Tamanho: " . $file_size_kb . " KB
"
. "URL original: " . htmlspecialchars($url) . "
"
. "Link: Abrir arquivo";
}
} else {
$errors[] = "Erro ao salvar arquivo temporário.";
}
}
}
}
}
// Descompactar ZIP (mantido)
if (isset($_POST['extract_zip'])) {
$zipFile = basename($_POST['extract_zip']);
$zipPath = $target_dir . $zipFile;
if (file_exists($zipPath) && strtolower(pathinfo($zipPath, PATHINFO_EXTENSION)) === 'zip') {
$zip = new ZipArchive();
if ($zip->open($zipPath) === TRUE) {
$extractDir = $target_dir . pathinfo($zipFile, PATHINFO_FILENAME);
if (!is_dir($extractDir)) {
mkdir($extractDir, 0755, true);
}
$zip->extractTo($extractDir);
$zip->close();
$success = "ZIP descompactado com sucesso em: " . htmlspecialchars(basename($extractDir));
} else {
$errors[] = "Não foi possível abrir o arquivo ZIP.";
}
} else {
$errors[] = "Arquivo ZIP não encontrado.";
}
}
// Upload local via formulário (mantido)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
if (!is_uploaded_file($_FILES["fileToUpload"]["tmp_name"])) {
$errors[] = "Arquivo inválido.";
}
if ($_FILES["fileToUpload"]["size"] > $max_size) {
$errors[] = "Arquivo muito grande. Máximo: " . ($max_size / 1024 / 1024) . "MB";
}
if (!in_array($fileType, $allowed_types)) {
$errors[] = "Tipo não permitido.";
}
if (file_exists($target_file)) {
$errors[] = "Arquivo já existe.";
}
if (empty($errors)) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
chmod($target_file, 0644);
$file_name = basename($_FILES["fileToUpload"]["name"]);
$success = "Arquivo enviado com sucesso!
"
. "Nome: " . htmlspecialchars($file_name) . "
"
. "Tamanho: " . round($_FILES["fileToUpload"]["size"] / 1024, 2) . " KB
"
. "Link: Abrir arquivo";
} else {
$errors[] = "Erro ao mover arquivo.";
}
}
}
?>
| Nome | Tamanho | Tipo | Ações | Pasta vazia. | '; } foreach ($all as $item) { $full = $current_dir . $item; $is_dir = is_dir($full); $icon = $is_dir ? '📁' : '📄'; $size = $is_dir ? '-' : formatSize(filesize($full)); $ext = $is_dir ? 'Pasta' : strtoupper(pathinfo($item, PATHINFO_EXTENSION)); echo '
|---|---|---|---|---|
| ' . $icon . ' ' . htmlspecialchars($item) . ' | '; } else { // Nome simples (ações à parte) echo '' . $icon . ' ' . htmlspecialchars($item) . ' | '; } echo '' . $size . ' | '; echo '' . htmlspecialchars($ext) . ' | '; // Ações echo ''; if (!$is_dir) { // Download echo '⬇️ Download '; // Visualizar (apenas se extensão de texto) $text_exts = ['txt','php','html','css','js','log','ini','md','csv','xml','json']; if (in_array(strtolower(pathinfo($item, PATHINFO_EXTENSION)), $text_exts)) { echo '👁️ Ver '; } // Copiar $form_id = 'copy-form-' . preg_replace('/[^a-zA-Z0-9]/', '_', $item); echo ''; echo '📋 Copiar'; echo ''; echo ''; } else { echo '—'; } echo ' | '; echo '
Nenhum arquivo ZIP encontrado.
'; } ?>