It's an ugly hack, but this is the simplest way I found to prevent a file from being deleted. It works by hooking file_delete
and then removing the uri
property from the $file
variable. Without the uri, Drupal is unable to delete the file.
// Think twice before using this ugly hack.
// It probably breaks something and kills kittens.
function mymodule_file_delete($file) {
$path = drupal_realpath($file->uri);
if (!is_dir($path) && is_file($path)) {
if (preg_match('/insert_regex_here/', $path)) {
$file->uri = NULL;
}
}
}
The other alternatives I considered were:
- Hacking core
Although hacking core is taboo, it would be a cleaner solution than the hook I use above.
- Using file_usage_add() on each file I want to retain
Doesn't fit my use case very well - tens of thousands of files created and deleted independently of Drupal. Synchronizing all those files with file_usage_add
would be daunting.
- Use Media module to reference the file paths
Media seems like overkill and it isn't stable yet. Plus I'm not sure if it would do what I need.