You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

files.php 9.8KB

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