Skip to content

Commit

Permalink
create only one folder for all files
Browse files Browse the repository at this point in the history
- delete folder after
- log errors to w log file
  • Loading branch information
vincent-peugnet committed Oct 12, 2024
1 parent 8237680 commit 5353748
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
9 changes: 7 additions & 2 deletions app/class/Modelmedia.php
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,7 @@ public function multiupload(string $index, string $target, bool $idclean = false
$count = 0;
$successcount = 0;
$failedconversion = 0;
$tmpdir = mktmpdir('w-media-upload');
foreach ($_FILES[$index]['name'] as $filename) {
$fileinfo = pathinfo($filename);
if ($idclean) {
Expand All @@ -242,7 +243,7 @@ public function multiupload(string $index, string $target, bool $idclean = false

$from = $_FILES[$index]['tmp_name'][$count];
$count++;
$to = mktmpdir('w-media-upload') . '/' . $id . '.' . $extension;
$to = "$tmpdir/$id.$extension";
if (move_uploaded_file($from, $to)) {
try {
$media = new Media($to);
Expand All @@ -251,14 +252,18 @@ public function multiupload(string $index, string $target, bool $idclean = false
}
if (rename($media->getabsolutepath(), $target . $media->filename())) {
$successcount++;
} else {
Logger::error('failed to move file from tmp dir to media folder');
}
} catch (Fileexception $e) {
// transfert failed
Logger::errorex($e);
} catch (RuntimeException | ImagickException $e) {
Logger::errorex($e);
$failedconversion++;
}
}
}
rmdir($tmpdir);

if ($successcount < $count || $failedconversion > 0) {
$message = "$successcount / $count files have been uploaded";
Expand Down
6 changes: 4 additions & 2 deletions app/fn/fn.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use Wcms\Folderexception;

function readablesize($bytes, $base = 2 ** 10)
{
$format = '%d&nbsp;%s';
Expand Down Expand Up @@ -440,15 +442,15 @@ function get_temp_dir()
* @param string $prefix A prefix to suit your case (It is nice to precise that it is related to W)
* @return string Absolute created path without trailing slash
*
* @throws RuntimeException If creation failed
* @throws Folderexception If creation failed
*/
function mktmpdir(string $prefix): string
{
$tmp = get_temp_dir();
$randstr = dechex(mt_rand() % (2 << 16));
$path = "$tmp/$prefix-$randstr";
if (!mkdir($path)) {
throw new RuntimeException("cannot create tmp dir '$path'");
throw new Folderexception("cannot create tmp dir '$path'");
}
return $path;
}

0 comments on commit 5353748

Please sign in to comment.