function tmgmt_file_file_download

Implements hook_file_download().

File

translators/tmgmt_file/tmgmt_file.module, line 100
Module file of the translation management test module.

Code

function tmgmt_file_file_download($uri) {

  // Get the file record based on the URI. If not in the database just return.
  $fids = \Drupal::entityQuery('file')
    ->accessCheck(TRUE)
    ->condition('uri', $uri)
    ->execute();
  if ($fids) {
    $files = \Drupal\file\Entity\File::loadMultiple($fids);
    foreach ($files as $item) {

      // Since some database servers sometimes use a case-insensitive comparison
      // by default, double check that the filename is an exact match.
      if ($item
        ->getFileUri() === $uri) {
        $file = $item;
        break;
      }
    }
  }
  if (!isset($file)) {
    return;
  }

  // Check if this file belongs to a job.
  $usage_list = \Drupal::service('file.usage')
    ->listUsage($file);
  if (!isset($usage_list['tmgmt_file']['tmgmt_job'])) {
    return;
  }
  foreach (Job::loadMultiple(array_keys($usage_list['tmgmt_file']['tmgmt_job'])) as $job) {
    if ($job
      ->access('view')) {

      // Access is granted.
      $headers = file_get_content_headers($file);
      return $headers;
    }
  }

  // Returning nothing means access denied unless another module specifically
  // grants access.
}