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 14KB

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