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

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