You are here

function download_count_file_download_access_alter in Download Count 7.3

Implements hook_file_download_access_alter().

File

./download_count.module, line 149
Tracks file downloads for files stored in the drupal files table using the private files setting or custom private filefield.

Code

function download_count_file_download_access_alter(&$grants, $file, $entity_type, $entity) {
  $time = REQUEST_TIME;

  //if role should be skipped, return.
  if (user_access('skip download counts')) {
    return;
  }

  //if no access, simply return.
  if (!in_array(TRUE, $grants)) {
    return;
  }

  //check flood control
  $flood_limit = variable_get('download_count_flood_limit', 0);
  if ($flood_limit > 0) {
    $flood_window = variable_get('download_count_flood_window', 5);
    if (!flood_is_allowed('download_count-fid_' . $file['fid'], $flood_limit, $flood_window)) {
      return;
    }
  }

  //validate file has extension that should be counted, if not return.
  $extensions = explode(' ', drupal_strtolower(trim(variable_get('download_count_excluded_file_extensions', 'jpg jpeg gif png'))));
  if (count($extensions)) {
    $extension = drupal_strtolower(pathinfo($file['filename'], PATHINFO_EXTENSION));
    if (in_array($extension, $extensions)) {
      return;
    }
  }

  // Count the download.
  global $user;
  $entity_info = entity_get_info($entity_type);
  $ip = ip_address();
  $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL;
  $id = db_insert('download_count')
    ->fields(array(
    'fid' => $file['fid'],
    'uid' => $user->uid,
    'type' => $entity_type,
    'id' => $entity->{$entity_info['entity keys']['id']},
    'ip_address' => $ip,
    'referrer' => $referrer,
    'timestamp' => $time,
  ))
    ->execute();
  flood_register_event('download_count-fid_' . $file['fid'], 3600);
  watchdog('download_count', '%file was downloaded by user #%uid from %ip', array(
    '%file' => $file['filename'],
    '%uid' => $user->uid,
    '%ip' => $ip,
  ), WATCHDOG_NOTICE);
  if (module_exists('rules')) {
    rules_invoke_event('download_count_file_download', (object) $file, $user, $entity);
  }
}