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`>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' => $uri])->rowCount()) {
$file = new stdClass();
$file->fid = NULL;
$file->uri = $uri;
$file->filename = drupal_basename($uri);
$file->filemime = file_get_mimetype($file->uri);
$file->uid = $user->uid;
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
}
}