From 04d81e8553ead1750d63e5679a6435268d45eb1d Mon Sep 17 00:00:00 2001 From: cdujeu Date: Fri, 10 Jun 2016 11:12:06 +0200 Subject: [PATCH] Clean HTMLWriter class --- .../src/pydio/Core/Controller/HTMLWriter.php | 188 +++++++++++------- .../src/pydio/Core/Controller/XMLWriter.php | 23 --- .../Core/Http/Response/FileReaderResponse.php | 2 +- .../editor.browser/class.FileMimeSender.php | 111 ++++++----- .../src/plugins/meta.git/class.GitManager.php | 51 ++--- 5 files changed, 199 insertions(+), 176 deletions(-) diff --git a/core/src/core/src/pydio/Core/Controller/HTMLWriter.php b/core/src/core/src/pydio/Core/Controller/HTMLWriter.php index 287c35f83c..ead82f14a7 100644 --- a/core/src/core/src/pydio/Core/Controller/HTMLWriter.php +++ b/core/src/core/src/pydio/Core/Controller/HTMLWriter.php @@ -22,7 +22,6 @@ use Psr\Http\Message\ResponseInterface; use Pydio\Core\Services\ConfService; -use Pydio\Core\Services\LocaleService; use Pydio\Core\Utils\TextEncoder; defined('AJXP_EXEC') or die( 'Access not allowed'); @@ -34,19 +33,6 @@ */ class HTMLWriter { - /** - * Write an HTML block message - * @static - * @param string $logMessage - * @param string $errorMessage - * @return void - */ - public static function displayMessage($logMessage, $errorMessage) - { - $mess = LocaleService::getMessages(); - echo "
".(isset($logMessage)?$logMessage:$errorMessage)."".$mess[98]."
"; - echo ""; - } /** * Replace the doc files keywords @@ -68,29 +54,6 @@ public static function getDocFile($docFileName) } return "File not found : ".$docFileName; } - /** - * Write the messages as Javascript - * @static - * @param array $mess - * @return void - */ - public static function writeI18nMessagesClass($mess) - { - echo "\n"; - } /** * Send a simple Content-type header @@ -127,15 +90,6 @@ public static function charsetHeader($type = 'text/html', $charset='UTF-8') { header("Content-type:$type; charset=$charset"); } - /** - * Write a closing sequence - * @static - * @return void - */ - public static function closeBodyAndPage() - { - print(""); - } /** * Write directly an error as a javascript instruction @@ -151,7 +105,58 @@ public static function javascriptErrorHandler($errorType, $errorMessage) die(""); } - public static function encodeAttachmentName($name){ + + /** + * @param ResponseInterface $response + * @param $attachName + * @param $fileSize + * @param $mimeType + * @return ResponseInterface + */ + public static function responseWithInlineHeaders(ResponseInterface $response, $attachName, $fileSize, $mimeType){ + return self::generateInlineHeaders($attachName, $fileSize, $mimeType, $response); + } + + /** + * @param ResponseInterface $response + * @param $attachmentName + * @param $dataSize + * @param bool $isFile + * @param bool $gzip + * @return null|ResponseInterface + */ + public static function responseWithAttachmentsHeaders(ResponseInterface $response, &$attachmentName, $dataSize, $isFile=true, $gzip=false){ + return self::generateAttachmentsHeader($attachmentName, $dataSize, $isFile, $gzip, $response); + } + + + /** + * @param $attachName + * @param $fileSize + * @param $mimeType + */ + public static function emitInlineHeaders($attachName, $fileSize, $mimeType){ + self::generateInlineHeaders($attachName, $fileSize, $mimeType); + } + + /** + * @param $attachmentName + * @param $dataSize + * @param bool $isFile + * @param bool $gzip + */ + public static function emitAttachmentsHeaders(&$attachmentName, $dataSize, $isFile=true, $gzip=false){ + self::generateAttachmentsHeader($attachmentName, $dataSize, $isFile, $gzip); + } + + + + /** + * Correctly encode name for attachment header + * @param string $name + * @return string + */ + private static function encodeAttachmentName($name){ if (preg_match('/ MSIE /',$_SERVER['HTTP_USER_AGENT']) || preg_match('/ WebKit /',$_SERVER['HTTP_USER_AGENT']) || preg_match('/ Trident/',$_SERVER['HTTP_USER_AGENT'])) { @@ -166,69 +171,98 @@ public static function encodeAttachmentName($name){ * @param int $dataSize * @param bool $isFile * @param bool $gzip If true, make sure the $dataSize is the size of the ENCODED data. + * @param ResponseInterface $response Response to update instead of generating headers + * @return ResponseInterface|null Update response interface if passed by argument */ - public static function generateAttachmentsHeader(&$attachmentName, $dataSize, $isFile=true, $gzip=false) + private static function generateAttachmentsHeader(&$attachmentName, $dataSize, $isFile=true, $gzip=false, ResponseInterface $response = null) { $attachmentName = self::encodeAttachmentName($attachmentName); - header("Content-Type: application/force-download; name=\"".$attachmentName."\""); - header("Content-Transfer-Encoding: binary"); + $headers = []; + $headers["Content-Type"] = "application/force-download; name=\"".$attachmentName."\""; + $headers["Content-Transfer-Encoding"] = "binary"; if ($gzip) { - header("Content-Encoding: gzip"); + $headers["Content-Encoding"] = "gzip"; } - header("Content-Length: ".$dataSize); + $headers["Content-Length"] = $dataSize; if ($isFile && ($dataSize != 0)) { - header("Content-Range: bytes 0-" . ($dataSize- 1) . "/" . $dataSize . ";"); + $headers["Content-Range"] = "bytes 0-" . ($dataSize- 1) . "/" . $dataSize . ";"; } - header("Content-Disposition: attachment; filename=\"".$attachmentName."\""); - header("Expires: 0"); - header("Cache-Control: no-cache, must-revalidate"); - header("Pragma: no-cache"); + $headers["Content-Disposition"] = "attachment; filename=\"".$attachmentName."\""; + $headers["Expires"] = "0"; + $headers["Cache-Control"] = "no-cache, must-revalidate"; + $headers["Pragma"] = "no-cache"; + if (preg_match('/ MSIE /',$_SERVER['HTTP_USER_AGENT'])) { - header("Cache-Control: max_age=0"); - header("Pragma: public"); + $headers["Pragma"] = "public"; + $headers["Cache-Control"] = "max_age=0"; } // IE8 is dumb if (preg_match('/ MSIE /',$_SERVER['HTTP_USER_AGENT'])) { - header("Pragma: public"); - header("Expires: 0"); - header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); - header("Cache-Control: private",false); + $headers["Pragma"] = "public"; + $headers["Cache-Control"] = "private, must-revalidate, post-check=0, pre-check=0"; } // For SSL websites there is a bug with IE see article KB 323308 // therefore we must reset the Cache-Control and Pragma Header if (ConfService::getConf("USE_HTTPS")==1 && preg_match('/ MSIE /',$_SERVER['HTTP_USER_AGENT'])) { - header("Cache-Control:"); - header("Pragma:"); + $headers["Pragma"] = ""; + $headers["Cache-Control"] = ""; } + + foreach($headers as $headerName => $headerValue){ + if($response !== null){ + $response = $response->withHeader($headerName, $headerValue); + }else{ + header($headerName.": ".$headerValue); + } + } + + return $response; } - public static function generateInlineHeaders($attachName, $fileSize, $mimeType) + /** + * Generate correct headers + * @param string $attachName + * @param int $fileSize + * @param string $mimeType + * @param ResponseInterface $response + * @return ResponseInterface + */ + private static function generateInlineHeaders($attachName, $fileSize, $mimeType, ResponseInterface $response = null) { $attachName = self::encodeAttachmentName($attachName); - //Send headers - header("Content-Type: " . $mimeType . "; name=\"" . $attachName . "\""); - header("Content-Disposition: inline; filename=\"" . $attachName . "\""); + $headers = []; + $headers["Content-Type"] = $mimeType . "; name=\"" . $attachName . "\""; + $headers["Content-Disposition"] = "inline; filename=\"" . $attachName . "\""; // changed header for IE 7 & 8 if (preg_match('/ MSIE /',$_SERVER['HTTP_USER_AGENT'])) { - header("Pragma: public"); - header("Expires: 0"); - header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); - header("Cache-Control: private",false); + $headers["Expires"] = "0"; + $headers["Pragma"] = "public"; + $headers["Cache-Control"] = "private, must-revalidate, post-check=0, pre-check=0"; } else { - header("Cache-Control: public"); + $headers["Cache-Control"] = "public"; } - header("Content-Length: " . $fileSize); + $headers["Content-Length"] = $fileSize; // Neccessary for IE 8 and xx if (ConfService::getConf("USE_HTTPS")==1 && preg_match('/ MSIE /',$_SERVER['HTTP_USER_AGENT'])) { - header("Cache-Control:"); - header("Pragma:"); + $headers["Pragma"] = ""; + $headers["Cache-Control"] = ""; } + foreach($headers as $headerName => $headerValue){ + if($response !== null){ + $response = $response->withHeader($headerName, $headerValue); + }else{ + header($headerName.": ".$headerValue); + } + } + + return $response; + } } diff --git a/core/src/core/src/pydio/Core/Controller/XMLWriter.php b/core/src/core/src/pydio/Core/Controller/XMLWriter.php index 85705484df..8da8f36059 100644 --- a/core/src/core/src/pydio/Core/Controller/XMLWriter.php +++ b/core/src/core/src/pydio/Core/Controller/XMLWriter.php @@ -705,29 +705,6 @@ public static function repositoryToXML($repoId, $repoObject, $exposed, $streams, } - /** - * Writes a tag - * @static - * @param integer $result - * @param string $rememberLogin - * @param string $rememberPass - * @param string $secureToken - * @return void|string - */ - public static function loggingResult($result, $rememberLogin="", $rememberPass = "", $secureToken="", $print = true) - { - $remString = ""; - if ($rememberPass != "" && $rememberLogin!= "") { - $remString = " remember_login=\"$rememberLogin\" remember_pass=\"$rememberPass\""; - } - if ($secureToken != "") { - $remString .= " secure_token=\"$secureToken\""; - } - $st = ""; - if($print) print $st; - else return $st; - } - /** * Create plain PHP associative array from XML. * diff --git a/core/src/core/src/pydio/Core/Http/Response/FileReaderResponse.php b/core/src/core/src/pydio/Core/Http/Response/FileReaderResponse.php index a891327881..7efbac8e23 100644 --- a/core/src/core/src/pydio/Core/Http/Response/FileReaderResponse.php +++ b/core/src/core/src/pydio/Core/Http/Response/FileReaderResponse.php @@ -272,7 +272,7 @@ public function readFile($node = null, $filePath = null, $data = null, $headerTy } - HTMLWriter::generateAttachmentsHeader($localName, $size, $isFile, $confGzip); + HTMLWriter::emitAttachmentsHeaders($localName, $size, $isFile, $confGzip); if ($confGzip && isSet($gzippedData)) { print $gzippedData; diff --git a/core/src/plugins/editor.browser/class.FileMimeSender.php b/core/src/plugins/editor.browser/class.FileMimeSender.php index c77d1f2dd2..21e1126ee4 100755 --- a/core/src/plugins/editor.browser/class.FileMimeSender.php +++ b/core/src/plugins/editor.browser/class.FileMimeSender.php @@ -37,81 +37,90 @@ */ class FileMimeSender extends Plugin { - public function switchAction($action, $httpVars, $filesVars, \Pydio\Core\Model\ContextInterface $ctx) + public function switchAction(\Psr\Http\Message\ServerRequestInterface $requestInterface, \Psr\Http\Message\ResponseInterface &$responseInterface) { + if($requestInterface->getAttribute("action") !== "open_file"){ + return; + } + + /** @var \Pydio\Core\Model\ContextInterface $ctx */ + $ctx = $requestInterface->getAttribute("ctx"); + $httpVars = $requestInterface->getParsedBody(); + $repository = RepositoryService::getRepositoryById($httpVars["repository_id"]); if (UsersService::usersEnabled()) { $loggedUser = $ctx->getUser(); if (!$loggedUser->canSwitchTo($repository->getId())) { - echo("You do not have permissions to access this resource"); - return false; + throw new \Pydio\Core\Exception\AuthRequiredException(); } } $selection = UserSelection::fromContext($ctx, $httpVars); - if ($action == "open_file") { - $selectedNode = $selection->getUniqueNode(); - $selectedNodeUrl = $selectedNode->getUrl(); + $selectedNode = $selection->getUniqueNode(); + $selectedNodeUrl = $selectedNode->getUrl(); - if (!file_exists($selectedNodeUrl) || !is_readable($selectedNodeUrl)) { - echo("File does not exist"); - return false; - } + if (!file_exists($selectedNodeUrl) || !is_readable($selectedNodeUrl)) { + throw new \Pydio\Core\Exception\PydioException("File does not exist"); + } - $filesize = filesize($selectedNodeUrl); - $fp = fopen($selectedNodeUrl, "rb"); - $fileMime = "application/octet-stream"; + $filesize = filesize($selectedNodeUrl); + $fp = fopen($selectedNodeUrl, "rb"); + $fileMime = "application/octet-stream"; - //Get mimetype with fileinfo PECL extension - if (class_exists("finfo")) { - $finfo = new finfo(FILEINFO_MIME); - $fileMime = $finfo->buffer(fread($fp, 2000)); - } - //Get mimetype with (deprecated) mime_content_type - if (strpos($fileMime, "application/octet-stream")===0 && function_exists("mime_content_type")) { - $fileMime = @mime_content_type($fp); - } - //Guess mimetype based on file extension - if (strpos($fileMime, "application/octet-stream")===0 ) { - $fileExt = substr(strrchr(basename($selectedNodeUrl), '.'), 1); - if(empty($fileExt)) - $fileMime = "application/octet-stream"; - else { - $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileExt\s)/i"; - $lines = file( $this->getBaseDir()."/resources/other/mime.types"); - foreach ($lines as $line) { - if(substr($line, 0, 1) == '#') - continue; // skip comments - $line = rtrim($line) . " "; - if(!preg_match($regex, $line, $matches)) - continue; // no match to the extension - $fileMime = $matches[1]; - } + //Get mimetype with fileinfo PECL extension + if (class_exists("finfo")) { + $finfo = new finfo(FILEINFO_MIME); + $fileMime = $finfo->buffer(fread($fp, 2000)); + } + //Get mimetype with (deprecated) mime_content_type + if (strpos($fileMime, "application/octet-stream")===0 && function_exists("mime_content_type")) { + $fileMime = @mime_content_type($fp); + } + //Guess mimetype based on file extension + if (strpos($fileMime, "application/octet-stream")===0 ) { + $fileExt = substr(strrchr(basename($selectedNodeUrl), '.'), 1); + if(empty($fileExt)) + $fileMime = "application/octet-stream"; + else { + $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileExt\s)/i"; + $lines = file( $this->getBaseDir()."/resources/other/mime.types"); + foreach ($lines as $line) { + if(substr($line, 0, 1) == '#') + continue; // skip comments + $line = rtrim($line) . " "; + if(!preg_match($regex, $line, $matches)) + continue; // no match to the extension + $fileMime = $matches[1]; } } - fclose($fp); - // If still no mimetype, give up and serve application/octet-stream - if(empty($fileMime)) - $fileMime = "application/octet-stream"; + } + fclose($fp); + // If still no mimetype, give up and serve application/octet-stream + if(empty($fileMime)) + $fileMime = "application/octet-stream"; - if(strpos($fileMime, "image/svg+xml;") === 0){ - // Do not open SVG directly in browser. - $fileMime = "application/octet-stream"; - } + if(strpos($fileMime, "image/svg+xml;") === 0){ + // Do not open SVG directly in browser. + $fileMime = "application/octet-stream"; + } - //Send headers - HTMLWriter::generateInlineHeaders(basename($selectedNodeUrl), $filesize, $fileMime); + //Send headers + $responseInterface = HTMLWriter::responseWithInlineHeaders($responseInterface, basename($selectedNodeUrl), $filesize, $fileMime); + $aSyncReader = new \Pydio\Core\Http\Response\AsyncResponseStream(function () use ($selectedNode){ $stream = fopen("php://output", "a"); - AJXP_MetaStreamWrapper::copyFileInStream($selectedNodeUrl, $stream); + AJXP_MetaStreamWrapper::copyFileInStream($selectedNode->getUrl(), $stream); fflush($stream); fclose($stream); Controller::applyHook("node.read", array($selectedNode)); - $this->logInfo('Download', 'Read content of '.$selectedNodeUrl, array("files" => $selectedNodeUrl)); + $this->logInfo('Download', 'Read content of '.$selectedNode->getUrl(), array("files" => $selectedNode->getUrl())); + + }); + + $responseInterface = $responseInterface->withBody($aSyncReader); - } } } diff --git a/core/src/plugins/meta.git/class.GitManager.php b/core/src/plugins/meta.git/class.GitManager.php index bcf91a033b..18b68f0729 100644 --- a/core/src/plugins/meta.git/class.GitManager.php +++ b/core/src/plugins/meta.git/class.GitManager.php @@ -73,10 +73,11 @@ public function initMeta(ContextInterface $ctx, AbstractAccessDriver $accessDriv */ public function applyActions(\Psr\Http\Message\ServerRequestInterface $requestInterface, \Psr\Http\Message\ResponseInterface &$responseInterface) { - $actionName = $requestInterface->getAttribute("action"); - $httpVars = $requestInterface->getParsedBody(); - $x = new \Pydio\Core\Http\Response\SerializableResponseStream(); - $responseInterface = $responseInterface->withBody($x); + + $actionName = $requestInterface->getAttribute("action"); + $httpVars = $requestInterface->getParsedBody(); + $x = new \Pydio\Core\Http\Response\SerializableResponseStream(); + $responseInterface = $responseInterface->withBody($x); $git = new VersionControl_Git($this->repoBase); switch ($actionName) { @@ -145,28 +146,30 @@ public function applyActions(\Psr\Http\Message\ServerRequestInterface $requestIn $command->addArgument($commitId.":".$file); $commandLine = $command->createCommandString(); - $reader = function() use ($git, $commandLine, $attach, $file, $size){ - if ($attach == "inline") { - $fileExt = substr(strrchr(basename($file), '.'), 1); - if (empty($fileExt)) { - $fileMime = "application/octet-stream"; - } else { - $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileExt\s)/i"; - $lines = file( AJXP_INSTALL_PATH."/".AJXP_PLUGINS_FOLDER."/editor.browser/resources/other/mime.types"); - foreach ($lines as $line) { - if(substr($line, 0, 1) == '#') - continue; // skip comments - $line = rtrim($line) . " "; - if(!preg_match($regex, $line, $matches)) - continue; // no match to the extension - $fileMime = $matches[1]; - } - } - if(empty($fileMime)) $fileMime = "application/octet-stream"; - HTMLWriter::generateInlineHeaders(basename($file), $size, $fileMime); + if ($attach == "inline") { + $fileExt = substr(strrchr(basename($file), '.'), 1); + if (empty($fileExt)) { + $fileMime = "application/octet-stream"; } else { - HTMLWriter::generateAttachmentsHeader(basename($file), $size, false, false); + $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileExt\s)/i"; + $lines = file( AJXP_INSTALL_PATH."/".AJXP_PLUGINS_FOLDER."/editor.browser/resources/other/mime.types"); + foreach ($lines as $line) { + if(substr($line, 0, 1) == '#') + continue; // skip comments + $line = rtrim($line) . " "; + if(!preg_match($regex, $line, $matches)) + continue; // no match to the extension + $fileMime = $matches[1]; + } } + if(empty($fileMime)) $fileMime = "application/octet-stream"; + $responseInterface = HTMLWriter::responseWithInlineHeaders($responseInterface, basename($file), $size, $fileMime); + } else { + $responseInterface = HTMLWriter::responseWithAttachmentsHeaders($responseInterface, basename($file), $size, false, false); + } + + + $reader = function() use ($git, $commandLine){ $outputStream = fopen("php://output", "a"); $this->executeCommandInStreams($git, $commandLine, $outputStream); fclose($outputStream);