diff options
author | Julien Veyssier <eneiluj@posteo.net> | 2022-05-09 12:54:24 +0300 |
---|---|---|
committer | Julien Veyssier <eneiluj@posteo.net> | 2022-05-09 13:46:27 +0300 |
commit | 6759366d120160b04b50cd12decc65f42df36628 (patch) | |
tree | 16cfbeae1dc8fa4e00467864d73712f706c53178 /lib | |
parent | d01d0b3713213762a57829fb49c9917db5fb8c60 (diff) |
refs #2338 use '(n)' suffix instead of timestamp prefix to make sure attachment names are unique
Signed-off-by: Julien Veyssier <eneiluj@posteo.net>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/Service/ImageService.php | 23 |
1 files changed, 20 insertions, 3 deletions
diff --git a/lib/Service/ImageService.php b/lib/Service/ImageService.php index df22d374f..69b65a0ed 100644 --- a/lib/Service/ImageService.php +++ b/lib/Service/ImageService.php @@ -152,7 +152,7 @@ class ImageService { throw new NotPermittedException('No write permissions'); } $saveDir = $this->getAttachmentDirectoryForFile($textFile, true); - $fileName = (string) time() . '-' . $newFileName; + $fileName = $this->getUniqueFileName($saveDir, $newFileName); $savedFile = $saveDir->newFile($fileName, $newFileResource); return [ 'name' => $fileName, @@ -179,7 +179,7 @@ class ImageService { } $textFile = $this->getTextFilePublic($documentId, $shareToken); $saveDir = $this->getAttachmentDirectoryForFile($textFile, true); - $fileName = (string) time() . '-' . $newFileName; + $fileName = $this->getUniqueFileName($saveDir, $newFileName); $savedFile = $saveDir->newFile($fileName, $newFileResource); return [ 'name' => $fileName, @@ -221,7 +221,7 @@ class ImageService { private function copyImageFile(File $imageFile, Folder $saveDir, File $textFile): array { $mimeType = $imageFile->getMimeType(); if (in_array($mimeType, ImageController::IMAGE_MIME_TYPES, true)) { - $fileName = (string) time() . '-' . $imageFile->getName(); + $fileName = $this->getUniqueFileName($saveDir, $imageFile->getName()); $targetPath = $saveDir->getPath() . '/' . $fileName; $targetFile = $imageFile->copy($targetPath); // get file type and name @@ -237,6 +237,23 @@ class ImageService { } /** + * Get unique file name in a directory. Add '(n)' suffix. + * @param Folder $dir + * @param string $fileName + * @return string + */ + private function getUniqueFileName(Folder $dir, string $fileName): string { + $extension = pathinfo($fileName, PATHINFO_EXTENSION); + $counter = 1; + $uniqueFileName = $fileName; + while ($dir->nodeExists($uniqueFileName)) { + $counter++; + $uniqueFileName = preg_replace('/\.' . $extension . '$/', ' (' . $counter . ').' . $extension, $fileName); + } + return $uniqueFileName; + } + + /** * Check if the shared access has write permissions * * @param string $shareToken |