function auditfiles_merge_files in Audit Files 7.3
Same name and namespace in other branches
- 7.4 auditfiles.module \auditfiles_merge_files()
Merges selected files.
This function takes all files given it and changes all their usages to point to the initial file, then removes their reference for all but the first file from the file managed table and then also removes the files from the file system.
This function does not verify that the files are actually duplicates. The assumption is made that the user has already done that.
Parameters
array $files: An array of file objects, keyed by file ID.
array $context: The context the action is executed in.
File
- ./
auditfiles.module, line 320 - Implements various Drupal hooks.
Code
function auditfiles_merge_files(array &$files, array $context) {
// Make sure that more than one file was selected.
if (count($files) > 1) {
// Remove the file being kept from the array of files, so it is not deleted.
$kept_file = $files[$context['file_being_kept']];
unset($files[$context['file_being_kept']]);
// Get the data for the record being kept.
$results = db_select('file_usage', 'fu')
->fields('fu', array(
'id',
'count',
))
->condition('fid', $kept_file->fid)
->execute()
->fetchAll();
if (empty($results)) {
$message = t('There was no file usage data found for the file you choose to keep. No changes were made.');
drupal_set_message($message, 'warning');
return;
}
$kept_file_data = reset($results);
// Iterate through the rest of the files in the array.
foreach ($files as $file) {
// Get the file data of the file being compared.
$results = db_select('file_usage', 'fu')
->fields('fu', array(
'id',
'count',
))
->condition('fid', $file->fid)
->execute()
->fetchAll();
if (empty($results)) {
$message = t('There was an error retrieving the file usage data from the database for file ID !fid. Please check the files in one of the other reports. No changes were made for this file.', array(
'!fid' => $file->fid,
));
drupal_set_message($message, 'warning');
continue;
}
$compared_file_data = reset($results);
// Compare it with the kept file.
if ($kept_file_data->id == $compared_file_data->id) {
// If it matches, update the kept file and delete the one being
// compared.
$kept_file_data->count += $compared_file_data->count;
// Delete the unnecessary entry from the file_usage table.
db_delete('file_usage')
->condition('fid', $file->fid)
->execute();
}
else {
// If it does not match, update the one being compared.
// Make the file usages point to the fid of the file being kept.
db_update('file_usage')
->fields(array(
'fid' => $kept_file->fid,
))
->condition('fid', $file->fid)
->execute();
}
// Delete the unnecessary entries from the file_managed table.
db_delete('file_managed')
->condition('fid', $file->fid)
->execute();
// Delete the duplicate file.
file_unmanaged_delete($file->uri);
}
}
else {
$message = t('More than one file must be selected in order to merge them. No changes were made.');
drupal_set_message($message, 'warning');
}
}