You are here

public static function WebformManagedFileBase::accessFileDownload in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Plugin/WebformElement/WebformManagedFileBase.php \Drupal\webform\Plugin\WebformElement\WebformManagedFileBase::accessFileDownload()

Control access to webform submission private file downloads.

Parameters

string $uri: The URI of the file.

Return value

mixed Returns NULL if the file is not attached to a webform submission. Returns -1 if the user does not have permission to access a webform. Returns an associative array of headers.

See also

hook_file_download()

webform_file_download()

File

src/Plugin/WebformElement/WebformManagedFileBase.php, line 1419

Class

WebformManagedFileBase
Provides a base class webform 'managed_file' elements.

Namespace

Drupal\webform\Plugin\WebformElement

Code

public static function accessFileDownload($uri) {
  $files = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties([
    'uri' => $uri,
  ]);
  if (empty($files)) {
    return NULL;
  }

  /** @var \Drupal\file\FileInterface $file */
  $file = reset($files);
  $access = static::accessFile($file);
  if ($access === TRUE) {

    // Return file content headers.
    $headers = file_get_content_headers($file);

    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');
    $filename = $file_system
      ->basename($uri);

    // Force blacklisted files to be downloaded instead of opening in the browser.
    if (in_array($headers['Content-Type'], static::$blacklistedMimeTypes)) {
      $headers['Content-Disposition'] = 'attachment; filename="' . Unicode::mimeHeaderEncode($filename) . '"';
    }
    else {
      $headers['Content-Disposition'] = 'inline; filename="' . Unicode::mimeHeaderEncode($filename) . '"';
    }
    return $headers;
  }
  elseif ($access === FALSE) {
    return -1;
  }
  else {
    return NULL;
  }
}