hook_file_download() example breaks other modules files

Created on 7 December 2016, about 8 years ago
Updated 3 June 2024, 7 months ago

The example for https://api.drupal.org/api/drupal/modules!system!system.api.php/function...

  • Uses file_prepare_directory() to determine if it's managed by the current module but this function will always return false if passed a file
  • Doesn't return NULL if a file is not managed by the current module because it never checks this
  • If the user doesn't have the 'access user profiles' permission they will not be able to see private files managed by another module because it always thinks it manages every file
  • If the user does have 'access user profiles' the 'Content-Type' header is set to NULL so files that aren't images are displayed as binary because it always sets the 'Content-Type' header to NULL

Should be something like:

function hook_file_download($uri) {
  // Check if the file is controlled by the current module.
  $files = file_load_multiple(array(), array('uri' => $uri));
  $file = reset($files);
  if ($file) {
    $usage = file_usage_list($file);
    if (isset($usage['user'])) {
      if (user_access('access user profiles')) {
        $info = image_get_info($uri);
        return array('Content-Type' => $info['mime_type']);
      }
      else {
        // Access to the file is denied.
        return -1;
      }
    }
    else {
      // File is not controlled by the current module
      return NULL;
    }
  }
}
πŸ“Œ Task
Status

Active

Version

7.0 ⚰️

Component
DocumentationΒ  β†’

Last updated 1 day ago

No maintainer
Created by

πŸ‡ΊπŸ‡ΈUnited States Reuben Unruh

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024