You are here

function webform_protected_downloads_file_download in Webform Protected Downloads 7

Same name and namespace in other branches
  1. 6 webform_protected_downloads.module \webform_protected_downloads_file_download()

Implementation of hook_file_download().

Parameters

string $filepath:

File

./webform_protected_downloads.module, line 189
This file contains hook declarations and functions for the Webform Protected Downloads module.

Code

function webform_protected_downloads_file_download($uri) {
  global $conf;
  $admin_access = user_access('administer webform protected downloads');

  // 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;
      }
    }
  }

  // no file found, it is not up to us to handle this
  if (!isset($file)) {
    return NULL;
  }

  // check if the file is registered as protected
  $count = db_select('wpd_protected_files', 'p')
    ->fields('p')
    ->condition('fid', $file->fid)
    ->countQuery()
    ->execute()
    ->fetchColumn();
  if (!$count) {
    return NULL;
  }

  // now we know, that this is a protected file
  // get all nodes that this file has been attached to
  $result = db_select('file_usage', 'f')
    ->fields('f')
    ->condition('fid', $file->fid)
    ->condition('module', 'file')
    ->condition('type', 'node')
    ->execute();
  while ($record = $result
    ->fetchObject()) {
    $nid = $record->id;

    // check if the file is protected for this node
    if (webform_protected_downloads_file_is_protected($nid, $file->fid)) {

      // don't cache access allowed or denied
      $conf['cache'] = 0;

      // check if the current user should be granted access to this file
      if (webform_protected_downloads_file_user_has_access($nid, $file->fid) || $admin_access) {

        // access granted
        return file_get_content_headers($file);
      }
      else {

        // access denied
        return -1;
      }
    }
  }

  // file is not protected so we have nothing to say
  return NULL;
}