From e0c9f839178e40e418c44521901b0a6fc21072fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Thu, 29 Dec 2016 11:31:53 +0100 Subject: [PATCH 01/14] composer: fixed missing Environment dependency --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 007ef3b..aea8bf6 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,8 @@ }, "require": { "php": ">= 5.3.0", - "nette/application": "~2.2", + "nette/application": "~2.4", + "nette/deprecated": "^2.4", "jkuchar/bigfiletools": "~1.1" } } From 8fa3cd1eeaed0b223eeff810614249faa635dc1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Thu, 29 Dec 2016 12:14:19 +0100 Subject: [PATCH 02/14] refactoring: got rid of Nette\Environment --- FileDownloader/BaseFileDownload.php | 63 ++++++++++--------- .../Downloader/AdvancedDownloader.php | 29 ++++----- FileDownloader/Downloader/BaseDownloader.php | 53 ++++++++-------- .../Downloader/NativePHPDownloader.php | 8 ++- FileDownloader/FDTools.php | 21 ++++--- FileDownloader/IDownloader.php | 11 +++- composer.json | 2 +- 7 files changed, 96 insertions(+), 91 deletions(-) diff --git a/FileDownloader/BaseFileDownload.php b/FileDownloader/BaseFileDownload.php index 17d1ed0..264e3f0 100644 --- a/FileDownloader/BaseFileDownload.php +++ b/FileDownloader/BaseFileDownload.php @@ -43,7 +43,9 @@ use FileDownloader\Downloader\AdvancedDownloader; use FileDownloader\Downloader\NativePHPDownloader; use Nette\Application\BadRequestException; -use Nette\Environment; +use Nette\Http\Request; +use Nette\Http\Response; +use Nette\Http\Session; use Nette\InvalidArgumentException; use Nette\InvalidStateException; use Nette\Object; @@ -75,6 +77,17 @@ * @property int $contentDisposition Content disposition: inline or attachment * @property-read float $sourceFileSize File size * @property-read int $transferID TransferId + * + * Callbacks: + * @method void onBeforeDownloaderStarts(BaseFileDownload $fileDownload, IDownloader $downloader) + * @method void onBeforeOutputStarts(BaseFileDownload $fileDownload, IDownloader $downloader) + * @method void onStatusChange(BaseFileDownload $fileDownload, IDownloader $downloader) + * @method void onComplete(BaseFileDownload $fileDownload, IDownloader $downloader) + * @method void onTransferContinue(BaseFileDownload $fileDownload, IDownloader $downloader) + * @method void onNewTransferStart(BaseFileDownload $fileDownload, IDownloader $downloader) + * @method void onAbort(BaseFileDownload $fileDownload, IDownloader $downloader) + * @method void onConnectionLost(BaseFileDownload $fileDownload, IDownloader $downloader) + */ abstract class BaseFileDownload extends Object { /** @@ -89,12 +102,6 @@ abstract class BaseFileDownload extends Object { */ private static $fileDownloaders=array(); - /** - * Close session before start download? (if not, it will block session until file is transferred!) - * @var bool - */ - public static $closeSession = true; - /** * Add file downlaoder * Order is priority (last added will be used first) @@ -491,15 +498,11 @@ public function getMimeType() { } // By file extension from ini file - $cache = Environment::getCache("FileDownloader"); - if (!IsSet($cache["mime-types"])) { - $cache["mime-types"] = parse_ini_file(dirname(__FILE__) . DIRECTORY_SEPARATOR . "mime.ini"); - } - $mimetypes = $cache["mime-types"]; + $mimeTypes = parse_ini_file(dirname(__FILE__) . DIRECTORY_SEPARATOR . "mime.ini"); $extension = pathinfo($this->sourceFile, PATHINFO_EXTENSION); - if (array_key_exists($extension, $mimetypes)) { - $mime = $mimetypes[$extension]; + if (array_key_exists($extension, $mimeTypes)) { + $mime = $mimeTypes[$extension]; } if (FDTools::isValidMimeType($mime)) { @@ -527,19 +530,19 @@ public function getSourceFileSize() { return FDTools::filesize($this->sourceFile); } + /** * Download the file! * @param IDownloader $downloader + * @param Request $request HTTP request + * @param Response $response HTTP response + * @param Session $session HTTP Session (this is needed to be able to close it + * @throws Exception */ - function download(IDownloader $downloader = null) { - $req = Environment::getHttpRequest(); - $res = Environment::getHttpResponse(); + function download(IDownloader $downloader = null, Request $request, Response $response, Session $session) { - if(self::$closeSession) { - $ses = Environment::getSession(); - if($ses->isStarted()) { - $ses->close(); - } + if($session->isStarted()) { + $session->close(); } if($this->getContentDisposition() == "inline" AND is_null($this->enableBrowserCache)) { @@ -565,21 +568,21 @@ function download(IDownloader $downloader = null) { foreach($downloaders AS $downloader) { if($downloader instanceof IDownloader and $downloader->isCompatible($this)) { try { - FDTools::clearHeaders($res); // Delete all headers + FDTools::clearHeaders($response); // Delete all headers $this->transferredBytes = 0; $this->onBeforeDownloaderStarts($this,$downloader); $downloader->download($this); // Start download $this->onComplete($this,$downloader); die(); // If all gone ok -> die } catch (FDSkypeMeException $e) { - if($res->isSent()) { + if($response->isSent()) { throw new InvalidStateException("Headers are already sent! Can't skip downloader."); } else { continue; } } catch (Exception $e) { - if(!$res->isSent()) - FDTools::clearHeaders($res); + if(!$response->isSent()) + FDTools::clearHeaders($response); throw $e; } } @@ -587,14 +590,14 @@ function download(IDownloader $downloader = null) { // Pokud se soubor nějakým způsobem odešle - toto už se nespustí if($lastException instanceof Exception) { - FDTools::clearHeaders(Environment::getHttpResponse(),TRUE); + FDTools::clearHeaders($response,TRUE); throw $lastException; } - if($req->getHeader("Range")) - FDTools::_HTTPError(416); // Požadavek na range + if($request->getHeader("Range")) + FDTools::_HTTPError($response, 416); // Požadavek na range else - $res->setCode(500); + $response->setCode(500); throw new InvalidStateException("There is no compatible downloader (all downloader returns downloader->isComplatible()=false or was skipped)!"); } } diff --git a/FileDownloader/Downloader/AdvancedDownloader.php b/FileDownloader/Downloader/AdvancedDownloader.php index d9bb417..635ec35 100644 --- a/FileDownloader/Downloader/AdvancedDownloader.php +++ b/FileDownloader/Downloader/AdvancedDownloader.php @@ -47,6 +47,8 @@ use FileDownloader\FDTools; use FileDownloader\FileDownloaderException; use Nette\Environment; +use Nette\Http\Request; +use Nette\Http\Response; use Nette\InvalidArgumentException; use Nette\InvalidStateException; @@ -85,19 +87,12 @@ class AdvancedDownloader extends BaseDownloader { */ protected $sleep; - /** - * Download file! - * @param BaseFileDownload $file - */ - function download(BaseFileDownload $transfer) { + function download(Request $request, Response $response, BaseFileDownload $transfer) { $this->currentTransfer = $transfer; - $this->sendStandardFileHeaders($transfer,$this); + $this->sendStandardFileHeaders($request, $response, $transfer,$this); @ignore_user_abort(true); // For onAbort event - $req = Environment::getHttpRequest(); - $res = Environment::getHttpResponse(); - $filesize = $this->size = $transfer->sourceFileSize; $this->length = $this->size; // Content-length $this->start = 0; @@ -119,17 +114,17 @@ function download(BaseFileDownload $transfer) { */ //$res->setHeader("Accept-Ranges", "0-".$this->end); // single-part - now not accepted by mozilla - $res->setHeader("Accept-Ranges", "bytes"); // multi-part (through Mozilla) + $response->setHeader("Accept-Ranges", "bytes"); // multi-part (through Mozilla) // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2 - if ($req->getHeader("Range", false)) // If partial download + if ($request->getHeader("Range", false)) // If partial download { try { $range_start = $this->start; $range_end = $this->end; // Extract the range string - $rangeArray = explode('=', $req->getHeader("Range"), 2); + $rangeArray = explode('=', $request->getHeader("Range"), 2); $range = $rangeArray[1]; // Make sure the client hasn't sent us a multibyte range @@ -170,18 +165,18 @@ function download(BaseFileDownload $transfer) { $this->length = $this->end - $this->start + 1; // Calculate new content length } catch (FileDownloaderException $e) { if ($e->getCode() === 416) { - $res->setHeader("Content-Range", "bytes $this->start-$this->end/$this->size"); - FDTools::_HTTPError(416); + $response->setHeader("Content-Range", "bytes $this->start-$this->end/$this->size"); + FDTools::_HTTPError($response, 416); } else { throw $e; } } - $res->setCode(206); // Partial content + $response->setCode(206); // Partial content } // End of if partial download // Notify the client the byte range we'll be outputting - $res->setHeader("Content-Range","bytes $this->start-$this->end/$this->size"); - $res->setHeader("Content-Length",$this->length); + $response->setHeader("Content-Range","bytes $this->start-$this->end/$this->size"); + $response->setHeader("Content-Length",$this->length); /* ### Call callbacks ### */ diff --git a/FileDownloader/Downloader/BaseDownloader.php b/FileDownloader/Downloader/BaseDownloader.php index 916eb98..34d2a44 100644 --- a/FileDownloader/Downloader/BaseDownloader.php +++ b/FileDownloader/Downloader/BaseDownloader.php @@ -41,7 +41,7 @@ use FileDownloader\BaseFileDownload; use FileDownloader\FDTools; use FileDownloader\IDownloader; -use Nette\Environment; +use Nette\Http\Request; use Nette\Http\Response; use Nette\Object; @@ -54,54 +54,51 @@ * @author Jan Kuchař */ abstract class BaseDownloader extends Object implements IDownloader { - /** * Sends a standard headers for file download - * @param BaseFileDownload $file File - * @param BaseDownloader $downloader Downloader of the file + * @param Request $request + * @param Response $rCesponse + * @param BaseFileDownload $file File + * @param BaseDownloader $downloader Downloader of the file */ - protected function sendStandardFileHeaders(BaseFileDownload $file, BaseDownloader $downloader=null) { - $res = Environment::getHttpResponse(); - $req = Environment::getHttpRequest(); + protected function sendStandardFileHeaders(Request $request, Response $response, BaseFileDownload $file, BaseDownloader $downloader=null) { //FDTools::clearHeaders($res); // Voláno už v FileDownload.php - $res->setContentType($file->mimeType, "UTF-8"); - $res->setHeader("X-File-Downloader", "File Downloader (http://filedownloader.projekty.mujserver.net)"); + $response->setContentType($file->mimeType, "UTF-8"); + $response->setHeader("X-File-Downloader", "File Downloader (http://filedownloader.projekty.mujserver.net)"); if ($downloader !== null) { - $res->setHeader("X-FileDownloader-Actual-Script", $downloader->getReflection()->name); + $response->setHeader("X-FileDownloader-Actual-Script", $downloader->getReflection()->name); } - $res->setHeader('Pragma', 'public'); // Fix for IE - Content-Disposition - $res->setHeader('Content-Disposition', $file->getContentDisposition() . '; filename="' . FDTools::getContentDispositionHeaderData($file->transferFileName) . '"'); - $res->setHeader('Content-Description', 'File Transfer'); - $res->setHeader('Content-Transfer-Encoding', 'binary'); - $res->setHeader('Connection', 'close'); - $res->setHeader('ETag', FDTools::getETag($file->sourceFile)); - $res->setHeader('Content-Length', FDTools::filesize($file->sourceFile)); + $response->setHeader('Pragma', 'public'); // Fix for IE - Content-Disposition + $response->setHeader('Content-Disposition', $file->getContentDisposition() . '; filename="' . FDTools::getContentDispositionHeaderData($request, $file->transferFileName) . '"'); + $response->setHeader('Content-Description', 'File Transfer'); + $response->setHeader('Content-Transfer-Encoding', 'binary'); + $response->setHeader('Connection', 'close'); + $response->setHeader('ETag', FDTools::getETag($file->sourceFile)); + $response->setHeader('Content-Length', FDTools::filesize($file->sourceFile)); // Cache control if ($file->enableBrowserCache) { - $this->setupCacheHeaders($file); + $this->setupCacheHeaders($response, $file); } else { - $this->setupNonCacheHeaders($file); + $this->setupNonCacheHeaders($response, $file); } } - protected function setupCacheHeaders(BaseFileDownload $file) { - $res = Environment::getHttpResponse(); - $res->setExpiration(time() + 99999999); - $res->setHeader('Last-Modified', "Mon, 23 Jan 1978 10:00:00 GMT"); + protected function setupCacheHeaders(Response $response, BaseFileDownload $file) { + $response->setExpiration(time() + 99999999); + $response->setHeader('Last-Modified', "Mon, 23 Jan 1978 10:00:00 GMT"); if (!empty($_SERVER["HTTP_IF_MODIFIED_SINCE"])) { - $res->setCode(Response::S304_NOT_MODIFIED); + $response->setCode(Response::S304_NOT_MODIFIED); //header("HTTP/1.1 304 Not Modified"); exit(); }; } - protected function setupNonCacheHeaders(BaseFileDownload $file) { - $res = Environment::getHttpResponse(); - $res->setHeader('Expires', '0'); - $res->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); + protected function setupNonCacheHeaders(Response $response, BaseFileDownload $file) { + $response->setHeader('Expires', '0'); + $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); } } diff --git a/FileDownloader/Downloader/NativePHPDownloader.php b/FileDownloader/Downloader/NativePHPDownloader.php index c680ce7..a9e432b 100644 --- a/FileDownloader/Downloader/NativePHPDownloader.php +++ b/FileDownloader/Downloader/NativePHPDownloader.php @@ -40,6 +40,8 @@ namespace FileDownloader\Downloader; use FileDownloader\BaseFileDownload; +use Nette\Http\Request; +use Nette\Http\Response; use Nette\InvalidStateException; /** @@ -56,9 +58,9 @@ class NativePHPDownloader extends BaseDownloader { * Download file! * @param BaseFileDownload $file */ - function download(BaseFileDownload $file) { - $this->sendStandardFileHeaders($file,$this); - $file->onBeforeOutputStarts($file,$this); + function download(Request $request, Response $response, BaseFileDownload $file) { + $this->sendStandardFileHeaders($request, $response, $file, $this); + $file->onBeforeOutputStarts($file, $this); // Bugfix: when output buffer active, there is a problem with memory // @see http://www.php.net/manual/en/function.readfile.php#81032 diff --git a/FileDownloader/FDTools.php b/FileDownloader/FDTools.php index 6d9f828..8d88f86 100644 --- a/FileDownloader/FDTools.php +++ b/FileDownloader/FDTools.php @@ -39,8 +39,9 @@ namespace FileDownloader; use BigFileTools; -use Nette\Environment; use Nette\Http\IResponse; +use Nette\Http\Request; +use Nette\Http\Response; use Nette\InvalidArgumentException; use Nette\InvalidStateException; use Nette\Object; @@ -161,18 +162,19 @@ static function getETag($location) { return "\"" . md5($location . filemtime($location) . self::filesize($location)) . "\""; } + /** * Returns filename (but if IE fix the bug) * * @link http://cz2.php.net/manual/en/function.fpassthru.php#25801 * @author Unknown + * @param Request $request HTTP request * @param string $basename Path to file or filename * @return string */ - static function getContentDispositionHeaderData($basename) { + static function getContentDispositionHeaderData(Request $request, $basename) { $basename = basename($basename); - $req = Environment::getHttpRequest(); - $userAgent = $req->getHeader("User-Agent"); + $userAgent = $request->getHeader("User-Agent"); if ($userAgent AND strstr($userAgent, "MSIE")) { // workaround for IE filename bug with multiple periods / multiple dots in filename // that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe @@ -182,23 +184,24 @@ static function getContentDispositionHeaderData($basename) { return $basename; } + /** * Sends http error to client * * @author Jan Kuchař - * @param int $code HTTP code + * @param Response $response + * @param int $code HTTP code * @param string $message HTTP status */ - static function _HTTPError($code,$message=null) { + static function _HTTPError(Response $response, $code, $message=null) { $errors = array( 416=>"Requested Range not satisfiable" ); if ($message === null and isset($errors[$code])) { $message = $errors[$code]; } - $res = Environment::getHttpResponse(); - $res->setCode($code); - $res->setContentType("plain/text","UTF-8"); + $response->setCode($code); + $response->setContentType("plain/text","UTF-8"); die("

HTTP Error ".$code." - ".$message."

".$message."

"); } diff --git a/FileDownloader/IDownloader.php b/FileDownloader/IDownloader.php index 14b450a..a26c1db 100644 --- a/FileDownloader/IDownloader.php +++ b/FileDownloader/IDownloader.php @@ -37,6 +37,8 @@ */ namespace FileDownloader; +use Nette\Http\Request; +use Nette\Http\Response; /** * @@ -49,13 +51,16 @@ interface IDownloader { /** * Download file! - * @param FileDownload $file + * @param Request $request HTTP request + * @param Response $response HTTP response + * @param BaseFileDownload|FileDownload $file */ - function download(BaseFileDownload $file); + function download(Request $request, Response $response, BaseFileDownload $file); + /** * Is this downloader compatible? - * @param FileDownload $file + * @param BaseFileDownload|FileDownload $file * @return bool TRUE if is compatible; FALSE if not */ function isCompatible(BaseFileDownload $file); diff --git a/composer.json b/composer.json index aea8bf6..f36ab55 100644 --- a/composer.json +++ b/composer.json @@ -19,6 +19,6 @@ "php": ">= 5.3.0", "nette/application": "~2.4", "nette/deprecated": "^2.4", - "jkuchar/bigfiletools": "~1.1" + "jkuchar/bigfiletools": "~1.1" } } From 3cf3ddebb2034cb104f923b2f900d51db0f7c2a2 Mon Sep 17 00:00:00 2001 From: Jiri Novak Date: Fri, 3 Feb 2017 00:17:17 +0100 Subject: [PATCH 03/14] Fixed wrong parameters provided to downloader. --- FileDownloader/BaseFileDownload.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FileDownloader/BaseFileDownload.php b/FileDownloader/BaseFileDownload.php index 264e3f0..02cb433 100644 --- a/FileDownloader/BaseFileDownload.php +++ b/FileDownloader/BaseFileDownload.php @@ -571,7 +571,7 @@ function download(IDownloader $downloader = null, Request $request, Response $re FDTools::clearHeaders($response); // Delete all headers $this->transferredBytes = 0; $this->onBeforeDownloaderStarts($this,$downloader); - $downloader->download($this); // Start download + $downloader->download($request, $response, $this); // Start download $this->onComplete($this,$downloader); die(); // If all gone ok -> die } catch (FDSkypeMeException $e) { From 2227589e2643e2587adeb7acc67a806ceb6d4760 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 16:52:07 +0200 Subject: [PATCH 04/14] make visibility explicit --- FileDownloader/AppFileDownload.php | 10 +++--- FileDownloader/BaseFileDownload.php | 36 +++++++++---------- .../Downloader/AdvancedDownloader.php | 8 ++--- .../Downloader/NativePHPDownloader.php | 4 +-- FileDownloader/FDTools.php | 18 +++++----- FileDownloader/IDownloader.php | 4 +-- 6 files changed, 40 insertions(+), 40 deletions(-) diff --git a/FileDownloader/AppFileDownload.php b/FileDownloader/AppFileDownload.php index f1560b9..23284b3 100644 --- a/FileDownloader/AppFileDownload.php +++ b/FileDownloader/AppFileDownload.php @@ -79,7 +79,7 @@ public static function getInstance(Component $parent) { /** * @param Component $parent */ - function __construct(Component $parent) { + public function __construct(Component $parent) { parent::__construct(); $this->setParent($parent); } @@ -89,7 +89,7 @@ function __construct(Component $parent) { * @param Component $parent * @return AppFileDownload */ - function setParent(Component $parent) { + public function setParent(Component $parent) { $this->parent = $parent; return $this; } @@ -98,14 +98,14 @@ function setParent(Component $parent) { * Getts AppFileDownload parent * @return Component */ - function getParent() { + public function getParent() { return $this->parent; } /** * Implementation of IPresenterResponse::send() */ - function send(IRequest $httpRequest, IResponse $httpResponse) { + public function send(IRequest $httpRequest, IResponse $httpResponse) { parent::download($this->downloader); } @@ -113,7 +113,7 @@ function send(IRequest $httpRequest, IResponse $httpResponse) { * Start download of the file! * @param IDownloader $downloader */ - function download(IDownloader $downloader = null) { + public function download(IDownloader $downloader = null) { $this->downloader = $downloader; // Call sendResponse on presenter (used since 2.0 instead of terminate) diff --git a/FileDownloader/BaseFileDownload.php b/FileDownloader/BaseFileDownload.php index 264e3f0..6e85f89 100644 --- a/FileDownloader/BaseFileDownload.php +++ b/FileDownloader/BaseFileDownload.php @@ -202,7 +202,7 @@ public static function clearFileDownloaders() { * @param callback $callback Callback * @return BaseFileDownload */ - function addBeforeDownloaderStartsCallback($callback) { + public function addBeforeDownloaderStartsCallback($callback) { return $this->addCallback(__METHOD__, $callback); } @@ -220,7 +220,7 @@ function addBeforeDownloaderStartsCallback($callback) { * @param callback $callback Callback * @return BaseFileDownload */ - function addBeforeOutputStartsCallback($callback) { + public function addBeforeOutputStartsCallback($callback) { return $this->addCallback(__METHOD__, $callback); } @@ -238,7 +238,7 @@ function addBeforeOutputStartsCallback($callback) { * @param callback $callback Callback * @return BaseFileDownload */ - function addStatusChangeCallback($callback) { + public function addStatusChangeCallback($callback) { return $this->addCallback(__METHOD__, $callback); } @@ -255,7 +255,7 @@ function addStatusChangeCallback($callback) { * @param callback $callback Callback * @return BaseFileDownload */ - function addCompleteCallback($callback) { + public function addCompleteCallback($callback) { return $this->addCallback(__METHOD__, $callback); } @@ -275,7 +275,7 @@ function addCompleteCallback($callback) { * @param callback $callback Callback * @return BaseFileDownload */ - function addTransferContinueCallback($callback) { + public function addTransferContinueCallback($callback) { return $this->addCallback(__METHOD__, $callback); } @@ -294,7 +294,7 @@ function addTransferContinueCallback($callback) { * @param callback $callback Callback * @return BaseFileDownload */ - function addNewTransferStartCallback($callback) { + public function addNewTransferStartCallback($callback) { return $this->addCallback(__METHOD__, $callback); } @@ -312,7 +312,7 @@ function addNewTransferStartCallback($callback) { * @param callback $callback Callback * @return BaseFileDownload */ - function addAbortCallback($callback) { + public function addAbortCallback($callback) { return $this->addCallback(__METHOD__, $callback); } @@ -330,7 +330,7 @@ function addAbortCallback($callback) { * @param callback $callback Callback * @return BaseFileDownload */ - function addConnectionLostCallback($callback) { + public function addConnectionLostCallback($callback) { return $this->addCallback(__METHOD__, $callback); } @@ -348,7 +348,7 @@ private function addCallback($fceName, $callback) { return $this; } - function __construct() { + public function __construct() { $this->vTransferID = time()."-".rand(); foreach(self::$defaults AS $key => $val) { $this->$key = $val; @@ -368,7 +368,7 @@ public function getTransferId() { * @param string $location Location of the source file * @return BaseFileDownload */ - function setSourceFile($location) { + public function setSourceFile($location) { if($location === null) { $this->vSourceFile = null; }else { @@ -388,7 +388,7 @@ function setSourceFile($location) { * Getts location of the source file * @return BaseFileDownload */ - function getSourceFile() { + public function getSourceFile() { if ($this->vSourceFile === null) { throw new InvalidStateException("Location is not set!"); } @@ -400,7 +400,7 @@ function getSourceFile() { * @param string $disposition * @return BaseFileDownload */ - function setContentDisposition($disposition) { + public function setContentDisposition($disposition) { $values = array("inline","attachment"); if (!in_array($disposition, $values)) { throw new InvalidArgumentException("Content disposition must be one of these: " . implode(",", $values)); @@ -413,7 +413,7 @@ function setContentDisposition($disposition) { * Getts content disposition * @return string */ - function getContentDisposition() { + public function getContentDisposition() { return $this->vContentDisposition; } @@ -421,7 +421,7 @@ function getContentDisposition() { * Getts send as name * @return string */ - function getTransferFileName() { + public function getTransferFileName() { return $this->vTransferFileName; } @@ -430,7 +430,7 @@ function getTransferFileName() { * @param string $sendAs * @return BaseFileDownload */ - function setTransferFileName($name) { + public function setTransferFileName($name) { $this->vTransferFileName = pathinfo($name, PATHINFO_BASENAME); return $this; } @@ -441,7 +441,7 @@ function setTransferFileName($name) { * @param int $speed Speed limit * @return BaseFileDownload */ - function setSpeedLimit($speed) { + public function setSpeedLimit($speed) { if (!is_int($speed)) { throw new InvalidArgumentException("Max download speed must be integer!"); } @@ -463,7 +463,7 @@ function setSpeedLimit($speed) { * Getts speed limit * @return int */ - function getSpeedLimit() { + public function getSpeedLimit() { return $this->vSpeedLimit; } @@ -539,7 +539,7 @@ public function getSourceFileSize() { * @param Session $session HTTP Session (this is needed to be able to close it * @throws Exception */ - function download(IDownloader $downloader = null, Request $request, Response $response, Session $session) { + public function download(IDownloader $downloader = null, Request $request, Response $response, Session $session) { if($session->isStarted()) { $session->close(); diff --git a/FileDownloader/Downloader/AdvancedDownloader.php b/FileDownloader/Downloader/AdvancedDownloader.php index 635ec35..be16389 100644 --- a/FileDownloader/Downloader/AdvancedDownloader.php +++ b/FileDownloader/Downloader/AdvancedDownloader.php @@ -65,7 +65,7 @@ class AdvancedDownloader extends BaseDownloader { * Check for environment configuration? * @var bool */ - static $checkEnvironmentSettings = true; + public static $checkEnvironmentSettings = true; public $size = 0; public $start = 0; @@ -87,7 +87,7 @@ class AdvancedDownloader extends BaseDownloader { */ protected $sleep; - function download(Request $request, Response $response, BaseFileDownload $transfer) { + public function download(Request $request, Response $response, BaseFileDownload $transfer) { $this->currentTransfer = $transfer; $this->sendStandardFileHeaders($request, $response, $transfer,$this); @@ -353,7 +353,7 @@ protected function _afterBufferSent($tmpTime, $fp=null) { * Is this downloader initialized? * @return bool */ - function isInitialized() { + public function isInitialized() { if ($this->end == 0) { return false; } @@ -366,7 +366,7 @@ function isInitialized() { * @param BaseFileDownload $file * @return bool TRUE if is compatible; FALSE if not */ - function isCompatible(BaseFileDownload $file) { + public function isCompatible(BaseFileDownload $file) { if(self::$checkEnvironmentSettings === true) { if (FDTools::setTimeLimit(0) !== true) { return false; diff --git a/FileDownloader/Downloader/NativePHPDownloader.php b/FileDownloader/Downloader/NativePHPDownloader.php index a9e432b..8f25eb0 100644 --- a/FileDownloader/Downloader/NativePHPDownloader.php +++ b/FileDownloader/Downloader/NativePHPDownloader.php @@ -58,7 +58,7 @@ class NativePHPDownloader extends BaseDownloader { * Download file! * @param BaseFileDownload $file */ - function download(Request $request, Response $response, BaseFileDownload $file) { + public function download(Request $request, Response $response, BaseFileDownload $file) { $this->sendStandardFileHeaders($request, $response, $file, $this); $file->onBeforeOutputStarts($file, $this); @@ -83,7 +83,7 @@ function download(Request $request, Response $response, BaseFileDownload $file) * @param bool $isLast Is this last downloader in list? * @return bool TRUE if is compatible; FALSE if not */ - function isCompatible(BaseFileDownload $file) { + public function isCompatible(BaseFileDownload $file) { return true; } } diff --git a/FileDownloader/FDTools.php b/FileDownloader/FDTools.php index 8d88f86..3a36851 100644 --- a/FileDownloader/FDTools.php +++ b/FileDownloader/FDTools.php @@ -71,7 +71,7 @@ class FDTools extends Object { * Returns available memery in bytes or NULL when no limit it set * @return int|null */ - static function getAvailableMemory() { + public static function getAvailableMemory() { $mem = self::parsePHPIniMemoryValue(ini_get("memory_limit")); if ($mem == 0) { return null; @@ -84,12 +84,12 @@ static function getAvailableMemory() { * @param string $phpIniValueStr * @return int */ - static function parsePHPIniMemoryValue($phpIniValueStr) { + public static function parsePHPIniMemoryValue($phpIniValueStr) { $phpIniValueInt = (int)$phpIniValueStr; if ($phpIniValueInt <= 0) { return 0; } - switch (substr($phpIniValueStr, -1, 1)) { + switch ($phpIniValueStr[strlen($phpIniValueStr) - 1]) { case "K": $phpIniValueInt *= self::KILOBYTE; break; @@ -114,7 +114,7 @@ static function parsePHPIniMemoryValue($phpIniValueStr) { * @param IResponse $res * @return IResponse */ - static function clearHeaders(IResponse $res,$setContentType=false) { + public static function clearHeaders(IResponse $res, $setContentType=false) { $res->setCode(IResponse::S200_OK); foreach($res->getHeaders() AS $key => $val) { $res->setHeader($key, null); @@ -130,7 +130,7 @@ static function clearHeaders(IResponse $res,$setContentType=false) { * @param int $time Time limit * @return bool */ - static function setTimeLimit($time=0) { + public static function setTimeLimit($time=0) { if (!function_exists("ini_get")) { throw new InvalidStateException("Function ini_get must be allowed."); } @@ -158,7 +158,7 @@ static function setTimeLimit($time=0) { * @param string $location Location to source file * @return string ETag */ - static function getETag($location) { + public static function getETag($location) { return "\"" . md5($location . filemtime($location) . self::filesize($location)) . "\""; } @@ -172,7 +172,7 @@ static function getETag($location) { * @param string $basename Path to file or filename * @return string */ - static function getContentDispositionHeaderData(Request $request, $basename) { + public static function getContentDispositionHeaderData(Request $request, $basename) { $basename = basename($basename); $userAgent = $request->getHeader("User-Agent"); if ($userAgent AND strstr($userAgent, "MSIE")) { @@ -193,7 +193,7 @@ static function getContentDispositionHeaderData(Request $request, $basename) { * @param int $code HTTP code * @param string $message HTTP status */ - static function _HTTPError(Response $response, $code, $message=null) { + public static function _HTTPError(Response $response, $code, $message=null) { $errors = array( 416=>"Requested Range not satisfiable" ); @@ -210,7 +210,7 @@ static function _HTTPError(Response $response, $code, $message=null) { * @param string $mime Mime-type * @return bool */ - static function isValidMimeType($mime) { + public static function isValidMimeType($mime) { $mime = (string)$mime; // Thanks to Matúš Matula: http://forum.nette.org/cs/1952-addon-file-downloader-file-downloader?p=2#p61785 // return preg_match('#^[-\w]+/[-\w\+]+$#i', $mime); // simple check diff --git a/FileDownloader/IDownloader.php b/FileDownloader/IDownloader.php index a26c1db..f6113a4 100644 --- a/FileDownloader/IDownloader.php +++ b/FileDownloader/IDownloader.php @@ -55,7 +55,7 @@ interface IDownloader { * @param Response $response HTTP response * @param BaseFileDownload|FileDownload $file */ - function download(Request $request, Response $response, BaseFileDownload $file); + public function download(Request $request, Response $response, BaseFileDownload $file); /** @@ -63,7 +63,7 @@ function download(Request $request, Response $response, BaseFileDownload $file); * @param BaseFileDownload|FileDownload $file * @return bool TRUE if is compatible; FALSE if not */ - function isCompatible(BaseFileDownload $file); + public function isCompatible(BaseFileDownload $file); } From e991e3974c210297702098f76080c4b8770347ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 16:55:21 +0200 Subject: [PATCH 05/14] random minor fixes --- FileDownloader/BaseFileDownload.php | 6 +++--- FileDownloader/Downloader/AdvancedDownloader.php | 5 ++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/FileDownloader/BaseFileDownload.php b/FileDownloader/BaseFileDownload.php index 6e85f89..482b7e6 100644 --- a/FileDownloader/BaseFileDownload.php +++ b/FileDownloader/BaseFileDownload.php @@ -349,7 +349,7 @@ private function addCallback($fceName, $callback) { } public function __construct() { - $this->vTransferID = time()."-".rand(); + $this->vTransferID = time()."-".mt_rand(); foreach(self::$defaults AS $key => $val) { $this->$key = $val; } @@ -498,7 +498,7 @@ public function getMimeType() { } // By file extension from ini file - $mimeTypes = parse_ini_file(dirname(__FILE__) . DIRECTORY_SEPARATOR . "mime.ini"); + $mimeTypes = parse_ini_file(__DIR__ . DIRECTORY_SEPARATOR . "mime.ini"); $extension = pathinfo($this->sourceFile, PATHINFO_EXTENSION); if (array_key_exists($extension, $mimeTypes)) { @@ -545,7 +545,7 @@ public function download(IDownloader $downloader = null, Request $request, Respo $session->close(); } - if($this->getContentDisposition() == "inline" AND is_null($this->enableBrowserCache)) { + if($this->getContentDisposition() == "inline" AND $this->enableBrowserCache === NULL) { $this->enableBrowserCache = true; }else{ $this->enableBrowserCache = false; diff --git a/FileDownloader/Downloader/AdvancedDownloader.php b/FileDownloader/Downloader/AdvancedDownloader.php index be16389..b2d8942 100644 --- a/FileDownloader/Downloader/AdvancedDownloader.php +++ b/FileDownloader/Downloader/AdvancedDownloader.php @@ -46,7 +46,6 @@ use FileDownloader\BaseFileDownload; use FileDownloader\FDTools; use FileDownloader\FileDownloaderException; -use Nette\Environment; use Nette\Http\Request; use Nette\Http\Response; use Nette\InvalidArgumentException; @@ -337,10 +336,10 @@ protected function _afterBufferSent($tmpTime, $fp=null) { } die(); } - if($this->sleep==true OR $tmpTime<=time()) { + if($this->sleep == true OR $tmpTime<=time()) { $transfer->transferredBytes = $this->transferred = $this->position-$this->start; $transfer->onStatusChange($transfer,$this); - if (IsSet($tmpTime)) { + if ($tmpTime !== NULL) { $tmpTime = time() + 1; } } From fa7e6e4f4cc507a0c706fc57764403c3c4f70626 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 16:55:55 +0200 Subject: [PATCH 06/14] replace double quotes with single quotes where possible --- FileDownloader/AppFileDownload.php | 2 +- FileDownloader/BaseFileDownload.php | 38 ++++++++-------- .../Downloader/AdvancedDownloader.php | 32 +++++++------- FileDownloader/Downloader/BaseDownloader.php | 10 ++--- .../Downloader/NativePHPDownloader.php | 2 +- FileDownloader/FDTools.php | 44 +++++++++---------- 6 files changed, 65 insertions(+), 63 deletions(-) diff --git a/FileDownloader/AppFileDownload.php b/FileDownloader/AppFileDownload.php index 23284b3..d7ee24a 100644 --- a/FileDownloader/AppFileDownload.php +++ b/FileDownloader/AppFileDownload.php @@ -120,7 +120,7 @@ public function download(IDownloader $downloader = null) { if($this->parent instanceof Presenter) { $presenter = $this->parent; } else { - $presenter = $this->parent->lookup("Nette/Application/UI/Presenter",true); + $presenter = $this->parent->lookup('Nette/Application/UI/Presenter',true); } $presenter->sendResponse($this); diff --git a/FileDownloader/BaseFileDownload.php b/FileDownloader/BaseFileDownload.php index 482b7e6..e692249 100644 --- a/FileDownloader/BaseFileDownload.php +++ b/FileDownloader/BaseFileDownload.php @@ -141,8 +141,8 @@ public static function clearFileDownloaders() { */ private $vTransferID = -1; - const CONTENT_DISPOSITION_ATTACHMENT = "attachment"; - const CONTENT_DISPOSITION_INLINE = "inline"; + const CONTENT_DISPOSITION_ATTACHMENT = 'attachment'; + const CONTENT_DISPOSITION_INLINE = 'inline'; /** * Content disposition: attachment / inline @@ -341,15 +341,15 @@ public function addConnectionLostCallback($callback) { * @return BaseFileDownload */ private function addCallback($fceName, $callback) { - preg_match("/^.*::add(.*)Callback$/", $fceName, $matches); - $varName = "on".$matches[1]; + preg_match('/^.*::add(.*)Callback$/', $fceName, $matches); + $varName = 'on' .$matches[1]; $var = &$this->$varName; $var[] = $callback; return $this; } public function __construct() { - $this->vTransferID = time()."-".mt_rand(); + $this->vTransferID = time(). '-' .mt_rand(); foreach(self::$defaults AS $key => $val) { $this->$key = $val; } @@ -376,7 +376,7 @@ public function setSourceFile($location) { throw new BadRequestException("File not found at '" . $location . "'!"); } if (!is_readable($location)) { - throw new InvalidStateException("File is NOT readable!"); + throw new InvalidStateException('File is NOT readable!'); } $this->transferFileName = pathinfo($location, PATHINFO_BASENAME); $this->vSourceFile = realpath($location); @@ -390,7 +390,7 @@ public function setSourceFile($location) { */ public function getSourceFile() { if ($this->vSourceFile === null) { - throw new InvalidStateException("Location is not set!"); + throw new InvalidStateException('Location is not set!'); } return $this->vSourceFile; } @@ -401,9 +401,9 @@ public function getSourceFile() { * @return BaseFileDownload */ public function setContentDisposition($disposition) { - $values = array("inline","attachment"); + $values = array('inline', 'attachment'); if (!in_array($disposition, $values)) { - throw new InvalidArgumentException("Content disposition must be one of these: " . implode(",", $values)); + throw new InvalidArgumentException('Content disposition must be one of these: ' . implode(',', $values)); } $this->vContentDisposition = $disposition; return $this; @@ -443,7 +443,7 @@ public function setTransferFileName($name) { */ public function setSpeedLimit($speed) { if (!is_int($speed)) { - throw new InvalidArgumentException("Max download speed must be integer!"); + throw new InvalidArgumentException('Max download speed must be integer!'); } if ($speed < 0) { throw new InvalidArgumentException("Max download speed can't be smaller than zero!"); @@ -452,7 +452,7 @@ public function setSpeedLimit($speed) { if ($availableMem) { $availableMemWithReserve = ($availableMem-100*1024); if ($speed > $availableMemWithReserve) { - throw new InvalidArgumentException("Max download speed can't be a bigger than available memory " . $availableMemWithReserve . "b!"); + throw new InvalidArgumentException("Max download speed can't be a bigger than available memory " . $availableMemWithReserve . 'b!'); } } $this->vSpeedLimit = (int)round($speed); @@ -479,7 +479,7 @@ public function getMimeType() { } $mime = ""; - if (extension_loaded('fileinfo') and function_exists("finfo_open")) { + if (extension_loaded('fileinfo') and function_exists('finfo_open')) { //TODO: test this code: if ($finfo = @finfo_open(FILEINFO_MIME)) { $mime = @finfo_file($finfo, $this->sourceFile); @@ -490,7 +490,7 @@ public function getMimeType() { } } - if(function_exists("mime_content_type")) { + if(function_exists('mime_content_type')) { $mime = mime_content_type($this->sourceFile); if (FDTools::isValidMimeType($mime)) { return $mime; @@ -498,7 +498,7 @@ public function getMimeType() { } // By file extension from ini file - $mimeTypes = parse_ini_file(__DIR__ . DIRECTORY_SEPARATOR . "mime.ini"); + $mimeTypes = parse_ini_file(__DIR__ . DIRECTORY_SEPARATOR . 'mime.ini'); $extension = pathinfo($this->sourceFile, PATHINFO_EXTENSION); if (array_key_exists($extension, $mimeTypes)) { @@ -508,7 +508,7 @@ public function getMimeType() { if (FDTools::isValidMimeType($mime)) { return $mime; } else { - return "application/octet-stream"; + return 'application/octet-stream'; } } @@ -545,7 +545,7 @@ public function download(IDownloader $downloader = null, Request $request, Respo $session->close(); } - if($this->getContentDisposition() == "inline" AND $this->enableBrowserCache === NULL) { + if($this->getContentDisposition() == 'inline' AND $this->enableBrowserCache === NULL) { $this->enableBrowserCache = true; }else{ $this->enableBrowserCache = false; @@ -558,7 +558,7 @@ public function download(IDownloader $downloader = null, Request $request, Respo } if (count($downloaders) <= 0) { - throw new InvalidStateException("There is no registred downloader!"); + throw new InvalidStateException('There is no registred downloader!'); } krsort($downloaders); @@ -594,11 +594,11 @@ public function download(IDownloader $downloader = null, Request $request, Respo throw $lastException; } - if($request->getHeader("Range")) + if($request->getHeader('Range')) FDTools::_HTTPError($response, 416); // Požadavek na range else $response->setCode(500); - throw new InvalidStateException("There is no compatible downloader (all downloader returns downloader->isComplatible()=false or was skipped)!"); + throw new InvalidStateException('There is no compatible downloader (all downloader returns downloader->isComplatible()=false or was skipped)!'); } } diff --git a/FileDownloader/Downloader/AdvancedDownloader.php b/FileDownloader/Downloader/AdvancedDownloader.php index b2d8942..caacf0a 100644 --- a/FileDownloader/Downloader/AdvancedDownloader.php +++ b/FileDownloader/Downloader/AdvancedDownloader.php @@ -113,17 +113,17 @@ public function download(Request $request, Response $response, BaseFileDownload */ //$res->setHeader("Accept-Ranges", "0-".$this->end); // single-part - now not accepted by mozilla - $response->setHeader("Accept-Ranges", "bytes"); // multi-part (through Mozilla) + $response->setHeader('Accept-Ranges', 'bytes'); // multi-part (through Mozilla) // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2 - if ($request->getHeader("Range", false)) // If partial download + if ($request->getHeader('Range', false)) // If partial download { try { $range_start = $this->start; $range_end = $this->end; // Extract the range string - $rangeArray = explode('=', $request->getHeader("Range"), 2); + $rangeArray = explode('=', $request->getHeader('Range'), 2); $range = $rangeArray[1]; // Make sure the client hasn't sent us a multibyte range @@ -131,7 +131,7 @@ public function download(Request $request, Response $response, BaseFileDownload // (?) Shoud this be issued here, or should the first // range be used? Or should the header be ignored and // we output the whole content? - throw new FileDownloaderException("HTTP 416",416); + throw new FileDownloaderException('HTTP 416',416); } // If the range starts with an '-' we start from the beginning @@ -155,7 +155,7 @@ public function download(Request $request, Response $response, BaseFileDownload $range_end = ($range_end > $this->end) ? $this->end : $range_end; // Validate the requested range and return an error if it's not correct. if ($range_start > $range_end || $range_start > $this->size - 1 || $range_end >= $this->size) { - throw new FileDownloaderException("HTTP 416",416); + throw new FileDownloaderException('HTTP 416',416); } // All is ok - so assign variables back @@ -164,7 +164,7 @@ public function download(Request $request, Response $response, BaseFileDownload $this->length = $this->end - $this->start + 1; // Calculate new content length } catch (FileDownloaderException $e) { if ($e->getCode() === 416) { - $response->setHeader("Content-Range", "bytes $this->start-$this->end/$this->size"); + $response->setHeader('Content-Range', "bytes $this->start-$this->end/$this->size"); FDTools::_HTTPError($response, 416); } else { throw $e; @@ -174,8 +174,8 @@ public function download(Request $request, Response $response, BaseFileDownload } // End of if partial download // Notify the client the byte range we'll be outputting - $response->setHeader("Content-Range","bytes $this->start-$this->end/$this->size"); - $response->setHeader("Content-Length",$this->length); + $response->setHeader('Content-Range',"bytes $this->start-$this->end/$this->size"); + $response->setHeader('Content-Length',$this->length); /* ### Call callbacks ### */ @@ -197,17 +197,17 @@ public function download(Request $request, Response $response, BaseFileDownload $this->sleep = $sleep; if ($buffer < 1) { - throw new InvalidArgumentException("Buffer must be bigger than zero!"); + throw new InvalidArgumentException('Buffer must be bigger than zero!'); } $availableMem = FDTools::getAvailableMemory(); if ($availableMem && $buffer > ($availableMem - memory_get_usage())) { - throw new InvalidArgumentException("Buffer is too big! (bigger than available memory)"); + throw new InvalidArgumentException('Buffer is too big! (bigger than available memory)'); } $this->buffer = $buffer; - $fp = fopen($transfer->sourceFile,"rb"); + $fp = fopen($transfer->sourceFile, 'rb'); // TODO: Add flock() READ if (!$fp) { throw new InvalidStateException("Can't open file for reading!"); @@ -276,19 +276,21 @@ protected function processNative($fp) { } protected function processByCUrl() { - if(function_exists("curl_init")) { // Curl available + if(function_exists('curl_init')) { // Curl available $transfer = $this->currentTransfer; - $ch = curl_init("file://" . realpath($transfer->sourceFile)); + $ch = curl_init('file://' . realpath($transfer->sourceFile)); $range = $this->start.'-'.$this->end; // HTTP range curl_setopt($ch, CURLOPT_RANGE, $range); curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); curl_setopt($ch, CURLOPT_BUFFERSIZE, $this->buffer); - curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this,"_curlProcessBlock")); + curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, + '_curlProcessBlock' + )); $curlRet = curl_exec($ch); if($curlRet === false) { - throw new Exception("cUrl error number ".curl_errno($ch).": ".curl_error($ch)); + throw new Exception('cUrl error number ' .curl_errno($ch). ': ' .curl_error($ch)); } return true; }else{ diff --git a/FileDownloader/Downloader/BaseDownloader.php b/FileDownloader/Downloader/BaseDownloader.php index 34d2a44..69633f4 100644 --- a/FileDownloader/Downloader/BaseDownloader.php +++ b/FileDownloader/Downloader/BaseDownloader.php @@ -64,10 +64,10 @@ abstract class BaseDownloader extends Object implements IDownloader { protected function sendStandardFileHeaders(Request $request, Response $response, BaseFileDownload $file, BaseDownloader $downloader=null) { //FDTools::clearHeaders($res); // Voláno už v FileDownload.php - $response->setContentType($file->mimeType, "UTF-8"); - $response->setHeader("X-File-Downloader", "File Downloader (http://filedownloader.projekty.mujserver.net)"); + $response->setContentType($file->mimeType, 'UTF-8'); + $response->setHeader('X-File-Downloader', 'File Downloader (http://filedownloader.projekty.mujserver.net)'); if ($downloader !== null) { - $response->setHeader("X-FileDownloader-Actual-Script", $downloader->getReflection()->name); + $response->setHeader('X-FileDownloader-Actual-Script', $downloader->getReflection()->name); } $response->setHeader('Pragma', 'public'); // Fix for IE - Content-Disposition @@ -88,8 +88,8 @@ protected function sendStandardFileHeaders(Request $request, Response $response, protected function setupCacheHeaders(Response $response, BaseFileDownload $file) { $response->setExpiration(time() + 99999999); - $response->setHeader('Last-Modified', "Mon, 23 Jan 1978 10:00:00 GMT"); - if (!empty($_SERVER["HTTP_IF_MODIFIED_SINCE"])) { + $response->setHeader('Last-Modified', 'Mon, 23 Jan 1978 10:00:00 GMT'); + if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { $response->setCode(Response::S304_NOT_MODIFIED); //header("HTTP/1.1 304 Not Modified"); exit(); diff --git a/FileDownloader/Downloader/NativePHPDownloader.php b/FileDownloader/Downloader/NativePHPDownloader.php index 8f25eb0..0060ccd 100644 --- a/FileDownloader/Downloader/NativePHPDownloader.php +++ b/FileDownloader/Downloader/NativePHPDownloader.php @@ -68,7 +68,7 @@ public function download(Request $request, Response $response, BaseFileDownload flush(); if(!@readfile($file->sourceFile)) { - throw new InvalidStateException("PHP readfile() function fails!"); } + throw new InvalidStateException('PHP readfile() function fails!'); } // Or use this code? (from http://www.php.net/manual/en/function.readfile.php#50212) // diff --git a/FileDownloader/FDTools.php b/FileDownloader/FDTools.php index 3a36851..3dae3f9 100644 --- a/FileDownloader/FDTools.php +++ b/FileDownloader/FDTools.php @@ -72,7 +72,7 @@ class FDTools extends Object { * @return int|null */ public static function getAvailableMemory() { - $mem = self::parsePHPIniMemoryValue(ini_get("memory_limit")); + $mem = self::parsePHPIniMemoryValue(ini_get('memory_limit')); if ($mem == 0) { return null; } @@ -90,17 +90,17 @@ public static function parsePHPIniMemoryValue($phpIniValueStr) { return 0; } switch ($phpIniValueStr[strlen($phpIniValueStr) - 1]) { - case "K": + case 'K': $phpIniValueInt *= self::KILOBYTE; break; - case "M": + case 'M': $phpIniValueInt *= self::MEGABYTE; ; break; - case "G": + case 'G': $phpIniValueInt *= self::GYGABYTE; break; - case "T": + case 'T': $phpIniValueInt *= self::TERABYTE; break; default: @@ -120,7 +120,7 @@ public static function clearHeaders(IResponse $res, $setContentType=false) { $res->setHeader($key, null); } if ($setContentType === true) { - $res->setContentType("text/html", "UTF-8"); + $res->setContentType('text/html', 'UTF-8'); } return $res; } @@ -131,21 +131,21 @@ public static function clearHeaders(IResponse $res, $setContentType=false) { * @return bool */ public static function setTimeLimit($time=0) { - if (!function_exists("ini_get")) { - throw new InvalidStateException("Function ini_get must be allowed."); + if (!function_exists('ini_get')) { + throw new InvalidStateException('Function ini_get must be allowed.'); } - if ((int) @ini_get("max_execution_time") === $time) { + if ((int) @ini_get('max_execution_time') === $time) { return true; } - if (function_exists("set_time_limit")) { + if (function_exists('set_time_limit')) { @set_time_limit($time); - } elseif (function_exists("ini_set")) { - @ini_set("max_execution_time", $time); + } elseif (function_exists('ini_set')) { + @ini_set('max_execution_time', $time); } - if ((int) @ini_get("max_execution_time") === $time) { + if ((int) @ini_get('max_execution_time') === $time) { return true; } @@ -159,7 +159,7 @@ public static function setTimeLimit($time=0) { * @return string ETag */ public static function getETag($location) { - return "\"" . md5($location . filemtime($location) . self::filesize($location)) . "\""; + return '"' . md5($location . filemtime($location) . self::filesize($location)) . '"'; } @@ -174,8 +174,8 @@ public static function getETag($location) { */ public static function getContentDispositionHeaderData(Request $request, $basename) { $basename = basename($basename); - $userAgent = $request->getHeader("User-Agent"); - if ($userAgent AND strstr($userAgent, "MSIE")) { + $userAgent = $request->getHeader('User-Agent'); + if ($userAgent AND strstr($userAgent, 'MSIE')) { // workaround for IE filename bug with multiple periods / multiple dots in filename // that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe $iefilename = preg_replace('/\./', '%2e', $basename, substr_count($basename, '.') - 1); @@ -195,14 +195,14 @@ public static function getContentDispositionHeaderData(Request $request, $basena */ public static function _HTTPError(Response $response, $code, $message=null) { $errors = array( - 416=>"Requested Range not satisfiable" + 416=> 'Requested Range not satisfiable' ); if ($message === null and isset($errors[$code])) { $message = $errors[$code]; } $response->setCode($code); - $response->setContentType("plain/text","UTF-8"); - die("

HTTP Error ".$code." - ".$message."

".$message."

"); + $response->setContentType('plain/text', 'UTF-8'); + die('

HTTP Error ' .$code. ' - ' .$message. '

' .$message. '

'); } /** @@ -248,14 +248,14 @@ public static function readFile($location,$start=0,$end=null,$speedLimit=0) { $buffer = (int)round($speedLimit); } if ($buffer < 1) { - throw new InvalidArgumentException("Buffer must be bigger than zero!"); + throw new InvalidArgumentException('Buffer must be bigger than zero!'); } $availableMem = self::getAvailableMemory(); if ($availableMem && $buffer > ($availableMem * 0.9)) { - throw new InvalidArgumentException("Buffer is too big! (bigger than available memory)"); + throw new InvalidArgumentException('Buffer is too big! (bigger than available memory)'); } - $fp = fopen($location,"rb"); + $fp = fopen($location, 'rb'); if (!$fp) { throw new InvalidStateException("Can't open file for reading!"); } From ba7fc674ee420f2d9b736f010cc0a70cdae0a586 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 16:56:24 +0200 Subject: [PATCH 07/14] .gitignore: updated --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 187adb2..1991e63 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ -/nbproject/ \ No newline at end of file +/nbproject/ +/vendor +/.idea +/composer.lock \ No newline at end of file From c5168f4dc8fb468466593495193f72bfbb388ac3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 16:58:15 +0200 Subject: [PATCH 08/14] condition operators with higher priority --- FileDownloader/BaseFileDownload.php | 6 +++--- FileDownloader/Downloader/AdvancedDownloader.php | 4 ++-- FileDownloader/FDTools.php | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/FileDownloader/BaseFileDownload.php b/FileDownloader/BaseFileDownload.php index e692249..dc8d3a7 100644 --- a/FileDownloader/BaseFileDownload.php +++ b/FileDownloader/BaseFileDownload.php @@ -479,7 +479,7 @@ public function getMimeType() { } $mime = ""; - if (extension_loaded('fileinfo') and function_exists('finfo_open')) { + if (extension_loaded('fileinfo') && function_exists('finfo_open')) { //TODO: test this code: if ($finfo = @finfo_open(FILEINFO_MIME)) { $mime = @finfo_file($finfo, $this->sourceFile); @@ -545,7 +545,7 @@ public function download(IDownloader $downloader = null, Request $request, Respo $session->close(); } - if($this->getContentDisposition() == 'inline' AND $this->enableBrowserCache === NULL) { + if($this->getContentDisposition() == 'inline' && $this->enableBrowserCache === NULL) { $this->enableBrowserCache = true; }else{ $this->enableBrowserCache = false; @@ -566,7 +566,7 @@ public function download(IDownloader $downloader = null, Request $request, Respo $lastException = null; foreach($downloaders AS $downloader) { - if($downloader instanceof IDownloader and $downloader->isCompatible($this)) { + if($downloader instanceof IDownloader && $downloader->isCompatible($this)) { try { FDTools::clearHeaders($response); // Delete all headers $this->transferredBytes = 0; diff --git a/FileDownloader/Downloader/AdvancedDownloader.php b/FileDownloader/Downloader/AdvancedDownloader.php index caacf0a..dea94e2 100644 --- a/FileDownloader/Downloader/AdvancedDownloader.php +++ b/FileDownloader/Downloader/AdvancedDownloader.php @@ -190,7 +190,7 @@ public function download(Request $request, Response $response, BaseFileDownload $buffer = FDTools::$readFileBuffer; $sleep = false; - if(is_int($transfer->speedLimit) and $transfer->speedLimit>0) { + if(is_int($transfer->speedLimit) && $transfer->speedLimit>0) { $sleep = true; $buffer = (int)round($transfer->speedLimit); } @@ -338,7 +338,7 @@ protected function _afterBufferSent($tmpTime, $fp=null) { } die(); } - if($this->sleep == true OR $tmpTime<=time()) { + if($this->sleep == true || $tmpTime<=time()) { $transfer->transferredBytes = $this->transferred = $this->position-$this->start; $transfer->onStatusChange($transfer,$this); if ($tmpTime !== NULL) { diff --git a/FileDownloader/FDTools.php b/FileDownloader/FDTools.php index 3dae3f9..9d05cdb 100644 --- a/FileDownloader/FDTools.php +++ b/FileDownloader/FDTools.php @@ -175,7 +175,7 @@ public static function getETag($location) { public static function getContentDispositionHeaderData(Request $request, $basename) { $basename = basename($basename); $userAgent = $request->getHeader('User-Agent'); - if ($userAgent AND strstr($userAgent, 'MSIE')) { + if ($userAgent && strstr($userAgent, 'MSIE')) { // workaround for IE filename bug with multiple periods / multiple dots in filename // that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe $iefilename = preg_replace('/\./', '%2e', $basename, substr_count($basename, '.') - 1); @@ -197,7 +197,7 @@ public static function _HTTPError(Response $response, $code, $message=null) { $errors = array( 416=> 'Requested Range not satisfiable' ); - if ($message === null and isset($errors[$code])) { + if ($message === null && isset($errors[$code])) { $message = $errors[$code]; } $response->setCode($code); @@ -243,7 +243,7 @@ public static function isValidMimeType($mime) { public static function readFile($location,$start=0,$end=null,$speedLimit=0) { $buffer = self::$readFileBuffer; $sleep = false; - if(is_int($speedLimit) and $speedLimit>0) { + if(is_int($speedLimit) && $speedLimit>0) { $sleep = true; $buffer = (int)round($speedLimit); } From 67e705e9f6b6a948069d348cfc6a6a59375613b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 17:05:25 +0200 Subject: [PATCH 09/14] AppFileDownload: made hidden dependencies explicit --- FileDownloader/AppFileDownload.php | 33 +++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/FileDownloader/AppFileDownload.php b/FileDownloader/AppFileDownload.php index d7ee24a..e29d300 100644 --- a/FileDownloader/AppFileDownload.php +++ b/FileDownloader/AppFileDownload.php @@ -44,6 +44,9 @@ use Nette\ComponentModel\Component; use Nette\Http\IRequest; use Nette\Http\IResponse; +use Nette\Http\Request; +use Nette\Http\Response; +use Nette\Http\Session; /** * @link http://filedownloader.projekty.mujserver.net @@ -67,21 +70,41 @@ class AppFileDownload extends BaseFileDownload implements IResponse2 { */ private $downloader; + /** + * @var Request + */ + private $request; + + /** + * @var Response + */ + private $response; + + /** + * @var Session + */ + private $session; + + /** * Getts new instance of self * @param Component $parent * @return AppFileDownload + * @deprecated */ - public static function getInstance(Component $parent) { - return new AppFileDownload($parent); + public static function getInstance(Component $parent, Request $request, Response $response, Session $session) { + return new AppFileDownload($parent, $request, $response, $session); } /** * @param Component $parent */ - public function __construct(Component $parent) { + public function __construct(Component $parent, Request $request, Response $response, Session $session) { parent::__construct(); $this->setParent($parent); + $this->request = $request; + $this->response = $response; + $this->session = $session; } /** @@ -106,14 +129,14 @@ public function getParent() { * Implementation of IPresenterResponse::send() */ public function send(IRequest $httpRequest, IResponse $httpResponse) { - parent::download($this->downloader); + parent::download($this->downloader, $this->request, $this->response, $this->session); } /** * Start download of the file! * @param IDownloader $downloader */ - public function download(IDownloader $downloader = null) { + public function download(IDownloader $downloader = null, Request $request, Response $response, Session $session) { $this->downloader = $downloader; // Call sendResponse on presenter (used since 2.0 instead of terminate) From 7ecdd1dcffb20c1e2534fdef7f6ab3cac6defbb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 17:09:01 +0200 Subject: [PATCH 10/14] renamed overridden parameter --- FileDownloader/BaseFileDownload.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/FileDownloader/BaseFileDownload.php b/FileDownloader/BaseFileDownload.php index 8d38020..50c3509 100644 --- a/FileDownloader/BaseFileDownload.php +++ b/FileDownloader/BaseFileDownload.php @@ -539,7 +539,7 @@ public function getSourceFileSize() { * @param Session $session HTTP Session (this is needed to be able to close it * @throws Exception */ - public function download(IDownloader $downloader = null, Request $request, Response $response, Session $session) { + public function download(IDownloader $inputDownloader = null, Request $request, Response $response, Session $session) { if($session->isStarted()) { $session->close(); @@ -551,10 +551,10 @@ public function download(IDownloader $downloader = null, Request $request, Respo $this->enableBrowserCache = false; } - if ($downloader === null) { + if ($inputDownloader === null) { $downloaders = self::getFileDownloaders(); } else { - $downloaders = array($downloader); + $downloaders = array($inputDownloader); } if (count($downloaders) <= 0) { From 5dbc90454bcef0cf8cdab9c20087415f34f974d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 17:14:34 +0200 Subject: [PATCH 11/14] AppFileDownload: simplified [BC break] --- FileDownloader/AppFileDownload.php | 67 +++--------------------------- 1 file changed, 6 insertions(+), 61 deletions(-) diff --git a/FileDownloader/AppFileDownload.php b/FileDownloader/AppFileDownload.php index e29d300..7d56657 100644 --- a/FileDownloader/AppFileDownload.php +++ b/FileDownloader/AppFileDownload.php @@ -39,9 +39,6 @@ namespace FileDownloader; -use Nette\Application\IResponse as IResponse2; -use Nette\Application\UI\Presenter; -use Nette\ComponentModel\Component; use Nette\Http\IRequest; use Nette\Http\IResponse; use Nette\Http\Request; @@ -54,15 +51,8 @@ * @author Jan Kuchař * @copyright  Copyright (c) 2014 Jan Kuchar * @author Jan Kuchař - * - * @property Component $parent Parent component */ -class AppFileDownload extends BaseFileDownload implements IResponse2 { - /** - * Parent of this object - * @var Component - */ - private $parent; +class AppFileDownload extends BaseFileDownload implements \Nette\Application\IResponse { /** * Downloader used to download file (optional) @@ -85,69 +75,24 @@ class AppFileDownload extends BaseFileDownload implements IResponse2 { */ private $session; - - /** - * Getts new instance of self - * @param Component $parent - * @return AppFileDownload - * @deprecated - */ - public static function getInstance(Component $parent, Request $request, Response $response, Session $session) { - return new AppFileDownload($parent, $request, $response, $session); - } - - /** - * @param Component $parent - */ - public function __construct(Component $parent, Request $request, Response $response, Session $session) { + public function __construct(Request $request, Response $response, Session $session) { parent::__construct(); - $this->setParent($parent); $this->request = $request; $this->response = $response; $this->session = $session; } - /** - * Setts AppFileDownload parent - * @param Component $parent - * @return AppFileDownload - */ - public function setParent(Component $parent) { - $this->parent = $parent; - return $this; - } - - /** - * Getts AppFileDownload parent - * @return Component - */ - public function getParent() { - return $this->parent; + public function setDownloader(IDownloader $downloader) { + $this->downloader = $downloader; } - /** - * Implementation of IPresenterResponse::send() - */ + /* Implementation of IPresenterResponse::send() */ public function send(IRequest $httpRequest, IResponse $httpResponse) { parent::download($this->downloader, $this->request, $this->response, $this->session); } - /** - * Start download of the file! - * @param IDownloader $downloader - */ public function download(IDownloader $downloader = null, Request $request, Response $response, Session $session) { - $this->downloader = $downloader; - - // Call sendResponse on presenter (used since 2.0 instead of terminate) - if($this->parent instanceof Presenter) { - $presenter = $this->parent; - } else { - $presenter = $this->parent->lookup('Nette/Application/UI/Presenter',true); - } - - $presenter->sendResponse($this); - + throw new \LogicException('Use Presenter::sendResponse() to send response to client.'); } } From 6fb84d86a37d5de39e6bc724f4b92a0a2aba4848 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 17:15:50 +0200 Subject: [PATCH 12/14] strict comparison where possible --- FileDownloader/BaseFileDownload.php | 2 +- FileDownloader/Downloader/AdvancedDownloader.php | 10 +++++----- FileDownloader/FDTools.php | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/FileDownloader/BaseFileDownload.php b/FileDownloader/BaseFileDownload.php index 50c3509..954e090 100644 --- a/FileDownloader/BaseFileDownload.php +++ b/FileDownloader/BaseFileDownload.php @@ -545,7 +545,7 @@ public function download(IDownloader $inputDownloader = null, Request $request, $session->close(); } - if($this->getContentDisposition() == 'inline' && $this->enableBrowserCache === NULL) { + if($this->enableBrowserCache === NULL && $this->getContentDisposition() === 'inline') { $this->enableBrowserCache = true; }else{ $this->enableBrowserCache = false; diff --git a/FileDownloader/Downloader/AdvancedDownloader.php b/FileDownloader/Downloader/AdvancedDownloader.php index dea94e2..6fc42f2 100644 --- a/FileDownloader/Downloader/AdvancedDownloader.php +++ b/FileDownloader/Downloader/AdvancedDownloader.php @@ -137,7 +137,7 @@ public function download(Request $request, Response $response, BaseFileDownload // If the range starts with an '-' we start from the beginning // If not, we forward the file pointer // And make sure to get the end byte if spesified - if ($range{0} == '-') { + if ($range{0} === '-') { // The n-number of the last bytes is requested $range_start = $this->size - (float)substr($range, 1); } @@ -328,7 +328,7 @@ protected function _afterBufferSent($tmpTime, $fp=null) { flush(); // PHP: Do not buffer it - send it to browser! @ob_flush(); - if(connection_status()!=CONNECTION_NORMAL) { + if(connection_status() !== CONNECTION_NORMAL) { if ($fp) { fclose($fp); } @@ -338,14 +338,14 @@ protected function _afterBufferSent($tmpTime, $fp=null) { } die(); } - if($this->sleep == true || $tmpTime<=time()) { + if($this->sleep === true || $tmpTime<=time()) { $transfer->transferredBytes = $this->transferred = $this->position-$this->start; $transfer->onStatusChange($transfer,$this); if ($tmpTime !== NULL) { $tmpTime = time() + 1; } } - if ($this->sleep == true) { + if ($this->sleep === true) { sleep(1); } } @@ -355,7 +355,7 @@ protected function _afterBufferSent($tmpTime, $fp=null) { * @return bool */ public function isInitialized() { - if ($this->end == 0) { + if ($this->end === 0) { return false; } return true; diff --git a/FileDownloader/FDTools.php b/FileDownloader/FDTools.php index 9d05cdb..060cdb7 100644 --- a/FileDownloader/FDTools.php +++ b/FileDownloader/FDTools.php @@ -73,7 +73,7 @@ class FDTools extends Object { */ public static function getAvailableMemory() { $mem = self::parsePHPIniMemoryValue(ini_get('memory_limit')); - if ($mem == 0) { + if ($mem === 0) { return null; } return $mem-memory_get_usage(); @@ -271,7 +271,7 @@ public static function readFile($location,$start=0,$end=null,$speedLimit=0) { } echo fread($fp, $buffer); flush(); - if ($sleep == true) { + if ($sleep === true) { sleep(1); } } From d4ab05bee75cb84403fb5161182d84d616b25c7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 17:20:48 +0200 Subject: [PATCH 13/14] minor random fixes --- FileDownloader/BaseFileDownload.php | 4 ++-- FileDownloader/Downloader/AdvancedDownloader.php | 2 +- FileDownloader/Downloader/NativePHPDownloader.php | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/FileDownloader/BaseFileDownload.php b/FileDownloader/BaseFileDownload.php index 954e090..3f5c379 100644 --- a/FileDownloader/BaseFileDownload.php +++ b/FileDownloader/BaseFileDownload.php @@ -386,7 +386,7 @@ public function setSourceFile($location) { /** * Getts location of the source file - * @return BaseFileDownload + * @return string */ public function getSourceFile() { if ($this->vSourceFile === null) { @@ -402,7 +402,7 @@ public function getSourceFile() { */ public function setContentDisposition($disposition) { $values = array('inline', 'attachment'); - if (!in_array($disposition, $values)) { + if (!in_array($disposition, $values, TRUE)) { throw new InvalidArgumentException('Content disposition must be one of these: ' . implode(',', $values)); } $this->vContentDisposition = $disposition; diff --git a/FileDownloader/Downloader/AdvancedDownloader.php b/FileDownloader/Downloader/AdvancedDownloader.php index 6fc42f2..c0e152f 100644 --- a/FileDownloader/Downloader/AdvancedDownloader.php +++ b/FileDownloader/Downloader/AdvancedDownloader.php @@ -242,7 +242,7 @@ public function download(Request $request, Response $response, BaseFileDownload $this->position = $this->start; } - $this->processNative($fp,$sleep); + $this->processNative($fp); $this->cleanAfterTransfer(); } diff --git a/FileDownloader/Downloader/NativePHPDownloader.php b/FileDownloader/Downloader/NativePHPDownloader.php index 0060ccd..749f0a8 100644 --- a/FileDownloader/Downloader/NativePHPDownloader.php +++ b/FileDownloader/Downloader/NativePHPDownloader.php @@ -64,7 +64,7 @@ public function download(Request $request, Response $response, BaseFileDownload // Bugfix: when output buffer active, there is a problem with memory // @see http://www.php.net/manual/en/function.readfile.php#81032 - while (@ob_end_flush()); // @see example at http://php.net/manual/en/function.ob-end-flush.php + while (@ob_end_flush()) {}; // @see example at http://php.net/manual/en/function.ob-end-flush.php flush(); if(!@readfile($file->sourceFile)) { From 5f78e452c5959ce75e0cd79c4c479adf5089507c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Kucha=C5=99?= Date: Mon, 27 Mar 2017 17:22:49 +0200 Subject: [PATCH 14/14] MSIE: fix for non-ascii names (need to be tested properly) --- FileDownloader/FDTools.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FileDownloader/FDTools.php b/FileDownloader/FDTools.php index 060cdb7..a887fd0 100644 --- a/FileDownloader/FDTools.php +++ b/FileDownloader/FDTools.php @@ -179,7 +179,7 @@ public static function getContentDispositionHeaderData(Request $request, $basena // workaround for IE filename bug with multiple periods / multiple dots in filename // that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe $iefilename = preg_replace('/\./', '%2e', $basename, substr_count($basename, '.') - 1); - $basename = rawurlencode($basename); // Czech chars in filename + $basename = rawurlencode($iefilename); // Czech chars in filename } return $basename; }