ogcore/src/Controller/AssetManagerController.php

161 lines
6.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use ZipArchive;
class AssetManagerController extends AbstractController {
private function getSecureTargetPath(string $projectDir, string $requestedPath): ?string
{
$baseAssetsDir = $projectDir . '/public/assets';
$result = null;
if (!is_dir($baseAssetsDir)) {
mkdir($baseAssetsDir, 0755, true);
}
$realBase = realpath($baseAssetsDir);
if (strpos($requestedPath, '..') === false) {
$theoreticalPath = rtrim($realBase . '/' . ltrim($requestedPath, '/\\'), '/');
if (!file_exists($theoreticalPath)) {
$result = $theoreticalPath;
} else {
$realTarget = realpath($theoreticalPath);
if ($realTarget !== false && str_starts_with($realTarget, $realBase)) {
$result = $realTarget;
}
}
}
return $result;
}
#[Route('/ogassets/list', name: 'api_assets_list', methods: ['GET'])]
public function listAssets(Request $request, ParameterBagInterface $params): JsonResponse
{
$requestedPath = $request->query->get('path', '');
$targetPath = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath);
$response = null;
if ($targetPath === null || !is_dir($targetPath)) {
$response = new JsonResponse(['message' => 'Directorio inválido o no encontrado.'], Response::HTTP_NOT_FOUND);
} else {
$items = [];
$iterator = new \DirectoryIterator($targetPath);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isDot()) continue;
$items[] = [
'name' => $fileinfo->getFilename(),
'type' => $fileinfo->isDir() ? 'folder' : 'file',
'size' => $fileinfo->isFile() ? $fileinfo->getSize() : null,
'path' => ltrim($requestedPath . '/' . $fileinfo->getFilename(), '/')
];
}
usort($items, function($a, $b) {
if ($a['type'] === $b['type']) {
return strcasecmp($a['name'], $b['name']);
}
return $a['type'] === 'folder' ? -1 : 1;
});
$response = new JsonResponse($items, Response::HTTP_OK);
}
return $response;
}
#[Route('/ogassets/upload', name: 'api_assets_upload', methods: ['POST'])]
public function uploadAsset(Request $request, ParameterBagInterface $params, Filesystem $filesystem): JsonResponse
{
$file = $request->files->get('file');
$requestedPath = $request->request->get('path', '');
$extractZip = $request->request->getBoolean('extractZip', false);
$response = null;
if (!$file) {
$response = new JsonResponse(['message' => 'No file uploaded.'], Response::HTTP_BAD_REQUEST);
} else {
$targetDir = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath);
if ($targetDir === null) {
$response = new JsonResponse(['message' => 'Ruta destino inválida.'], Response::HTTP_FORBIDDEN);
} else {
if (!is_dir($targetDir)) {
mkdir($targetDir, 0755, true);
$targetDir = realpath($targetDir);
}
$originalName = $file->getClientOriginalName();
$extension = strtolower($file->getClientOriginalExtension());
if ($extractZip && $extension === 'zip') {
$safeName = preg_replace('/[^a-zA-Z0-9_\-]/', '_', pathinfo($originalName, PATHINFO_FILENAME));
$extractDir = $targetDir . '/' . $safeName;
if (!$filesystem->exists($extractDir)) {
$filesystem->mkdir($extractDir, 0755);
}
$zip = new ZipArchive();
if ($zip->open($file->getPathname()) === true) {
$zip->extractTo($extractDir);
$zip->close();
$response = new JsonResponse(['message' => 'ZIP extraído correctamente.']);
} else {
$response = new JsonResponse(['message' => 'Error al extraer ZIP.'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
} else {
try {
$file->move($targetDir, $originalName);
$response = new JsonResponse(['message' => 'Archivo subido correctamente.']);
} catch (\Exception $e) {
$response = new JsonResponse(['message' => 'Error al guardar el archivo.'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
}
}
return $response;
}
#[Route('/ogassets/delete', name: 'api_assets_delete', methods: ['DELETE'])]
public function deleteAsset(Request $request, ParameterBagInterface $params, Filesystem $filesystem): JsonResponse
{
$data = json_decode($request->getContent(), true);
$requestedPath = $data['path'] ?? '';
$response = null;
if (empty($requestedPath)) {
$response = new JsonResponse(['message' => 'Ruta requerida.'], Response::HTTP_BAD_REQUEST);
} else {
$realBase = realpath($params->get('kernel.project_dir') . '/public/assets');
$targetPath = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath);
if ($targetPath === null || !file_exists($targetPath) || $targetPath === $realBase) {
$response = new JsonResponse(['message' => 'Ruta inválida o prohibida.'], Response::HTTP_FORBIDDEN);
} else {
try {
$filesystem->remove($targetPath);
$response = new JsonResponse(['message' => 'Elemento eliminado correctamente.']);
} catch (\Exception $e) {
$response = new JsonResponse(['message' => 'Error al eliminar el elemento.'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
}
return $response;
}
}