function image_file_download

Same name in other branches
  1. 7.x modules/image/image.module \image_file_download()
  2. 9 core/modules/image/image.module \image_file_download()
  3. 10 core/modules/image/image.module \image_file_download()
  4. 11.x core/modules/image/image.module \image_file_download()

Implements hook_file_download().

Control the access to files underneath the styles directory.

File

core/modules/image/image.module, line 182

Code

function image_file_download($uri) {
    $path = StreamWrapperManager::getTarget($uri);
    // Private file access for image style derivatives.
    if (strpos($path, 'styles/') === 0) {
        $args = explode('/', $path);
        // Discard "styles", style name, and scheme from the path
        $args = array_slice($args, 3);
        // Then the remaining parts are the path to the image.
        $original_uri = StreamWrapperManager::getScheme($uri) . '://' . implode('/', $args);
        // Check that the file exists and is an image.
        $image = \Drupal::service('image.factory')->get($uri);
        if ($image->isValid()) {
            // Check the permissions of the original to grant access to this image.
            $headers = \Drupal::moduleHandler()->invokeAll('file_download', [
                $original_uri,
            ]);
            // Confirm there's at least one module granting access and none denying access.
            if (!empty($headers) && !in_array(-1, $headers)) {
                return [
                    // Send headers describing the image's size, and MIME-type.
'Content-Type' => $image->getMimeType(),
                    'Content-Length' => $image->getFileSize(),
                ];
            }
        }
        return -1;
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.