files.php 14 KB

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