baseMediaDir = rtrim(str_replace('\\', '/', $baseDataPath), '/') . '/media/'; // Белый список разрешенных расширений файлов $this->allowedTypes = [ 'jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt' ]; } public function resolveDir(string $ns): string { $ns = str_replace(['..', '\\'], '', $ns); $relativePath = str_replace(':', '/', $ns); return rtrim($this->baseMediaDir . $relativePath, '/') . '/'; } public function getFiles(string $ns): array { $dir = $this->resolveDir($ns); if (!is_dir($dir)) { return []; } $result = []; $files = scandir($dir); foreach ($files as $file) { if ($file === '.' || $file === '..') { continue; } if (is_file($dir . $file)) { $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); $isImage = in_array($ext, ['jpg', 'jpeg', 'png', 'gif'], true); $result[] = [ 'name' => $file, 'size' => filesize($dir . $file), 'is_image' => $isImage, 'ext' => $ext ]; } } return $result; } /** * Безопасная обработка и загрузка файла из глобального массива $_FILES */ public function upload(string $ns): bool { if (!isset($_FILES['uploadfile'])) { return false; } $error = $_FILES['uploadfile']['error']; if ($error !== UPLOAD_ERR_OK) { return false; } $name = $_FILES['uploadfile']['name']; $tmp_name = $_FILES['uploadfile']['tmp_name']; // Очищаем имя файла от опасных символов $filename = preg_replace('/[^a-zA-Z0-9_\-\.]/', '', $name); $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); // Жесткая проверка: если расширения нет в белом списке — бракуем загрузку if (!in_array($ext, $this->allowedTypes, true)) { return false; } $targetDir = $this->resolveDir($ns); if (!is_dir($targetDir)) { mkdir($targetDir, 0755, true); } // Переносим файл из временной папки сервера в каталог data/media/ return move_uploaded_file($tmp_name, $targetDir . $filename); } public function delete(string $ns, string $filename): bool { $filename = preg_replace('/[^a-zA-Z0-9_\-\.]/', '', $filename); $filePath = $this->resolveDir($ns) . $filename; if (file_exists($filePath) && is_file($filePath)) { return unlink($filePath); } return false; } }