Skip to content

Instantly share code, notes, and snippets.

@yusufhm
Last active February 25, 2024 20:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yusufhm/8a7a603bd36d93e98c7ed074d4b5d702 to your computer and use it in GitHub Desktop.
Save yusufhm/8a7a603bd36d93e98c7ed074d4b5d702 to your computer and use it in GitHub Desktop.
Drupal - Remove db entries for missing files

Drupal - Remove DB entries for missing temporary files

This script aims to address the error that often appear when running Drupal cron jobs, for temporary files that have an entry in the database but not actually existing in the file system:

[error]  Could not delete temporary file "public://example_file.pdf" during garbage collection

It can be run to get a count of the files:

drush scr /path/to/remove-missing-files.php

and then delete them:

drush scr /path/to/remove-missing-files.php delete
<?php
/**
* Get a list of temporary files that do not exist on the filesystem.
*
* Adapted from file_cron.
*
* @return array
* The list of fids.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*
* @see file_cron
*/
function get_expired_temp_files() {
$age = \Drupal::config('system.file')->get('temporary_maximum_age');
$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$result = [];
// Only delete temporary files if older than $age. Note that automatic cleanup
// is disabled if $age set to 0.
if ($age) {
$fids = Drupal::entityQuery('file')
->condition('status', FILE_STATUS_PERMANENT, '<>')
->condition('changed', REQUEST_TIME - $age, '<')
->execute();
$files = $file_storage->loadMultiple($fids);
foreach ($files as $file) {
$references = \Drupal::service('file.usage')->listUsage($file);
if (empty($references)) {
if (!file_exists($file->getFileUri())) {
$result[] = $file->id();
}
}
}
echo count($result) . " files found.\n";
}
return $result;
}
/**
* Delete DB entries for temporary files that do not exist on the filesystem.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
function delete_expired_temp_files() {
$fids = get_expired_temp_files();
if (empty($fids)) {
return;
}
$database = \Drupal::database();
$num_deleted = $database->delete('file_managed')
->condition('fid', $fids, 'IN')
->execute();
echo $num_deleted . " rows deleted.\n";
}
if (!empty($_SERVER['argv'][3]) && $_SERVER['argv'][3] === 'delete') {
delete_expired_temp_files();
}
else {
get_expired_temp_files();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment