/** * Returns the destination path/fileName of a unique fileName/foldername in that path. * If $theFile exists in $theDest (directory) the file have numbers appended up to $this->maxNumber. Hereafter a unique string will be appended. * This function is used by fx. TCEmain when files are attached to records and needs to be uniquely named in the uploads/* folders * * @param Folder $folder * @param string $theFile The input fileName to check * @param bool $dontCheckForUnique If set the fileName is returned with the path prepended without checking whether it already existed! * * @throws \RuntimeException * @return string A unique fileName inside $folder, based on $theFile. * @see \TYPO3\CMS\Core\Utility\File\BasicFileUtility::getUniqueName() */ protected function getUniqueName(Folder $folder, $theFile, $dontCheckForUnique = FALSE) { static $maxNumber = 99, $uniqueNamePrefix = ''; // Fetches info about path, name, extention of $theFile $origFileInfo = GeneralUtility::split_fileref($theFile); // Adds prefix if ($uniqueNamePrefix) { $origFileInfo['file'] = $uniqueNamePrefix . $origFileInfo['file']; $origFileInfo['filebody'] = $uniqueNamePrefix . $origFileInfo['filebody']; } // Check if the file exists and if not - return the fileName... $fileInfo = $origFileInfo; // The destinations file $theDestFile = $fileInfo['file']; // If the file does NOT exist we return this fileName if (!$this->driver->fileExistsInFolder($theDestFile, $folder->getIdentifier()) || $dontCheckForUnique) { return $theDestFile; } // Well the fileName in its pure form existed. Now we try to append // numbers / unique-strings and see if we can find an available fileName // This removes _xx if appended to the file $theTempFileBody = preg_replace('/_[0-9][0-9]$/', '', $origFileInfo['filebody']); $theOrigExt = $origFileInfo['realFileext'] ? '.' . $origFileInfo['realFileext'] : ''; for ($a = 1; $a <= $maxNumber + 1; $a++) { // First we try to append numbers if ($a <= $maxNumber) { $insert = '_' . sprintf('%02d', $a); } else { $insert = '_' . substr(md5(uniqId('')), 0, 6); } $theTestFile = $theTempFileBody . $insert . $theOrigExt; // The destinations file $theDestFile = $theTestFile; // If the file does NOT exist we return this fileName if (!$this->driver->fileExistsInFolder($theDestFile, $folder->getIdentifier())) { return $theDestFile; } } throw new \RuntimeException('Last possible name "' . $theDestFile . '" is already taken.', 1325194291); }