files.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Frank Karlitschek
  6. * @copyright 2012 Frank Karlitschek frank@owncloud.org
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  10. * License as published by the Free Software Foundation; either
  11. * version 3 of the License, or any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public
  19. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * Class for fileserver access
  24. *
  25. */
  26. class OC_Files {
  27. static $tmpFiles = array();
  28. static public function getFileInfo($path, $includeMountPoints = true){
  29. return \OC\Files\Filesystem::getFileInfo($path, $includeMountPoints);
  30. }
  31. static public function getDirectoryContent($path){
  32. return \OC\Files\Filesystem::getDirectoryContent($path);
  33. }
  34. /**
  35. * return the content of a file or return a zip file containing multiple files
  36. *
  37. * @param string $dir
  38. * @param string $file ; separated list of files to download
  39. * @param boolean $only_header ; boolean to only send header of the request
  40. */
  41. public static function get($dir, $files, $only_header = false) {
  42. $xsendfile = false;
  43. if (isset($_SERVER['MOD_X_SENDFILE_ENABLED']) ||
  44. isset($_SERVER['MOD_X_SENDFILE2_ENABLED']) ||
  45. isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) {
  46. $xsendfile = true;
  47. }
  48. if (is_array($files) && count($files) == 1) {
  49. $files = $files[0];
  50. }
  51. if (is_array($files)) {
  52. self::validateZipDownload($dir, $files);
  53. $executionTime = intval(ini_get('max_execution_time'));
  54. set_time_limit(0);
  55. $zip = new ZipArchive();
  56. $filename = OC_Helper::tmpFile('.zip');
  57. if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)!==true) {
  58. $l = OC_L10N::get('lib');
  59. throw new Exception($l->t('cannot open "%s"', array($filename)));
  60. }
  61. foreach ($files as $file) {
  62. $file = $dir . '/' . $file;
  63. if (\OC\Files\Filesystem::is_file($file)) {
  64. $tmpFile = \OC\Files\Filesystem::toTmpFile($file);
  65. self::$tmpFiles[] = $tmpFile;
  66. $zip->addFile($tmpFile, basename($file));
  67. } elseif (\OC\Files\Filesystem::is_dir($file)) {
  68. self::zipAddDir($file, $zip);
  69. }
  70. }
  71. $zip->close();
  72. if ($xsendfile) {
  73. $filename = OC_Helper::moveToNoClean($filename);
  74. }
  75. $basename = basename($dir);
  76. if ($basename) {
  77. $name = $basename . '.zip';
  78. } else {
  79. $name = 'owncloud.zip';
  80. }
  81. set_time_limit($executionTime);
  82. } elseif (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) {
  83. self::validateZipDownload($dir, $files);
  84. $executionTime = intval(ini_get('max_execution_time'));
  85. set_time_limit(0);
  86. $zip = new ZipArchive();
  87. $filename = OC_Helper::tmpFile('.zip');
  88. if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)!==true) {
  89. $l = OC_L10N::get('lib');
  90. throw new Exception($l->t('cannot open "%s"', array($filename)));
  91. }
  92. $file = $dir . '/' . $files;
  93. self::zipAddDir($file, $zip);
  94. $zip->close();
  95. if ($xsendfile) {
  96. $filename = OC_Helper::moveToNoClean($filename);
  97. }
  98. $name = $files . '.zip';
  99. set_time_limit($executionTime);
  100. } else {
  101. $zip = false;
  102. $filename = $dir . '/' . $files;
  103. $name = $files;
  104. if ($xsendfile && OC_App::isEnabled('files_encryption')) {
  105. $xsendfile = false;
  106. }
  107. }
  108. OC_Util::obEnd();
  109. if ($zip or \OC\Files\Filesystem::isReadable($filename)) {
  110. if ( preg_match( "/MSIE/", $_SERVER["HTTP_USER_AGENT"] ) ) {
  111. header( 'Content-Disposition: attachment; filename="' . rawurlencode($name) . '"' );
  112. } else {
  113. header( 'Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($name)
  114. . '; filename="' . rawurlencode($name) . '"' );
  115. }
  116. header('Content-Transfer-Encoding: binary');
  117. OC_Response::disableCaching();
  118. if ($zip) {
  119. ini_set('zlib.output_compression', 'off');
  120. header('Content-Type: application/zip');
  121. header('Content-Length: ' . filesize($filename));
  122. self::addSendfileHeader($filename);
  123. }else{
  124. $filesize = \OC\Files\Filesystem::filesize($filename);
  125. header('Content-Type: '.\OC\Files\Filesystem::getMimeType($filename));
  126. if ($filesize > -1) {
  127. header("Content-Length: ".$filesize);
  128. }
  129. if ($xsendfile) {
  130. list($storage) = \OC\Files\Filesystem::resolvePath(\OC\Files\Filesystem::getView()->getAbsolutePath($filename));
  131. if ($storage instanceof \OC\Files\Storage\Local) {
  132. self::addSendfileHeader(\OC\Files\Filesystem::getLocalFile($filename));
  133. }
  134. }
  135. }
  136. } elseif ($zip or !\OC\Files\Filesystem::file_exists($filename)) {
  137. header("HTTP/1.0 404 Not Found");
  138. $tmpl = new OC_Template('', '404', 'guest');
  139. $tmpl->assign('file', $name);
  140. $tmpl->printPage();
  141. } else {
  142. header("HTTP/1.0 403 Forbidden");
  143. die('403 Forbidden');
  144. }
  145. if($only_header) {
  146. return ;
  147. }
  148. if ($zip) {
  149. $handle = fopen($filename, 'r');
  150. if ($handle) {
  151. $chunkSize = 8 * 1024; // 1 MB chunks
  152. while (!feof($handle)) {
  153. echo fread($handle, $chunkSize);
  154. flush();
  155. }
  156. }
  157. if (!$xsendfile) {
  158. unlink($filename);
  159. }
  160. }else{
  161. \OC\Files\Filesystem::readfile($filename);
  162. }
  163. foreach (self::$tmpFiles as $tmpFile) {
  164. if (file_exists($tmpFile) and is_file($tmpFile)) {
  165. unlink($tmpFile);
  166. }
  167. }
  168. }
  169. private static function addSendfileHeader($filename) {
  170. if (isset($_SERVER['MOD_X_SENDFILE_ENABLED'])) {
  171. header("X-Sendfile: " . $filename);
  172. }
  173. if (isset($_SERVER['MOD_X_SENDFILE2_ENABLED'])) {
  174. if (isset($_SERVER['HTTP_RANGE']) &&
  175. preg_match("/^bytes=([0-9]+)-([0-9]*)$/", $_SERVER['HTTP_RANGE'], $range)) {
  176. $filelength = filesize($filename);
  177. if ($range[2] == "") {
  178. $range[2] = $filelength - 1;
  179. }
  180. header("Content-Range: bytes $range[1]-$range[2]/" . $filelength);
  181. header("HTTP/1.1 206 Partial content");
  182. header("X-Sendfile2: " . str_replace(",", "%2c", rawurlencode($filename)) . " $range[1]-$range[2]");
  183. } else {
  184. header("X-Sendfile: " . $filename);
  185. }
  186. }
  187. if (isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) {
  188. header("X-Accel-Redirect: " . $filename);
  189. }
  190. }
  191. public static function zipAddDir($dir, $zip, $internalDir='') {
  192. $dirname=basename($dir);
  193. $zip->addEmptyDir($internalDir.$dirname);
  194. $internalDir.=$dirname.='/';
  195. $files=OC_Files::getDirectoryContent($dir);
  196. foreach($files as $file) {
  197. $filename=$file['name'];
  198. $file=$dir.'/'.$filename;
  199. if(\OC\Files\Filesystem::is_file($file)) {
  200. $tmpFile=\OC\Files\Filesystem::toTmpFile($file);
  201. OC_Files::$tmpFiles[]=$tmpFile;
  202. $zip->addFile($tmpFile, $internalDir.$filename);
  203. }elseif(\OC\Files\Filesystem::is_dir($file)) {
  204. self::zipAddDir($file, $zip, $internalDir);
  205. }
  206. }
  207. }
  208. /**
  209. * checks if the selected files are within the size constraint. If not, outputs an error page.
  210. *
  211. * @param dir $dir
  212. * @param files $files
  213. */
  214. static function validateZipDownload($dir, $files) {
  215. if (!OC_Config::getValue('allowZipDownload', true)) {
  216. $l = OC_L10N::get('lib');
  217. header("HTTP/1.0 409 Conflict");
  218. OC_Template::printErrorPage(
  219. $l->t('ZIP download is turned off.'),
  220. $l->t('Files need to be downloaded one by one.')
  221. . '<br/><a href="javascript:history.back()">' . $l->t('Back to Files') . '</a>'
  222. );
  223. exit;
  224. }
  225. $zipLimit = OC_Config::getValue('maxZipInputSize', OC_Helper::computerFileSize('800 MB'));
  226. if ($zipLimit > 0) {
  227. $totalsize = 0;
  228. if(!is_array($files)) {
  229. $files = array($files);
  230. }
  231. foreach ($files as $file) {
  232. $path = $dir . '/' . $file;
  233. if(\OC\Files\Filesystem::is_dir($path)) {
  234. foreach (\OC\Files\Filesystem::getDirectoryContent($path) as $i) {
  235. $totalsize += $i['size'];
  236. }
  237. } else {
  238. $totalsize += \OC\Files\Filesystem::filesize($path);
  239. }
  240. }
  241. if ($totalsize > $zipLimit) {
  242. $l = OC_L10N::get('lib');
  243. header("HTTP/1.0 409 Conflict");
  244. OC_Template::printErrorPage(
  245. $l->t('Selected files too large to generate zip file.'),
  246. $l->t('Please download the files separately in smaller chunks or kindly ask your administrator.')
  247. .'<br/><a href="javascript:history.back()">'
  248. . $l->t('Back to Files') . '</a>'
  249. );
  250. exit;
  251. }
  252. }
  253. }
  254. /**
  255. * set the maximum upload size limit for apache hosts using .htaccess
  256. *
  257. * @param int size filesisze in bytes
  258. * @return false on failure, size on success
  259. */
  260. static function setUploadLimit($size) {
  261. //don't allow user to break his config -- upper boundary
  262. if ($size > PHP_INT_MAX) {
  263. //max size is always 1 byte lower than computerFileSize returns
  264. if ($size > PHP_INT_MAX + 1)
  265. return false;
  266. $size -= 1;
  267. } else {
  268. $size = OC_Helper::humanFileSize($size);
  269. $size = substr($size, 0, -1); //strip the B
  270. $size = str_replace(' ', '', $size); //remove the space between the size and the postfix
  271. }
  272. //don't allow user to break his config -- broken or malicious size input
  273. if (intval($size) == 0) {
  274. return false;
  275. }
  276. $htaccess = @file_get_contents(OC::$SERVERROOT . '/.htaccess'); //supress errors in case we don't have permissions for
  277. if (!$htaccess) {
  278. return false;
  279. }
  280. $phpValueKeys = array(
  281. 'upload_max_filesize',
  282. 'post_max_size'
  283. );
  284. foreach ($phpValueKeys as $key) {
  285. $pattern = '/php_value ' . $key . ' (\S)*/';
  286. $setting = 'php_value ' . $key . ' ' . $size;
  287. $hasReplaced = 0;
  288. $content = preg_replace($pattern, $setting, $htaccess, 1, $hasReplaced);
  289. if ($content !== null) {
  290. $htaccess = $content;
  291. }
  292. if ($hasReplaced == 0) {
  293. $htaccess .= "\n" . $setting;
  294. }
  295. }
  296. //check for write permissions
  297. if (is_writable(OC::$SERVERROOT . '/.htaccess')) {
  298. file_put_contents(OC::$SERVERROOT . '/.htaccess', $htaccess);
  299. return OC_Helper::computerFileSize($size);
  300. } else {
  301. OC_Log::write('files',
  302. 'Can\'t write upload limit to ' . OC::$SERVERROOT . '/.htaccess. Please check the file permissions',
  303. OC_Log::WARN);
  304. }
  305. return false;
  306. }
  307. }