How to add a file lock to all existing files in directory I've just started using file lock to prevent images getting deleted, so we can build up a store of images for use at a later date. I think this module will solve a problem I've had, but only for images uploaded from this point forward.

How can I also apply this protection retrospectively to:


Images already in file fields
Images uploaded by FTP (well, you know, SFTP )
To add a file_lock usage record for all existing files without one:

INSERT INTO file_usage (fid, module, `type`, id, `count`)
SELECT fid, 'file_lock' module, 'module' `type`, 0 id, 1 `count`
FROM file_managed 
WHERE status AND NOT EXISTS (
  SELECT id FROM file_usage
  WHERE file_managed.fid = file_usage.fid
        AND `type`='module'
        AND id=0
        AND `module` = 'file_lock'
        AND `count`&gt;0
);


To add a file_lock record for all files in a directory that are NOT registered in the file_managed table

Here I loop through all likely image files in and write them as public:// file_managed records if none exists.


preg_ls is not PHP/Drupal core - nicked it from PHP comment - v useful!
I exclude the styles/ directory which stores the variants made by different
image styles. I also exclude the images/backup/ directory - this is
particular to my needs, but I left the code in as you'll likely have
something to exclude too.
This assumes you have no private:// files and that everything under sites/default/files is to be a public:// file. do not run this as it is if you use private files at all!
It also assumes that on file_save, file_lock will add its own lock (based on your config for file_lock).


And now the code:

$dir = DRUPAL_ROOT . "/sites/default/files/";
foreach (preg_ls($dir, true, '/\.(jpe?g|gif|png|bmp)$/i') as $_) {

  $_ = substr($_, strlen($dir));
  if (preg_match('@^(styles/|images/backup/)@', $_)) {
    continue;
  }

  $uri = "public://$_";
  if (!db_query("SELECT fid FROM {file_managed} WHERE uri = :uri",[':uri' =&gt; $uri])-&gt;rowCount()) {
    $file = new stdClass();
    $file-&gt;fid = NULL;
    $file-&gt;uri = $uri;
    $file-&gt;filename = drupal_basename($uri);
    $file-&gt;filemime = file_get_mimetype($file-&gt;uri);
    $file-&gt;uid = $user-&gt;uid;
    $file-&gt;status = FILE_STATUS_PERMANENT;
    file_save($file);
  }
}