1
0

files.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Clark Tomlinson <fallen013@gmail.com>
  9. * @author Frank Karlitschek <frank@karlitschek.de>
  10. * @author Jakob Sack <mail@jakobsack.de>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  13. * @author Ko- <k.stoffelen@cs.ru.nl>
  14. * @author Lukas Reschke <lukas@statuscode.ch>
  15. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  16. * @author Nicolai Ehemann <en@enlightened.de>
  17. * @author noveens <noveen.sachdeva@research.iiit.ac.in>
  18. * @author Piotr Filiciak <piotr@filiciak.pl>
  19. * @author Robin Appelman <robin@icewind.nl>
  20. * @author Robin McCorkell <robin@mccorkell.me.uk>
  21. * @author Thibaut GRIDEL <tgridel@free.fr>
  22. * @author Thomas Müller <thomas.mueller@tmit.eu>
  23. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  24. * @author Vincent Petry <pvince81@owncloud.com>
  25. *
  26. * @license AGPL-3.0
  27. *
  28. * This code is free software: you can redistribute it and/or modify
  29. * it under the terms of the GNU Affero General Public License, version 3,
  30. * as published by the Free Software Foundation.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU Affero General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU Affero General Public License, version 3,
  38. * along with this program. If not, see <http://www.gnu.org/licenses/>
  39. *
  40. */
  41. use OC\Files\View;
  42. use OC\Streamer;
  43. use OCP\ILogger;
  44. use OCP\Lock\ILockingProvider;
  45. /**
  46. * Class for file server access
  47. *
  48. */
  49. class OC_Files {
  50. const FILE = 1;
  51. const ZIP_FILES = 2;
  52. const ZIP_DIR = 3;
  53. const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
  54. private static $multipartBoundary = '';
  55. /**
  56. * @return string
  57. */
  58. private static function getBoundary() {
  59. if (empty(self::$multipartBoundary)) {
  60. self::$multipartBoundary = md5(mt_rand());
  61. }
  62. return self::$multipartBoundary;
  63. }
  64. /**
  65. * @param string $filename
  66. * @param string $name
  67. * @param array $rangeArray ('from'=>int,'to'=>int), ...
  68. */
  69. private static function sendHeaders($filename, $name, array $rangeArray) {
  70. OC_Response::setContentDispositionHeader($name, 'attachment');
  71. header('Content-Transfer-Encoding: binary', true);
  72. header('Pragma: public');// enable caching in IE
  73. header('Expires: 0');
  74. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  75. $fileSize = \OC\Files\Filesystem::filesize($filename);
  76. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  77. if ($fileSize > -1) {
  78. if (!empty($rangeArray)) {
  79. http_response_code(206);
  80. header('Accept-Ranges: bytes', true);
  81. if (count($rangeArray) > 1) {
  82. $type = 'multipart/byteranges; boundary='.self::getBoundary();
  83. // no Content-Length header here
  84. }
  85. else {
  86. header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
  87. OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
  88. }
  89. }
  90. else {
  91. OC_Response::setContentLengthHeader($fileSize);
  92. }
  93. }
  94. header('Content-Type: '.$type, true);
  95. }
  96. /**
  97. * return the content of a file or return a zip file containing multiple files
  98. *
  99. * @param string $dir
  100. * @param string $files ; separated list of files to download
  101. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  102. */
  103. public static function get($dir, $files, $params = null) {
  104. $view = \OC\Files\Filesystem::getView();
  105. $getType = self::FILE;
  106. $filename = $dir;
  107. try {
  108. if (is_array($files) && count($files) === 1) {
  109. $files = $files[0];
  110. }
  111. if (!is_array($files)) {
  112. $filename = $dir . '/' . $files;
  113. if (!$view->is_dir($filename)) {
  114. self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
  115. return;
  116. }
  117. }
  118. $name = 'download';
  119. if (is_array($files)) {
  120. $getType = self::ZIP_FILES;
  121. $basename = basename($dir);
  122. if ($basename) {
  123. $name = $basename;
  124. }
  125. $filename = $dir . '/' . $name;
  126. } else {
  127. $filename = $dir . '/' . $files;
  128. $getType = self::ZIP_DIR;
  129. // downloading root ?
  130. if ($files !== '') {
  131. $name = $files;
  132. }
  133. }
  134. self::lockFiles($view, $dir, $files);
  135. /* Calculate filesize and number of files */
  136. if ($getType === self::ZIP_FILES) {
  137. $fileInfos = array();
  138. $fileSize = 0;
  139. foreach ($files as $file) {
  140. $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
  141. $fileSize += $fileInfo->getSize();
  142. $fileInfos[] = $fileInfo;
  143. }
  144. $numberOfFiles = self::getNumberOfFiles($fileInfos);
  145. } elseif ($getType === self::ZIP_DIR) {
  146. $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
  147. $fileSize = $fileInfo->getSize();
  148. $numberOfFiles = self::getNumberOfFiles(array($fileInfo));
  149. }
  150. $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
  151. OC_Util::obEnd();
  152. $streamer->sendHeaders($name);
  153. $executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
  154. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  155. @set_time_limit(0);
  156. }
  157. ignore_user_abort(true);
  158. if ($getType === self::ZIP_FILES) {
  159. foreach ($files as $file) {
  160. $file = $dir . '/' . $file;
  161. if (\OC\Files\Filesystem::is_file($file)) {
  162. $fileSize = \OC\Files\Filesystem::filesize($file);
  163. $fileTime = \OC\Files\Filesystem::filemtime($file);
  164. $fh = \OC\Files\Filesystem::fopen($file, 'r');
  165. $streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
  166. fclose($fh);
  167. } elseif (\OC\Files\Filesystem::is_dir($file)) {
  168. $streamer->addDirRecursive($file);
  169. }
  170. }
  171. } elseif ($getType === self::ZIP_DIR) {
  172. $file = $dir . '/' . $files;
  173. $streamer->addDirRecursive($file);
  174. }
  175. $streamer->finalize();
  176. set_time_limit($executionTime);
  177. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  178. } catch (\OCP\Lock\LockedException $ex) {
  179. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  180. OC::$server->getLogger()->logException($ex);
  181. $l = \OC::$server->getL10N('core');
  182. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  183. \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
  184. } catch (\OCP\Files\ForbiddenException $ex) {
  185. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  186. OC::$server->getLogger()->logException($ex);
  187. $l = \OC::$server->getL10N('core');
  188. \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage(), 200);
  189. } catch (\Exception $ex) {
  190. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  191. OC::$server->getLogger()->logException($ex);
  192. $l = \OC::$server->getL10N('core');
  193. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  194. \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint, 200);
  195. }
  196. }
  197. /**
  198. * @param string $rangeHeaderPos
  199. * @param int $fileSize
  200. * @return array $rangeArray ('from'=>int,'to'=>int), ...
  201. */
  202. private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
  203. $rArray=explode(',', $rangeHeaderPos);
  204. $minOffset = 0;
  205. $ind = 0;
  206. $rangeArray = array();
  207. foreach ($rArray as $value) {
  208. $ranges = explode('-', $value);
  209. if (is_numeric($ranges[0])) {
  210. if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
  211. $ranges[0] = $minOffset;
  212. }
  213. if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
  214. $ind--;
  215. $ranges[0] = $rangeArray[$ind]['from'];
  216. }
  217. }
  218. if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
  219. // case: x-x
  220. if ($ranges[1] >= $fileSize) {
  221. $ranges[1] = $fileSize-1;
  222. }
  223. $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
  224. $minOffset = $ranges[1] + 1;
  225. if ($minOffset >= $fileSize) {
  226. break;
  227. }
  228. }
  229. elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
  230. // case: x-
  231. $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
  232. break;
  233. }
  234. elseif (is_numeric($ranges[1])) {
  235. // case: -x
  236. if ($ranges[1] > $fileSize) {
  237. $ranges[1] = $fileSize;
  238. }
  239. $rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
  240. break;
  241. }
  242. }
  243. return $rangeArray;
  244. }
  245. /**
  246. * @param View $view
  247. * @param string $name
  248. * @param string $dir
  249. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  250. */
  251. private static function getSingleFile($view, $dir, $name, $params) {
  252. $filename = $dir . '/' . $name;
  253. OC_Util::obEnd();
  254. $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
  255. $rangeArray = array();
  256. if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
  257. $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6),
  258. \OC\Files\Filesystem::filesize($filename));
  259. }
  260. if (\OC\Files\Filesystem::isReadable($filename)) {
  261. self::sendHeaders($filename, $name, $rangeArray);
  262. } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
  263. http_response_code(404);
  264. $tmpl = new OC_Template('', '404', 'guest');
  265. $tmpl->printPage();
  266. exit();
  267. } else {
  268. http_response_code(403);
  269. die('403 Forbidden');
  270. }
  271. if (isset($params['head']) && $params['head']) {
  272. return;
  273. }
  274. if (!empty($rangeArray)) {
  275. try {
  276. if (count($rangeArray) == 1) {
  277. $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
  278. }
  279. else {
  280. // check if file is seekable (if not throw UnseekableException)
  281. // we have to check it before body contents
  282. $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
  283. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  284. foreach ($rangeArray as $range) {
  285. echo "\r\n--".self::getBoundary()."\r\n".
  286. "Content-type: ".$type."\r\n".
  287. "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
  288. $view->readfilePart($filename, $range['from'], $range['to']);
  289. }
  290. echo "\r\n--".self::getBoundary()."--\r\n";
  291. }
  292. } catch (\OCP\Files\UnseekableException $ex) {
  293. // file is unseekable
  294. header_remove('Accept-Ranges');
  295. header_remove('Content-Range');
  296. http_response_code(200);
  297. self::sendHeaders($filename, $name, array());
  298. $view->readfile($filename);
  299. }
  300. }
  301. else {
  302. $view->readfile($filename);
  303. }
  304. }
  305. /**
  306. * Returns the total (recursive) number of files and folders in the given
  307. * FileInfos.
  308. *
  309. * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
  310. * @return int the total number of files and folders
  311. */
  312. private static function getNumberOfFiles($fileInfos) {
  313. $numberOfFiles = 0;
  314. $view = new View();
  315. while ($fileInfo = array_pop($fileInfos)) {
  316. $numberOfFiles++;
  317. if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
  318. $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
  319. }
  320. }
  321. return $numberOfFiles;
  322. }
  323. /**
  324. * @param View $view
  325. * @param string $dir
  326. * @param string[]|string $files
  327. */
  328. public static function lockFiles($view, $dir, $files) {
  329. if (!is_array($files)) {
  330. $file = $dir . '/' . $files;
  331. $files = [$file];
  332. }
  333. foreach ($files as $file) {
  334. $file = $dir . '/' . $file;
  335. $view->lockFile($file, ILockingProvider::LOCK_SHARED);
  336. if ($view->is_dir($file)) {
  337. $contents = $view->getDirectoryContent($file);
  338. $contents = array_map(function($fileInfo) use ($file) {
  339. /** @var \OCP\Files\FileInfo $fileInfo */
  340. return $file . '/' . $fileInfo->getName();
  341. }, $contents);
  342. self::lockFiles($view, $dir, $contents);
  343. }
  344. }
  345. }
  346. /**
  347. * @param string $dir
  348. * @param $files
  349. * @param integer $getType
  350. * @param View $view
  351. * @param string $filename
  352. */
  353. private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
  354. if ($getType === self::FILE) {
  355. $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
  356. }
  357. if ($getType === self::ZIP_FILES) {
  358. foreach ($files as $file) {
  359. $file = $dir . '/' . $file;
  360. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  361. }
  362. }
  363. if ($getType === self::ZIP_DIR) {
  364. $file = $dir . '/' . $files;
  365. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  366. }
  367. }
  368. }