<?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();
}