Delete formatted images after image upload

This change fixes an issue where old/existing formatted images are used
when a filename is reused (by overwrite or by coincidence), regardless
of if the file contents have changed. To users this mainly manifests
as a file overwrite appearing not to work; the thumbnails in the CMS
show the original image until regeneration is forced.

Calling Image::deleteFormattedImages() after image upload ensures that
no stagnant formatted images will be used.
This commit is contained in:
Stephen Holdaway 2014-04-02 13:30:12 +13:00
parent 93ca3f7f23
commit 3be01968ec
3 changed files with 48 additions and 0 deletions

View File

@ -186,6 +186,7 @@ class Upload extends Controller {
// This is to prevent it from trying to rename the file
$this->file->Name = basename($relativeFilePath);
$this->file->write();
$this->file->onAfterUpload();
$this->extend('onAfterLoad', $this->file); //to allow extensions to e.g. create a version after an upload
return true;
} else {

View File

@ -641,6 +641,11 @@ class Image extends File {
}
}
public function onAfterUpload() {
$this->deleteFormattedImages();
parent::onAfterUpload();
}
protected function onBeforeDelete() {
parent::onBeforeDelete();

View File

@ -465,6 +465,48 @@ class UploadTest extends SapphireTest {
$file3->delete();
}
public function testDeleteResampledImagesOnUpload() {
$tmpFileName = 'UploadTest-testUpload.jpg';
$tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName;
$uploadImage = function() use ($tmpFileName, $tmpFilePath) {
copy(__DIR__ . '/gdtest/test_jpg.jpg', $tmpFilePath);
// emulates the $_FILES array
$tmpFile = array(
'name' => $tmpFileName,
'type' => 'text/plaintext',
'size' => filesize($tmpFilePath),
'tmp_name' => $tmpFilePath,
'extension' => 'jpg',
'error' => UPLOAD_ERR_OK,
);
$v = new UploadTest_Validator();
// test upload into default folder
$u = new Upload();
$u->setReplaceFile(true);
$u->setValidator($v);
$u->load($tmpFile);
return $u->getFile();
};
// Image upload and generate a resampled image
$image = $uploadImage();
$resampled = $image->ResizedImage(123, 456);
$resampledPath = $resampled->getFullPath();
$this->assertTrue(file_exists($resampledPath));
// Re-upload the image, overwriting the original
// Resampled images should removed when their parent file is overwritten
$image = $uploadImage();
$this->assertFalse(file_exists($resampledPath));
unlink($tmpFilePath);
$image->delete();
}
}
class UploadTest_Validator extends Upload_Validator implements TestOnly {