You are here

function commerce_file_file_download in Commerce File 7

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

Implements hook_file_download().

File

./commerce_file.module, line 700
Provides integration of file licenses with Commerce

Code

function commerce_file_file_download($uri) {
  global $user;
  $account = clone $user;
  $file = NULL;

  // Get the file record based on the URI. If not in the database just return.
  // @see file_file_download()
  $files = file_load_multiple(array(), array(
    'uri' => $uri,
  ));
  if (empty($files)) {
    return;
  }
  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;
      }
    }
  }

  // PASS if the file does not exist
  if (!isset($file)) {
    return;
  }

  // PASS if the file is not permanent (ie temporary)
  if ($file->status != FILE_STATUS_PERMANENT) {
    return;
  }

  // determine if file is associated with a commerce_file field
  $references = _commerce_file_get_file_references($file, NULL, FIELD_LOAD_CURRENT, COMMERCE_FILE_FIELD_TYPE);

  // PASS if not a file in any commerce_file field
  if (empty($references)) {
    return;
  }

  // ALLOW if user has 'view' access with no license (ie. admin)
  // - Note: This stops any license logging for admin users
  if (commerce_file_license_admin_access('view', $account)) {
    return commerce_file_get_content_headers($file);
  }

  // get user's licenses for this file
  $licenses = commerce_file_license_load_by_property(array(
    $file->fid,
  ), array(), $account);

  // check license based access
  if (!empty($licenses)) {

    // find a valid license that can be downloaded by the user
    ksort($licenses);
    foreach ($licenses as $license_id => $license) {

      // trigger download hook and check download was allowed by the hook actions
      if ($license
        ->can_download($account)) {

        // return on first license allowed
        // set time limit for large files
        drupal_set_time_limit(0);

        // store current licenses in this request for use in hook_exit()
        _commerce_file_license_set_request_license($license);

        // return additional file headers and PASS to file module and others to handle
        return commerce_file_get_content_headers($file);
      }
    }
  }

  // if do not have any valid licenses ...
  // let other modules ALLOW unlicensed access to the protected file
  $grants = _commerce_file_download_unlicensed_access($file, $account, $licenses);
  if (in_array(TRUE, $grants)) {

    // If TRUE is returned, access is granted
    return commerce_file_get_content_headers($file);
  }

  // DENY ALL
  return -1;
}