From 10514abecb1bdc3126468f277cbb0139fabe21a5 Mon Sep 17 00:00:00 2001 From: Johan Janssens Date: Sun, 17 May 2020 00:00:04 +0200 Subject: [PATCH] #345 - Add support for force downloading files Add support for the 'force-download' query parameter. If specified the file will be downloaded instead of allowing the browser to preview the file if it can do so. For example: 'files/[:name]' => '/files/documents/[:name].pdf?force-download' --- .../com_pages/event/subscriber/downloader.php | 74 ++++++++++--------- 1 file changed, 39 insertions(+), 35 deletions(-) diff --git a/code/site/components/com_pages/event/subscriber/downloader.php b/code/site/components/com_pages/event/subscriber/downloader.php index 27e175721..8c57e5ffd 100644 --- a/code/site/components/com_pages/event/subscriber/downloader.php +++ b/code/site/components/com_pages/event/subscriber/downloader.php @@ -9,38 +9,42 @@ class ComPagesEventSubscriberDownloader extends ComPagesEventSubscriberAbstract { - protected function _initialize(KObjectConfig $config) - { - $config->append(array( - 'priority' => KEvent::PRIORITY_HIGH, - )); - - parent::_initialize($config); - } - - public function onAfterApplicationRoute(KEventInterface $event) - { - $request = $this->getObject('request'); - $router = $this->getObject('com://site/pages.dispatcher.router.file', ['request' => $request]); - - if(false !== $route = $router->resolve()) - { - //Qualify the route - $path = (string) $router->qualify($route, true); - - //Set the location header - $dispatcher = $this->getObject('com://site/pages.dispatcher.http'); - - try - { - $dispatcher->getResponse() - ->setContent((string) $path, @mime_content_type($path) ?? 'application/octet-stream'); - } - catch (InvalidArgumentException $e) { - throw new KControllerExceptionResourceNotFound('File not found'); - } - - $dispatcher->send(); - } - } -} + protected function _initialize(KObjectConfig $config) + { + $config->append(array( + 'priority' => KEvent::PRIORITY_HIGH, + )); + + parent::_initialize($config); + } + + public function onAfterApplicationRoute(KEventInterface $event) + { + $request = $this->getObject('request'); + $router = $this->getObject('com://site/pages.dispatcher.router.file', ['request' => $request]); + + if(false !== $route = $router->resolve()) + { + //Qualify the route + $route = $router->qualify($route); + + //Get the file path + $path = $route->getPath(); + + if(isset($route->query['force-download'])) { + $request->query->set('force-download', true); + } + + //Set the location header + $dispatcher = $this->getObject('com://site/pages.dispatcher.http'); + + try { + $dispatcher->getResponse()->setContent($path, @mime_content_type($path) ?? 'application/octet-stream'); + } catch (InvalidArgumentException $e) { + throw new KControllerExceptionResourceNotFound('File not found'); + } + + $dispatcher->send(); + } + } +} \ No newline at end of file