You are here

function image_file_download in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 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 159
Exposes global functionality for creating image styles.

Code

function image_file_download($uri) {
  $path = file_uri_target($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 = file_uri_scheme($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', array(
        $original_uri,
      ));

      // Confirm there's at least one module granting access and none denying access.
      if (!empty($headers) && !in_array(-1, $headers)) {
        return array(
          // Send headers describing the image's size, and MIME-type.
          'Content-Type' => $image
            ->getMimeType(),
          'Content-Length' => $image
            ->getFileSize(),
        );
      }
    }
    return -1;
  }
}