Skip to content

Commit

Permalink
Improvements to uploaded file garbage collection
Browse files Browse the repository at this point in the history
  • Loading branch information
billtomczak committed Sep 11, 2019
1 parent 26f042a commit 60d501a
Showing 1 changed file with 34 additions and 15 deletions.
49 changes: 34 additions & 15 deletions src/admin/models/file.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,8 @@ public function save($data)
// File URL takes precedence over File Path
if (empty($data['file_url'])) {
$this->uploadFile($data);

} else {
$this->clearFilePath($data);
}

} catch (Exception $e) {
$this->setError($e->getMessage());
return false;
Expand All @@ -176,23 +174,45 @@ public function save($data)
return false;
}

return parent::save($data);
if (parent::save($data)) {
$this->gcFileUploads();

return true;
}

return false;
}

public function delete(&$pks)
{
if (parent::delete($pks)) {
$this->gcFileUploads();

return true;
}

return false;
}

/**
* Clear file_path in the submitted data and delete the file
*
* @param array $data
* Check for any files in the upload folder that are not linked
*/
protected function clearFilePath(array &$data)
protected function gcFileUploads()
{
$currentFile = empty($data['file_path']) ? null : $data['file_path'];
$currentFilePath = $this->uploadDir . '/' . $currentFile;
if (file_exists($currentFilePath)) {
unlink($currentFilePath);
}
$db = $this->getDbo();

$query = $db->getQuery(true)
->select('file_path')
->from('#__osdownloads_documents')
->where('file_path != ' . $db->quote(''));

$data['file_path'] = '';
$files = $db->setQuery($query)->loadColumn();
$uploadedFiles = JFolder::files($this->uploadDir);

$unlinkedFiles = array_diff($uploadedFiles, $files);
foreach ($unlinkedFiles as $file) {
@unlink($this->uploadDir . '/' . $file);
}
}

/**
Expand Down Expand Up @@ -285,7 +305,6 @@ protected function uploadFile(&$data)
throw new Exception($uploadErrorMessage);
}

$this->clearFilePath($data);
$data['file_path'] = $fileHash;

return;
Expand Down

0 comments on commit 60d501a

Please sign in to comment.