From 90b8ea15ffff564358d2532e8c3d7033e4a48b23 Mon Sep 17 00:00:00 2001 From: Bernd Bestel Date: Fri, 2 Jul 2021 20:50:52 +0200 Subject: [PATCH] Also delete downscaled image files when deleting an image (closes #1499) --- controllers/FilesApiController.php | 7 +------ services/FilesService.php | 32 +++++++++++++++++++++++++----- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/controllers/FilesApiController.php b/controllers/FilesApiController.php index 866bb70f..131d02df 100644 --- a/controllers/FilesApiController.php +++ b/controllers/FilesApiController.php @@ -25,12 +25,7 @@ class FilesApiController extends BaseApiController throw new \Exception('Invalid filename'); } - $filePath = $this->getFilesService()->GetFilePath($args['group'], $fileName); - - if (file_exists($filePath)) - { - unlink($filePath); - } + $this->getFilesService()->DeleteFile($args['group'], $fileName); return $this->EmptyApiResponse($response); } diff --git a/services/FilesService.php b/services/FilesService.php index 8c1483ec..86aad2a0 100644 --- a/services/FilesService.php +++ b/services/FilesService.php @@ -19,11 +19,6 @@ class FilesService extends BaseService $fileNameDownscaled = $fileNameWithoutExtension . '__downscaledto' . ($bestFitHeight ? $bestFitHeight : 'auto') . 'x' . ($bestFitWidth ? $bestFitWidth : 'auto') . '.' . $fileExtension; $filePathDownscaled = $this->GetFilePath($group, $fileNameDownscaled); - if (!extension_loaded('gd')) - { - return $filePath; - } - try { if (!file_exists($filePathDownscaled)) @@ -54,6 +49,33 @@ class FilesService extends BaseService return $filePathDownscaled; } + public function DeleteFile($group, $fileName) + { + $filePath = $this->GetFilePath($group, $fileName); + + if (file_exists($filePath)) + { + $fileNameWithoutExtension = pathinfo($filePath, PATHINFO_FILENAME); + $fileExtension = pathinfo($filePath, PATHINFO_EXTENSION); + + if (getimagesize($filePath) !== false) // Then the file is an image + { + // Also delete all corresponding "__downscaledto" files when deleting an image + $groupFolderPath = $this->StoragePath . '/' . $group; + $files = scandir($groupFolderPath); + foreach($files as $file) + { + if (string_starts_with($file, $fileNameWithoutExtension . '__downscaledto')) + { + unlink($this->GetFilePath($group, $file)); + } + } + } + + unlink($filePath); + } + } + public function GetFilePath($group, $fileName) { $groupFolderPath = $this->StoragePath . '/' . $group;