files.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. /**
  29. * get the content of a directory
  30. * @param dir $directory path under datadirectory
  31. */
  32. public static function getDirectoryContent($directory, $mimetype_filter = ''){
  33. $files=OC_FileCache::getFolderContent($directory, false, $mimetype_filter);
  34. foreach($files as &$file){
  35. $file['directory']=$directory;
  36. $file['type']=($file['mimetype']=='httpd/unix-directory')?'dir':'file';
  37. }
  38. usort($files, "fileCmp");//TODO: remove this once ajax is merged
  39. return $files;
  40. }
  41. /**
  42. * return the content of a file or return a zip file containning multiply files
  43. *
  44. * @param dir $dir
  45. * @param file $file ; seperated list of files to download
  46. * @param boolean $only_header ; boolean to only send header of the request
  47. */
  48. public static function get($dir,$files, $only_header = false){
  49. if(strpos($files,';')){
  50. $files=explode(';',$files);
  51. }
  52. if(is_array($files)){
  53. self::validateZipDownload($dir,$files);
  54. $executionTime = intval(ini_get('max_execution_time'));
  55. set_time_limit(0);
  56. $zip = new ZipArchive();
  57. $filename = OC_Helper::tmpFile('.zip');
  58. if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)!==TRUE) {
  59. exit("cannot open <$filename>\n");
  60. }
  61. foreach($files as $file){
  62. $file=$dir.'/'.$file;
  63. if(OC_Filesystem::is_file($file)){
  64. $tmpFile=OC_Filesystem::toTmpFile($file);
  65. self::$tmpFiles[]=$tmpFile;
  66. $zip->addFile($tmpFile,basename($file));
  67. }elseif(OC_Filesystem::is_dir($file)){
  68. self::zipAddDir($file,$zip);
  69. }
  70. }
  71. $zip->close();
  72. set_time_limit($executionTime);
  73. }elseif(OC_Filesystem::is_dir($dir.'/'.$files)){
  74. self::validateZipDownload($dir,$files);
  75. $executionTime = intval(ini_get('max_execution_time'));
  76. set_time_limit(0);
  77. $zip = new ZipArchive();
  78. $filename = OC_Helper::tmpFile('.zip');
  79. if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)!==TRUE) {
  80. exit("cannot open <$filename>\n");
  81. }
  82. $file=$dir.'/'.$files;
  83. self::zipAddDir($file,$zip);
  84. $zip->close();
  85. set_time_limit($executionTime);
  86. }else{
  87. $zip=false;
  88. $filename=$dir.'/'.$files;
  89. }
  90. @ob_end_clean();
  91. if($zip or OC_Filesystem::is_readable($filename)){
  92. header('Content-Disposition: attachment; filename="'.basename($filename).'"');
  93. header('Content-Transfer-Encoding: binary');
  94. OC_Response::disableCaching();
  95. if($zip){
  96. ini_set('zlib.output_compression', 'off');
  97. header('Content-Type: application/zip');
  98. header('Content-Length: ' . filesize($filename));
  99. }else{
  100. $fileData=OC_FileCache::get($filename);
  101. header('Content-Type: ' . $fileData['mimetype']);
  102. }
  103. }elseif($zip or !OC_Filesystem::file_exists($filename)){
  104. header("HTTP/1.0 404 Not Found");
  105. $tmpl = new OC_Template( '', '404', 'guest' );
  106. $tmpl->assign('file',$filename);
  107. $tmpl->printPage();
  108. }else{
  109. header("HTTP/1.0 403 Forbidden");
  110. die('403 Forbidden');
  111. }
  112. if($only_header){
  113. if(!$zip)
  114. header("Content-Length: ".OC_Filesystem::filesize($filename));
  115. return ;
  116. }
  117. if($zip){
  118. $handle=fopen($filename,'r');
  119. if ($handle) {
  120. $chunkSize = 8*1024;// 1 MB chunks
  121. while (!feof($handle)) {
  122. echo fread($handle, $chunkSize);
  123. flush();
  124. }
  125. }
  126. unlink($filename);
  127. }else{
  128. OC_Filesystem::readfile($filename);
  129. }
  130. foreach(self::$tmpFiles as $tmpFile){
  131. if(file_exists($tmpFile) and is_file($tmpFile)){
  132. unlink($tmpFile);
  133. }
  134. }
  135. }
  136. public static function zipAddDir($dir,$zip,$internalDir=''){
  137. $dirname=basename($dir);
  138. $zip->addEmptyDir($internalDir.$dirname);
  139. $internalDir.=$dirname.='/';
  140. $files=OC_Files::getdirectorycontent($dir);
  141. foreach($files as $file){
  142. $filename=$file['name'];
  143. $file=$dir.'/'.$filename;
  144. if(OC_Filesystem::is_file($file)){
  145. $tmpFile=OC_Filesystem::toTmpFile($file);
  146. OC_Files::$tmpFiles[]=$tmpFile;
  147. $zip->addFile($tmpFile,$internalDir.$filename);
  148. }elseif(OC_Filesystem::is_dir($file)){
  149. self::zipAddDir($file,$zip,$internalDir);
  150. }
  151. }
  152. }
  153. /**
  154. * move a file or folder
  155. *
  156. * @param dir $sourceDir
  157. * @param file $source
  158. * @param dir $targetDir
  159. * @param file $target
  160. */
  161. public static function move($sourceDir,$source,$targetDir,$target){
  162. if(OC_User::isLoggedIn() && ($sourceDir != '' || $source != 'Shared')){
  163. $targetFile=self::normalizePath($targetDir.'/'.$target);
  164. $sourceFile=self::normalizePath($sourceDir.'/'.$source);
  165. return OC_Filesystem::rename($sourceFile,$targetFile);
  166. }
  167. }
  168. /**
  169. * copy a file or folder
  170. *
  171. * @param dir $sourceDir
  172. * @param file $source
  173. * @param dir $targetDir
  174. * @param file $target
  175. */
  176. public static function copy($sourceDir,$source,$targetDir,$target){
  177. if(OC_User::isLoggedIn()){
  178. $targetFile=$targetDir.'/'.$target;
  179. $sourceFile=$sourceDir.'/'.$source;
  180. return OC_Filesystem::copy($sourceFile,$targetFile);
  181. }
  182. }
  183. /**
  184. * create a new file or folder
  185. *
  186. * @param dir $dir
  187. * @param file $name
  188. * @param type $type
  189. */
  190. public static function newFile($dir,$name,$type){
  191. if(OC_User::isLoggedIn()){
  192. $file=$dir.'/'.$name;
  193. if($type=='dir'){
  194. return OC_Filesystem::mkdir($file);
  195. }elseif($type=='file'){
  196. $fileHandle=OC_Filesystem::fopen($file, 'w');
  197. if($fileHandle){
  198. fclose($fileHandle);
  199. return true;
  200. }else{
  201. return false;
  202. }
  203. }
  204. }
  205. }
  206. /**
  207. * deletes a file or folder
  208. *
  209. * @param dir $dir
  210. * @param file $name
  211. */
  212. public static function delete($dir,$file){
  213. if(OC_User::isLoggedIn() && ($dir!= '' || $file != 'Shared')) {
  214. $file=$dir.'/'.$file;
  215. return OC_Filesystem::unlink($file);
  216. }
  217. }
  218. /**
  219. * checks if the selected files are within the size constraint. If not, outputs an error page.
  220. *
  221. * @param dir $dir
  222. * @param files $files
  223. */
  224. static function validateZipDownload($dir, $files) {
  225. if(!OC_Config::getValue('allowZipDownload', true)) {
  226. $l = OC_L10N::get('files');
  227. header("HTTP/1.0 409 Conflict");
  228. $tmpl = new OC_Template( '', 'error', 'user' );
  229. $errors = array(
  230. array(
  231. 'error' => $l->t('ZIP download is turned off.'),
  232. 'hint' => $l->t('Files need to be downloaded one by one.') . '<br/><a href="javascript:history.back()">' . $l->t('Back to Files') . '</a>',
  233. )
  234. );
  235. $tmpl->assign('errors', $errors);
  236. $tmpl->printPage();
  237. exit;
  238. }
  239. $zipLimit = OC_Config::getValue('maxZipInputSize', OC_Helper::computerFileSize('800 MB'));
  240. if($zipLimit > 0) {
  241. $totalsize = 0;
  242. if(is_array($files)){
  243. foreach($files as $file){
  244. $totalsize += OC_Filesystem::filesize($dir.'/'.$file);
  245. }
  246. }else{
  247. $totalsize += OC_Filesystem::filesize($dir.'/'.$files);
  248. }
  249. if($totalsize > $zipLimit) {
  250. $l = OC_L10N::get('files');
  251. header("HTTP/1.0 409 Conflict");
  252. $tmpl = new OC_Template( '', 'error', 'user' );
  253. $errors = array(
  254. array(
  255. 'error' => $l->t('Selected files too large to generate zip file.'),
  256. 'hint' => 'Download the files in smaller chunks, seperately or kindly ask your administrator.<br/><a href="javascript:history.back()">' . $l->t('Back to Files') . '</a>',
  257. )
  258. );
  259. $tmpl->assign('errors', $errors);
  260. $tmpl->printPage();
  261. exit;
  262. }
  263. }
  264. }
  265. /**
  266. * try to detect the mime type of a file
  267. *
  268. * @param string path
  269. * @return string guessed mime type
  270. */
  271. static function getMimeType($path){
  272. return OC_Filesystem::getMimeType($path);
  273. }
  274. /**
  275. * get a file tree
  276. *
  277. * @param string path
  278. * @return array
  279. */
  280. static function getTree($path){
  281. return OC_Filesystem::getTree($path);
  282. }
  283. /**
  284. * pull a file from a remote server
  285. * @param string source
  286. * @param string token
  287. * @param string dir
  288. * @param string file
  289. * @return string guessed mime type
  290. */
  291. static function pull($source,$token,$dir,$file){
  292. $tmpfile=tempnam(get_temp_dir(),'remoteCloudFile');
  293. $fp=fopen($tmpfile,'w+');
  294. $url=$source.="/files/pull.php?token=$token";
  295. $ch=curl_init();
  296. curl_setopt($ch,CURLOPT_URL,$url);
  297. curl_setopt($ch, CURLOPT_FILE, $fp);
  298. curl_exec($ch);
  299. fclose($fp);
  300. $info=curl_getinfo($ch);
  301. $httpCode=$info['http_code'];
  302. curl_close($ch);
  303. if($httpCode==200 or $httpCode==0){
  304. OC_Filesystem::fromTmpFile($tmpfile,$dir.'/'.$file);
  305. return true;
  306. }else{
  307. return false;
  308. }
  309. }
  310. /**
  311. * set the maximum upload size limit for apache hosts using .htaccess
  312. * @param int size filesisze in bytes
  313. * @return false on failure, size on success
  314. */
  315. static function setUploadLimit($size){
  316. //don't allow user to break his config -- upper boundary
  317. if($size > PHP_INT_MAX) {
  318. //max size is always 1 byte lower than computerFileSize returns
  319. if($size > PHP_INT_MAX+1)
  320. return false;
  321. $size -=1;
  322. } else {
  323. $size=OC_Helper::humanFileSize($size);
  324. $size=substr($size,0,-1);//strip the B
  325. $size=str_replace(' ','',$size); //remove the space between the size and the postfix
  326. }
  327. //don't allow user to break his config -- broken or malicious size input
  328. if(intval($size) == 0) {
  329. return false;
  330. }
  331. $htaccess = @file_get_contents(OC::$SERVERROOT.'/.htaccess'); //supress errors in case we don't have permissions for
  332. if(!$htaccess) {
  333. return false;
  334. }
  335. $phpValueKeys = array(
  336. 'upload_max_filesize',
  337. 'post_max_size'
  338. );
  339. foreach($phpValueKeys as $key) {
  340. $pattern = '/php_value '.$key.' (\S)*/';
  341. $setting = 'php_value '.$key.' '.$size;
  342. $hasReplaced = 0;
  343. $content = preg_replace($pattern, $setting, $htaccess, 1, $hasReplaced);
  344. if($content !== NULL) {
  345. $htaccess = $content;
  346. }
  347. if($hasReplaced == 0) {
  348. $htaccess .= "\n" . $setting;
  349. }
  350. }
  351. //check for write permissions
  352. if(is_writable(OC::$SERVERROOT.'/.htaccess')) {
  353. file_put_contents(OC::$SERVERROOT.'/.htaccess', $htaccess);
  354. return OC_Helper::computerFileSize($size);
  355. } else { OC_Log::write('files','Can\'t write upload limit to '.OC::$SERVERROOT.'/.htaccess. Please check the file permissions',OC_Log::WARN); }
  356. return false;
  357. }
  358. /**
  359. * normalize a path, removing any double, add leading /, etc
  360. * @param string $path
  361. * @return string
  362. */
  363. static public function normalizePath($path){
  364. $path='/'.$path;
  365. $old='';
  366. while($old!=$path){//replace any multiplicity of slashes with a single one
  367. $old=$path;
  368. $path=str_replace('//','/',$path);
  369. }
  370. return $path;
  371. }
  372. }
  373. function fileCmp($a,$b){
  374. if($a['type']=='dir' and $b['type']!='dir'){
  375. return -1;
  376. }elseif($a['type']!='dir' and $b['type']=='dir'){
  377. return 1;
  378. }else{
  379. return strnatcasecmp($a['name'],$b['name']);
  380. }
  381. }