From 366b73d27ed4ecbccd68a3464883d12482ba8fe2 Mon Sep 17 00:00:00 2001 From: Loic d'Anterroches Date: Tue, 5 Aug 2008 12:44:56 +0200 Subject: [PATCH] Fixed issue 10, add mime type when downloading a file. --- src/IDF/Tests/TestSource.php | 47 ++++++++++++++++++++++++++++++++++++ src/IDF/Views/Source.php | 39 ++++++++++++++++++++++++++++-- 2 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 src/IDF/Tests/TestSource.php diff --git a/src/IDF/Tests/TestSource.php b/src/IDF/Tests/TestSource.php new file mode 100644 index 0000000..77e5977 --- /dev/null +++ b/src/IDF/Tests/TestSource.php @@ -0,0 +1,47 @@ + 'application/x-httpd-php', + 'whatever.pht' => 'application/x-httpd-php', + 'README' => 'text/plain', + ); + foreach ($files as $file => $mime) { + $m = IDF_Views_Source::getMimeType($file); + $this->assertEqual($mime, $m[0]); + } + } +} \ No newline at end of file diff --git a/src/IDF/Views/Source.php b/src/IDF/Views/Source.php index 80a30c4..f967e97 100644 --- a/src/IDF/Views/Source.php +++ b/src/IDF/Views/Source.php @@ -101,8 +101,11 @@ class IDF_Views_Source return new Pluf_HTTP_Response_Redirect($url); } if ($request_file_info->type != 'tree') { - return new Pluf_HTTP_Response($git->getBlob($request_file_info->hash), - 'application/octet-stream'); + $info = self::getMimeType($request_file_info->file); + $rep = new Pluf_HTTP_Response($git->getBlob($request_file_info->hash), + $info[0]); + $rep->headers['Content-Disposition'] = 'attachment; filename="'.$info[1].'"'; + return $rep; } $bc = self::makeBreadCrumb($request->project, $commit, $request_file_info->file); $page_title = $bc.' - '.$title; @@ -198,6 +201,38 @@ class IDF_Views_Source $rep->headers['Content-Disposition'] = 'attachment; filename="'.$base.'.zip"'; return $rep; } + + /** + * Find the mime type of a file. + * + * Use /etc/mime.types to find the type. + * + * @param string Filename/Filepath + * @param string Path to the mime types database ('/etc/mime.types') + * @param array Mime type found or 'application/octet-stream' and basename + */ + public static function getMimeType($file, $src='/etc/mime.types') + { + $mimes = preg_split("/\015\012|\015|\012/", file_get_contents($src)); + $info = pathinfo($file); + if (isset($info['extension'])) { + foreach ($mimes as $mime) { + if ('#' != substr($mime, 0, 1)) { + $elts = preg_split('/ |\t/', $mime, -1, PREG_SPLIT_NO_EMPTY); + if (in_array($info['extension'], $elts)) { + return array($elts[0], $info['basename']); + } + } + } + } else { + // we consider that if no extension and base name is all + // uppercase, then we have a text file. + if ($info['basename'] == strtoupper($info['basename'])) { + return array('text/plain', $info['basename']); + } + } + return array('application/octet-stream', $info['basename']); + } } function IDF_Views_Source_PrettySize($size)