You are here

function file_force_file_download in File Force Download 7

Same name and namespace in other branches
  1. 5 file_force.module \file_force_file_download()
  2. 6.2 file_force.module \file_force_file_download()
  3. 6 file_force.module \file_force_file_download()

Implements hook_file_download().

This is what adds the headers which activates the force downloading.

File

./file_force.module, line 49
File Force Download module.

Code

function file_force_file_download($uri) {
  if (!isset($_GET['download'])) {

    // Our menu hook wasn't called, so we should ignore this.
    return FALSE;
  }
  if ($_GET['download'] == 1) {
    $disposition = 'attachment';
  }
  elseif ($_GET['download'] == 0) {
    $disposition = 'inline';
  }
  else {

    // We only use 1 and 0.
    return FALSE;
  }
  $scheme = file_uri_scheme($uri);
  if ($scheme == 'private') {

    // Check with all other modules if the file is allowed for the download
    $headers = array();
    foreach (module_implements('file_download') as $module) {
      if ($module == 'file_force') {
        continue;

        // Do not call ourselves.
      }
      $function = $module . '_file_download';
      $result = $function($uri);
      if ($result == -1) {

        // Throw away the headers received so far.
        $headers = array();
        break;
      }
      if (isset($result) && is_array($result)) {
        $headers = array_merge($headers, $result);
      }
    }
    if (!count($headers)) {
      return FALSE;
    }
  }

  // Attempt to give the file its original name (as stored in {file_managed}.filename), like file_file_download() does.
  // Get the file record based on the URI. If not in the database just return.
  $files = file_load_multiple(array(), array(
    'uri' => $uri,
  ));
  if (count($files)) {
    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->uri === $uri) {
        $file = $item;
        break;
      }
    }
  }
  if (isset($file)) {
    $name = $file->filename;
  }
  else {

    // Use uri for the name if file record is not found.
    $name = basename($uri);
  }

  // Return a list of headers that will force the download
  return array(
    'Content-Disposition' => $disposition . '; filename="' . mime_header_encode($name) . '"',
  );
}