5 * 1024 * 1024) { // 5MB limite para visualização
echo "Arquivo muito grande para visualização. Faça o download.";
exit;
}
readfile($filepath);
exit;
} else {
$errors[] = "Arquivo não encontrado, acesso negado ou não é um arquivo de texto.";
}
}
// Ação: Copiar arquivo
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'copy') {
$source_name = basename($_POST['source'] ?? '');
$target_name = basename($_POST['target'] ?? '');
$target_dir_post = $_POST['target_dir'] ?? '';
if (empty($source_name) || empty($target_name)) {
$errors[] = "Nome de arquivo inválido.";
} else {
$source_path = securePath(($rel_dir ? $rel_dir . '/' : '') . $source_name, $base_dir);
// Destino pode ser em outro diretório (relativo à base)
$dest_dir = !empty($target_dir_post) ? trim($target_dir_post, '/\\') : $rel_dir;
$dest_dir_path = securePath($dest_dir, $base_dir);
if ($source_path !== false && is_file($source_path) && $dest_dir_path !== false && is_dir($dest_dir_path)) {
$target_path = $dest_dir_path . $target_name;
if (file_exists($target_path)) {
$errors[] = "Arquivo de destino já existe: " . htmlspecialchars($target_name);
} elseif (copy($source_path, $target_path)) {
chmod($target_path, 0644);
$success = "Arquivo copiado com sucesso!
" .
"De: " . htmlspecialchars($source_name) . "
" .
"Para: " . htmlspecialchars($target_name);
} else {
$errors[] = "Erro ao copiar o arquivo. Verifique permissões.";
}
} else {
$errors[] = "Origem ou destino inválido.";
}
}
}
// Ação: Criar nova pasta
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'mkdir') {
$folder_name = basename($_POST['folder_name'] ?? '');
if (empty($folder_name)) {
$errors[] = "Nome da pasta inválido.";
} else {
$new_folder = $current_dir . $folder_name;
if (!file_exists($new_folder)) {
if (mkdir($new_folder, 0755, true)) {
$success = "Pasta criada com sucesso: " . htmlspecialchars($folder_name);
} else {
$errors[] = "Erro ao criar pasta. Verifique permissões.";
}
} else {
$errors[] = "Esta pasta já existe.";
}
}
}
// Ação: Deletar arquivo/pasta
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
$item_name = basename($_POST['item'] ?? '');
$item_path = securePath(($rel_dir ? $rel_dir . '/' : '') . $item_name, $base_dir);
// PROTEÇÃO: não permitir deletar fora do diretório base
if ($item_path !== false && $item_path !== $base_dir && strpos($item_path, $base_dir) === 0) {
if (is_dir($item_path)) {
// Deletar pasta (apenas se vazia)
$contents = scandir($item_path);
if (count($contents) <= 2) { // Apenas . e ..
if (rmdir($item_path)) {
$success = "Pasta removida: " . htmlspecialchars($item_name);
} else {
$errors[] = "Erro ao remover pasta.";
}
} else {
$errors[] = "A pasta não está vazia. Remova os arquivos primeiro.";
}
} elseif (is_file($item_path)) {
if (unlink($item_path)) {
$success = "Arquivo removido: " . htmlspecialchars($item_name);
} else {
$errors[] = "Erro ao remover arquivo.";
}
} else {
$errors[] = "Item não encontrado.";
}
} else {
$errors[] = "Operação não permitida.";
}
}
// ============================================
// UPLOADS (mantidos originais)
// ============================================
// Upload via URL com cURL
if (isset($_POST['upload_url'])) {
$url = trim($_POST['url']);
$upload_to = isset($_POST['upload_dir']) ? trim($_POST['upload_dir'], '/\\') : '';
$dest_path = securePath($upload_to, $base_dir);
if ($dest_path === false || !is_dir($dest_path)) {
$dest_path = $base_dir; // Fallback para raiz
}
if (empty($url)) {
$errors[] = "URL não pode estar vazia.";
} elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
$errors[] = "URL inválida.";
} else {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; FileManager/1.0)'
]);
$file_content = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_error) {
$errors[] = "Erro cURL: " . $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 {
$url_parts = parse_url($url);
$path_parts = pathinfo($url_parts['path']);
$original_name = $path_parts['filename'];
$file_ext = strtolower($path_parts['extension'] ?? '');
if (empty($file_ext) && $content_type) {
$mime_map = [
'application/zip' => 'zip',
'application/pdf' => 'pdf',
'image/jpeg' => 'jpg',
'image/png' => 'png',
'text/plain' => 'txt'
];
foreach ($mime_map as $mime => $ext) {
if (strpos($content_type, $mime) !== false) {
$file_ext = $ext;
break;
}
}
}
if (empty($file_ext)) $file_ext = 'bin';
if (!in_array($file_ext, $allowed_types)) {
$errors[] = "Tipo de arquivo não permitido: " . $file_ext;
} else {
$filename = $original_name . '_' . time() . '.' . $file_ext;
$target_path = $dest_path . $filename;
if (file_put_contents($target_path, $file_content)) {
chmod($target_path, 0644);
$success = "Arquivo baixado com sucesso!
" .
"Nome: " . htmlspecialchars($filename) . "
" .
"Tamanho: " . round(strlen($file_content) / 1024, 2) . " KB
" .
"Salvo em: " . htmlspecialchars(str_replace($base_dir, '', $dest_path));
} else {
$errors[] = "Erro ao salvar arquivo.";
}
}
}
}
}
// Upload local
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
$upload_to = isset($_POST['upload_dir']) ? trim($_POST['upload_dir'], '/\\') : '';
$dest_path = securePath($upload_to, $base_dir);
if ($dest_path === false || !is_dir($dest_path)) {
$dest_path = $base_dir;
}
$file_name = basename($_FILES["fileToUpload"]["name"]);
$target_file = $dest_path . $file_name;
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
if (!is_uploaded_file($_FILES["fileToUpload"]["tmp_name"])) {
$errors[] = "Arquivo inválido.";
} elseif ($_FILES["fileToUpload"]["size"] > $max_size) {
$errors[] = "Arquivo muito grande. Máximo: " . ($max_size / 1024 / 1024) . "MB";
} elseif (!in_array($fileType, $allowed_types)) {
$errors[] = "Tipo de arquivo não permitido.";
} elseif (file_exists($target_file)) {
$errors[] = "Arquivo já existe.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
chmod($target_file, 0644);
$success = "Upload realizado com sucesso!
" .
"Nome: " . htmlspecialchars($file_name) . "
" .
"Tamanho: " . round($_FILES["fileToUpload"]["size"] / 1024, 2) . " KB";
} else {
$errors[] = "Erro ao mover arquivo.";
}
}
}
?>
| Nome | Tamanho | Modificado | Ações | ❌ Sem permissão para acessar este diretório. | '; } else { $dirs = []; $files = []; foreach ($items as $item) { if ($item === '.' || $item === '..') continue; if ($item === 'temp' && realpath($current_dir . $item) === realpath($temp_dir)) continue; // Esconder pasta temp $full = $current_dir . $item; if (is_dir($full)) { $dirs[] = $item; } else { $files[] = $item; } } natcasesort($dirs); natcasesort($files); $all = array_merge($dirs, $files); if (empty($all)) { echo '
|---|---|---|---|---|
| 📭 Diretório vazio. | ||||
| ' . $icon . ' ' . htmlspecialchars($item) . '/ | '; } else { echo '' . $icon . ' ' . htmlspecialchars($item) . ' | '; } echo '' . $size . ' | '; echo '' . $modified . ' | '; echo ''; if (!$is_dir) { // Download echo '⬇️ '; // Visualizar texto if (in_array(strtolower(pathinfo($item, PATHINFO_EXTENSION)), $text_extensions)) { echo '👁️ '; } // Copiar $form_id = 'copy-form-' . preg_replace('/[^a-zA-Z0-9]/', '_', $item); echo ''; echo ' '; } // Deletar (arquivos e pastas vazias) echo ''; echo ' | '; echo '