files.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. }
  105. OC_Util::obEnd();
  106. if ($zip or \OC\Files\Filesystem::isReadable($filename)) {
  107. if ( preg_match( "/MSIE/", $_SERVER["HTTP_USER_AGENT"] ) ) {
  108. header( 'Content-Disposition: attachment; filename="' . rawurlencode($name) . '"' );
  109. } else {
  110. header( 'Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($name)
  111. . '; filename="' . rawurlencode($name) . '"' );
  112. }
  113. header('Content-Transfer-Encoding: binary');
  114. OC_Response::disableCaching();
  115. if ($zip) {
  116. ini_set('zlib.output_compression', 'off');
  117. header('Content-Type: application/zip');
  118. header('Content-Length: ' . filesize($filename));
  119. self::addSendfileHeader($filename);
  120. }else{
  121. $filesize = \OC\Files\Filesystem::filesize($filename);
  122. header('Content-Type: '.\OC\Files\Filesystem::getMimeType($filename));
  123. if ($filesize > -1) {
  124. header("Content-Length: ".$filesize);
  125. }
  126. if ($xsendfile) {
  127. list($storage) = \OC\Files\Filesystem::resolvePath(\OC\Files\Filesystem::getView()->getAbsolutePath($filename));
  128. if ($storage instanceof \OC\Files\Storage\Local) {
  129. self::addSendfileHeader(\OC\Files\Filesystem::getLocalFile($filename));
  130. }
  131. }
  132. }
  133. } elseif ($zip or !\OC\Files\Filesystem::file_exists($filename)) {
  134. header("HTTP/1.0 404 Not Found");
  135. $tmpl = new OC_Template('', '404', 'guest');
  136. $tmpl->assign('file', $name);
  137. $tmpl->printPage();
  138. } else {
  139. header("HTTP/1.0 403 Forbidden");
  140. die('403 Forbidden');
  141. }
  142. if($only_header) {
  143. return ;
  144. }
  145. if ($zip) {
  146. $handle = fopen($filename, 'r');
  147. if ($handle) {
  148. $chunkSize = 8 * 1024; // 1 MB chunks
  149. while (!feof($handle)) {
  150. echo fread($handle, $chunkSize);
  151. flush();
  152. }
  153. }
  154. if (!$xsendfile) {
  155. unlink($filename);
  156. }
  157. }else{
  158. \OC\Files\Filesystem::readfile($filename);
  159. }
  160. foreach (self::$tmpFiles as $tmpFile) {
  161. if (file_exists($tmpFile) and is_file($tmpFile)) {
  162. unlink($tmpFile);
  163. }
  164. }
  165. }
  166. private static function addSendfileHeader($filename) {
  167. if (isset($_SERVER['MOD_X_SENDFILE_ENABLED'])) {
  168. header("X-Sendfile: " . $filename);
  169. }
  170. if (isset($_SERVER['MOD_X_SENDFILE2_ENABLED'])) {
  171. if (isset($_SERVER['HTTP_RANGE']) &&
  172. preg_match("/^bytes=([0-9]+)-([0-9]*)$/", $_SERVER['HTTP_RANGE'], $range)) {
  173. $filelength = filesize($filename);
  174. if ($range[2] == "") {
  175. $range[2] = $filelength - 1;
  176. }
  177. header("Content-Range: bytes $range[1]-$range[2]/" . $filelength);
  178. header("HTTP/1.1 206 Partial content");
  179. header("X-Sendfile2: " . str_replace(",", "%2c", rawurlencode($filename)) . " $range[1]-$range[2]");
  180. } else {
  181. header("X-Sendfile: " . $filename);
  182. }
  183. }
  184. if (isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) {
  185. header("X-Accel-Redirect: " . $filename);
  186. }
  187. }
  188. public static function zipAddDir($dir, $zip, $internalDir='') {
  189. $dirname=basename($dir);
  190. $zip->addEmptyDir($internalDir.$dirname);
  191. $internalDir.=$dirname.='/';
  192. $files=OC_Files::getDirectoryContent($dir);
  193. foreach($files as $file) {
  194. $filename=$file['name'];
  195. $file=$dir.'/'.$filename;
  196. if(\OC\Files\Filesystem::is_file($file)) {
  197. $tmpFile=\OC\Files\Filesystem::toTmpFile($file);
  198. OC_Files::$tmpFiles[]=$tmpFile;
  199. $zip->addFile($tmpFile, $internalDir.$filename);
  200. }elseif(\OC\Files\Filesystem::is_dir($file)) {
  201. self::zipAddDir($file, $zip, $internalDir);
  202. }
  203. }
  204. }
  205. /**
  206. * checks if the selected files are within the size constraint. If not, outputs an error page.
  207. *
  208. * @param dir $dir
  209. * @param files $files
  210. */
  211. static function validateZipDownload($dir, $files) {
  212. if (!OC_Config::getValue('allowZipDownload', true)) {
  213. $l = OC_L10N::get('lib');
  214. header("HTTP/1.0 409 Conflict");
  215. OC_Template::printErrorPage(
  216. $l->t('ZIP download is turned off.'),
  217. $l->t('Files need to be downloaded one by one.')
  218. . '<br/><a href="javascript:history.back()">' . $l->t('Back to Files') . '</a>'
  219. );
  220. exit;
  221. }
  222. $zipLimit = OC_Config::getValue('maxZipInputSize', OC_Helper::computerFileSize('800 MB'));
  223. if ($zipLimit > 0) {
  224. $totalsize = 0;
  225. if(!is_array($files)) {
  226. $files = array($files);
  227. }
  228. foreach ($files as $file) {
  229. $path = $dir . '/' . $file;
  230. if(\OC\Files\Filesystem::is_dir($path)) {
  231. foreach (\OC\Files\Filesystem::getDirectoryContent($path) as $i) {
  232. $totalsize += $i['size'];
  233. }
  234. } else {
  235. $totalsize += \OC\Files\Filesystem::filesize($path);
  236. }
  237. }
  238. if ($totalsize > $zipLimit) {
  239. $l = OC_L10N::get('lib');
  240. header("HTTP/1.0 409 Conflict");
  241. OC_Template::printErrorPage(
  242. $l->t('Selected files too large to generate zip file.'),
  243. $l->t('Please download the files separately in smaller chunks or kindly ask your administrator.')
  244. .'<br/><a href="javascript:history.back()">'
  245. . $l->t('Back to Files') . '</a>'
  246. );
  247. exit;
  248. }
  249. }
  250. }
  251. /**
  252. * set the maximum upload size limit for apache hosts using .htaccess
  253. *
  254. * @param int size filesisze in bytes
  255. * @return false on failure, size on success
  256. */
  257. static function setUploadLimit($size) {
  258. //don't allow user to break his config -- upper boundary
  259. if ($size > PHP_INT_MAX) {
  260. //max size is always 1 byte lower than computerFileSize returns
  261. if ($size > PHP_INT_MAX + 1)
  262. return false;
  263. $size -= 1;
  264. } else {
  265. $size = OC_Helper::humanFileSize($size);
  266. $size = substr($size, 0, -1); //strip the B
  267. $size = str_replace(' ', '', $size); //remove the space between the size and the postfix
  268. }
  269. //don't allow user to break his config -- broken or malicious size input
  270. if (intval($size) == 0) {
  271. return false;
  272. }
  273. $htaccess = @file_get_contents(OC::$SERVERROOT . '/.htaccess'); //supress errors in case we don't have permissions for
  274. if (!$htaccess) {
  275. return false;
  276. }
  277. $phpValueKeys = array(
  278. 'upload_max_filesize',
  279. 'post_max_size'
  280. );
  281. foreach ($phpValueKeys as $key) {
  282. $pattern = '/php_value ' . $key . ' (\S)*/';
  283. $setting = 'php_value ' . $key . ' ' . $size;
  284. $hasReplaced = 0;
  285. $content = preg_replace($pattern, $setting, $htaccess, 1, $hasReplaced);
  286. if ($content !== null) {
  287. $htaccess = $content;
  288. }
  289. if ($hasReplaced == 0) {
  290. $htaccess .= "\n" . $setting;
  291. }
  292. }
  293. //check for write permissions
  294. if (is_writable(OC::$SERVERROOT . '/.htaccess')) {
  295. file_put_contents(OC::$SERVERROOT . '/.htaccess', $htaccess);
  296. return OC_Helper::computerFileSize($size);
  297. } else {
  298. OC_Log::write('files',
  299. 'Can\'t write upload limit to ' . OC::$SERVERROOT . '/.htaccess. Please check the file permissions',
  300. OC_Log::WARN);
  301. }
  302. return false;
  303. }
  304. }