Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
refs #2338 use '(n)' suffix instead of timestamp prefix to make sure …
…attachment names are unique

Signed-off-by: Julien Veyssier <[email protected]>
  • Loading branch information
Julien Veyssier authored and backportbot-nextcloud[bot] committed May 9, 2022
commit e7f130d46404f6ed38f740f70dd5ba26a3cd6570
23 changes: 20 additions & 3 deletions lib/Service/ImageService.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public function uploadImage(int $documentId, string $newFileName, $newFileResour
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,
Expand All @@ -179,7 +179,7 @@ public function uploadImagePublic(?int $documentId, string $newFileName, $newFil
}
$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,
Expand Down Expand Up @@ -221,7 +221,7 @@ public function insertImageFile(int $documentId, string $path, string $userId):
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
Expand All @@ -236,6 +236,23 @@ private function copyImageFile(File $imageFile, Folder $saveDir, File $textFile)
];
}

/**
* 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
*
Expand Down