You are here

public function DefaultController::pageDownload in Filebrowser 8.2

Same name and namespace in other branches
  1. 3.x src/Controller/DefaultController.php \Drupal\filebrowser\Controller\DefaultController::pageDownload()

Callback for route: filebrowser.page_download path: filebrowser/download/{fid}

Parameters

int $fid Id of the file selected in the download link:

Return value

\Symfony\Component\HttpFoundation\RedirectResponse

1 string reference to 'DefaultController::pageDownload'
filebrowser.routing.yml in ./filebrowser.routing.yml
filebrowser.routing.yml

File

src/Controller/DefaultController.php, line 76

Class

DefaultController
Default controller for the filebrowser module.

Namespace

Drupal\filebrowser\Controller

Code

public function pageDownload($fid) {

  /* @var NodeInterface $node **/
  $node_content = $this->common
    ->nodeContentLoad($fid);

  // If $fid doesn't point to a valid file, $node_content is FALSE.
  if (!$node_content) {
    throw new NotFoundHttpException();
  }
  $file_data = unserialize($node_content['file_data']);
  $filebrowser = new Filebrowser($node_content['nid']);

  // Download method is 'public' and the uri is public://
  // we will send the browser to the file location.
  // todo:
  // RedirectResponse needs a relative path so we will convert the full url into a relative path
  // This is done here, but should be moved to a better place in Common
  $file_path = file_url_transform_relative($file_data->url);
  if ($filebrowser->downloadManager == 'public' && StreamWrapperManager::getScheme($file_data->uri) == 'public') {
    $response = new RedirectResponse($file_path);
    return $response;
  }
  else {

    // load the node containing the file so we can check
    // for the access rights
    // User needs "view" permission on the node to download the file
    $node = Node::load($node_content['nid']);
    if (isset($node) && $node
      ->access('view')) {

      // Stream the file
      $file = $file_data->uri;

      // in case you need the container

      //$container = $this->container;
      $response = new StreamedResponse(function () use ($file) {
        $handle = fopen($file, 'r') or exit("Cannot open file {$file}");
        while (!feof($handle)) {
          $buffer = fread($handle, 1024);
          echo $buffer;
          flush();
        }
        fclose($handle);
      });
      $response->headers
        ->set('Content-Type', $file_data->mimetype);
      $content_disposition = $filebrowser->forceDownload ? 'attachment' : 'inline';
      $response->headers
        ->set('Content-Disposition', $content_disposition . '; filename="' . $file_data->filename . '";');
      return $response;
    }
    elseif (isset($node)) {
      throw new AccessDeniedHttpException();
    }
    else {
      throw new NotFoundHttpException();
    }
  }
}