You are here

function flipping_book_file_download in Flipping Book 8

Same name and namespace in other branches
  1. 7 flipping_book.module \flipping_book_file_download()

Implements hook_file_download().

File

./flipping_book.module, line 74
Contains flipping_book.module..

Code

function flipping_book_file_download($uri) {
  if (!preg_match('|^([\\w\\-]+)://flipping_books/(.*?)/|', $uri, $matches)) {
    return NULL;
  }
  $storage = \Drupal::entityTypeManager()
    ->getStorage('flipping_book');
  $flipping_books = $storage
    ->loadByProperties([
    'directory' => $matches[2],
  ]);
  $flipping_book = reset($flipping_books);

  // Invalid flipping book uri provided.
  if (empty($flipping_book)) {
    return -1;
  }
  $fb_service = \Drupal::service('flipping_book');

  /** @var FlippingBookType $fb_type */
  $fb_type = $fb_service
    ->getBundleEntity($flipping_book);
  $file_system = \Drupal::service('file_system');
  $current_user = \Drupal::currentUser();
  $file_path = $file_system
    ->realpath($uri);
  $denied = !file_exists($file_path) || !is_file($file_path) || !$current_user
    ->hasPermission($fb_type
    ->getPermissionName());

  // Access specifically denied.
  if ($denied) {
    return -1;
  }
  $mime_type = \Drupal::service('file.mime_type.guesser');
  $uri_chunks = explode('/', $uri);
  $file = File::create();
  $file
    ->setFilename(end($uri_chunks));
  $file
    ->setMimeType($mime_type
    ->guess($uri));
  $file
    ->setSize(filesize($file_path));

  // Access is granted.
  $headers = file_get_content_headers($file);
  return $headers;
}