You are here

function photos_file_download in Album Photos 8.4

Same name and namespace in other branches
  1. 7.3 photos.module \photos_file_download()

Implements hook_file_download().

File

./photos.module, line 194
Implementation of photos.module.

Code

function photos_file_download($uri) {
  if (strpos($uri, '/photos/')) {
    if (strpos($uri, '/tmp_images/')) {
      $pathinfo = pathinfo($uri);
      $ext = $pathinfo['extension'];
      $filename = $pathinfo['filename'];
      $fid = str_replace('.' . $ext, '', $filename);
      $fid = str_replace('image_', '', $fid);

      // Check photos access.
      if (!_photos_access('imageView', $fid)) {
        \Drupal::logger('photos')
          ->notice('Private file access denied imageView for file id:%fid.', [
          '%fid' => $fid,
        ]);

        // Access to the file is denied.
        return -1;
      }

      // Load image.
      $image = \Drupal::service('image.factory')
        ->get($uri);
      if ($image
        ->isValid()) {
        return [
          // Send headers describing the image's size, and MIME-type.
          'Content-Type' => $image
            ->getMimeType(),
          'Content-Length' => $image
            ->getFileSize(),
          'Cache-Control' => 'private',
        ];
      }
    }
    else {

      // Load file.
      $files = \Drupal::entityTypeManager()
        ->getStorage('file')
        ->loadByProperties([
        'uri' => $uri,
      ]);
      if (count($files)) {
        foreach ($files as $item) {

          // Since some database servers sometimes use a case-insensitive
          // comparison by default, double check that the filename is an
          // exact match.
          if ($item
            ->getFileUri() === $uri) {
            $file = $item;
            break;
          }
        }
      }

      // Check file.
      if (!isset($file)) {
        return NULL;
      }

      // Check file usage.
      $db = \Drupal::database();
      $photos_usage = $db
        ->query("SELECT id FROM {file_usage} WHERE module = 'photos' AND fid = :fid", [
        ':fid' => $file
          ->id(),
      ])
        ->fetchField();
      if ($photos_usage) {

        // Check photos access.
        if (!_photos_access('imageView', $file
          ->id())) {
          \Drupal::logger('photos')
            ->notice('Private file access denied imageView for file id:%fid.', [
            '%fid' => $file
              ->id(),
          ]);

          // Access to the file is denied.
          return -1;
        }

        // Access is granted.
        $headers = file_get_content_headers($file);
        $headers['Cache-Control'] = 'private';
        return $headers;
      }
    }
  }
}