Asset: cleaner handling of conflicting filenames

This commit is contained in:
Aaron van Geffen 2023-03-12 12:02:21 +01:00
parent 3ed84eb4d5
commit 244af88a9a
2 changed files with 8 additions and 8 deletions

View File

@ -33,14 +33,10 @@ class UploadMedia extends HTMLController
if (empty($uploaded_file))
continue;
// DIY slug club.
$slug = $tag->slug . '/' . strtr($uploaded_file['name'], [' ' => '-', '--' => '-', '&' => 'and', '=>' => '', "'" => "", ":"=> "", '\\' => '-']);
$asset = Asset::createNew([
'filename_to_copy' => $uploaded_file['tmp_name'],
'preferred_filename' => $uploaded_file['name'],
'preferred_subdir' => $tag->slug,
'slug' => $slug,
]);
$new_ids[] = $asset->getId();

View File

@ -187,9 +187,10 @@ class Asset
$new_filename = $preferred_filename;
$destination = ASSETSDIR . '/' . $preferred_subdir . '/' . $preferred_filename;
while (file_exists($destination))
for ($i = 1; file_exists($destination); $i++)
{
$filename = pathinfo($preferred_filename, PATHINFO_FILENAME) . '_' . mt_rand(10, 99);
$suffix = $i;
$filename = pathinfo($preferred_filename, PATHINFO_FILENAME) . ' (' . $suffix . ')';
$extension = pathinfo($preferred_filename, PATHINFO_EXTENSION);
$new_filename = $filename . '.' . $extension;
$destination = dirname($destination) . '/' . $new_filename;
@ -206,11 +207,14 @@ class Asset
$mimetype = finfo_file($finfo, $destination);
finfo_close($finfo);
// We're going to need the base name a few times...
$basename = pathinfo($new_filename, PATHINFO_FILENAME);
// Do we have a title yet? Otherwise, use the filename.
$title = isset($data['title']) ? $data['title'] : pathinfo($preferred_filename, PATHINFO_FILENAME);
$title = $data['title'] ?? $basename;
// Same with the slug.
$slug = isset($data['slug']) ? $data['slug'] : $preferred_subdir . '/' . pathinfo($preferred_filename, PATHINFO_FILENAME);
$slug = $data['slug'] ?? sprintf('%s/%s', $preferred_subdir, $basename);
// Detected an image?
if (substr($mimetype, 0, 5) == 'image')