function file_cron in Drupal 9
Same name and namespace in other branches
- 8 core/modules/file/file.module \file_cron()
Implements hook_cron().
File
- core/
modules/ file/ file.module, line 700 - Defines a "managed_file" Form API field and a "file" field for Field module.
Code
function file_cron() {
$age = \Drupal::config('system.file')
->get('temporary_maximum_age');
$file_storage = \Drupal::entityTypeManager()
->getStorage('file');
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
// 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')
->accessCheck(FALSE)
->condition('status', FileInterface::STATUS_PERMANENT, '<>')
->condition('changed', REQUEST_TIME - $age, '<')
->range(0, 100)
->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())) {
if (!$stream_wrapper_manager
->isValidUri($file
->getFileUri())) {
\Drupal::logger('file system')
->warning('Temporary file "%path" that was deleted during garbage collection did not exist on the filesystem. This could be caused by a missing stream wrapper.', [
'%path' => $file
->getFileUri(),
]);
}
else {
\Drupal::logger('file system')
->warning('Temporary file "%path" that was deleted during garbage collection did not exist on the filesystem.', [
'%path' => $file
->getFileUri(),
]);
}
}
// Delete the file entity. If the file does not exist, this will
// generate a second notice in the watchdog.
$file
->delete();
}
else {
\Drupal::logger('file system')
->info('Did not delete temporary file "%path" during garbage collection because it is in use by the following modules: %modules.', [
'%path' => $file
->getFileUri(),
'%modules' => implode(', ', array_keys($references)),
]);
}
}
}
}