You are here

function commerce_file_file_download in Commerce File 7.2

Same name and namespace in other branches
  1. 8.2 commerce_file.module \commerce_file_file_download()
  2. 7 commerce_file.module \commerce_file_file_download()

Implements hook_file_download().

File

./commerce_file.module, line 191
Extends Commerce License with the ability to sell access to files.

Code

function commerce_file_file_download($uri) {
  $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;
      }
    }
  }

  // No file found, or a temporary file found, do nothing.
  if (!isset($file) || $file->status != FILE_STATUS_PERMANENT) {
    return;
  }

  // This file is not licensable, do nothing.
  if (!commerce_file_is_licensable($file)) {
    return;
  }
  $op = 'download';

  // If we're checking access for an image derivative, check access for "view",
  // not "download". Derivatives don't increase the download count and work
  // even when the download limit has been reached.
  $menu_item = menu_get_item();
  if ($menu_item['path'] == 'system/files/styles/%') {
    $op = 'view';
  }

  // Perform the access check, and bubble-up any failures.
  if (!commerce_file_access($op, $file)) {
    return -1;
  }

  // Ensure that the download gets logged.
  if ($op == 'download') {
    commerce_file_set_request_file($file);
  }
}