files.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. @ob_end_clean();
  192. if($zip or OC_Filesystem::is_readable($filename)) {
  193. header('Content-Disposition: attachment; filename="'.basename($filename).'"');
  194. header('Content-Transfer-Encoding: binary');
  195. OC_Response::disableCaching();
  196. if($zip) {
  197. ini_set('zlib.output_compression', 'off');
  198. header('Content-Type: application/zip');
  199. header('Content-Length: ' . filesize($filename));
  200. self::addSendfileHeader($filename);
  201. }else{
  202. header('Content-Type: '.OC_Filesystem::getMimeType($filename));
  203. $storage = OC_Filesystem::getStorage($filename);
  204. if ($storage instanceof OC_Filestorage_Local) {
  205. self::addSendfileHeader(OC_Filesystem::getLocalFile($filename));
  206. }
  207. }
  208. }elseif($zip or !OC_Filesystem::file_exists($filename)) {
  209. header("HTTP/1.0 404 Not Found");
  210. $tmpl = new OC_Template( '', '404', 'guest' );
  211. $tmpl->assign('file', $filename);
  212. $tmpl->printPage();
  213. }else{
  214. header("HTTP/1.0 403 Forbidden");
  215. die('403 Forbidden');
  216. }
  217. if($only_header) {
  218. if(!$zip)
  219. header("Content-Length: ".OC_Filesystem::filesize($filename));
  220. return ;
  221. }
  222. if($zip) {
  223. $handle=fopen($filename, 'r');
  224. if ($handle) {
  225. $chunkSize = 8*1024;// 1 MB chunks
  226. while (!feof($handle)) {
  227. echo fread($handle, $chunkSize);
  228. flush();
  229. }
  230. }
  231. if (!$xsendfile) {
  232. unlink($filename);
  233. }
  234. }else{
  235. OC_Filesystem::readfile($filename);
  236. }
  237. foreach(self::$tmpFiles as $tmpFile) {
  238. if(file_exists($tmpFile) and is_file($tmpFile)) {
  239. unlink($tmpFile);
  240. }
  241. }
  242. }
  243. private static function addSendfileHeader($filename) {
  244. if (isset($_SERVER['MOD_X_SENDFILE_ENABLED'])) {
  245. header("X-Sendfile: " . $filename);
  246. }
  247. if (isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) {
  248. header("X-Accel-Redirect: " . $filename);
  249. }
  250. }
  251. public static function zipAddDir($dir, $zip, $internalDir='') {
  252. $dirname=basename($dir);
  253. $zip->addEmptyDir($internalDir.$dirname);
  254. $internalDir.=$dirname.='/';
  255. $files=OC_Files::getDirectoryContent($dir);
  256. foreach($files as $file) {
  257. $filename=$file['name'];
  258. $file=$dir.'/'.$filename;
  259. if(OC_Filesystem::is_file($file)) {
  260. $tmpFile=OC_Filesystem::toTmpFile($file);
  261. OC_Files::$tmpFiles[]=$tmpFile;
  262. $zip->addFile($tmpFile, $internalDir.$filename);
  263. }elseif(OC_Filesystem::is_dir($file)) {
  264. self::zipAddDir($file, $zip, $internalDir);
  265. }
  266. }
  267. }
  268. /**
  269. * move a file or folder
  270. *
  271. * @param dir $sourceDir
  272. * @param file $source
  273. * @param dir $targetDir
  274. * @param file $target
  275. */
  276. public static function move($sourceDir, $source, $targetDir, $target) {
  277. if(OC_User::isLoggedIn() && ($sourceDir != '' || $source != 'Shared')) {
  278. $targetFile=self::normalizePath($targetDir.'/'.$target);
  279. $sourceFile=self::normalizePath($sourceDir.'/'.$source);
  280. return OC_Filesystem::rename($sourceFile, $targetFile);
  281. } else {
  282. return false;
  283. }
  284. }
  285. /**
  286. * copy a file or folder
  287. *
  288. * @param dir $sourceDir
  289. * @param file $source
  290. * @param dir $targetDir
  291. * @param file $target
  292. */
  293. public static function copy($sourceDir, $source, $targetDir, $target) {
  294. if(OC_User::isLoggedIn()) {
  295. $targetFile=$targetDir.'/'.$target;
  296. $sourceFile=$sourceDir.'/'.$source;
  297. return OC_Filesystem::copy($sourceFile, $targetFile);
  298. }
  299. }
  300. /**
  301. * create a new file or folder
  302. *
  303. * @param dir $dir
  304. * @param file $name
  305. * @param type $type
  306. */
  307. public static function newFile($dir, $name, $type) {
  308. if(OC_User::isLoggedIn()) {
  309. $file=$dir.'/'.$name;
  310. if($type=='dir') {
  311. return OC_Filesystem::mkdir($file);
  312. }elseif($type=='file') {
  313. $fileHandle=OC_Filesystem::fopen($file, 'w');
  314. if($fileHandle) {
  315. fclose($fileHandle);
  316. return true;
  317. }else{
  318. return false;
  319. }
  320. }
  321. }
  322. }
  323. /**
  324. * deletes a file or folder
  325. *
  326. * @param dir $dir
  327. * @param file $name
  328. */
  329. public static function delete($dir, $file) {
  330. if(OC_User::isLoggedIn() && ($dir!= '' || $file != 'Shared')) {
  331. $file=$dir.'/'.$file;
  332. return OC_Filesystem::unlink($file);
  333. }
  334. }
  335. /**
  336. * checks if the selected files are within the size constraint. If not, outputs an error page.
  337. *
  338. * @param dir $dir
  339. * @param files $files
  340. */
  341. static function validateZipDownload($dir, $files) {
  342. if(!OC_Config::getValue('allowZipDownload', true)) {
  343. $l = OC_L10N::get('lib');
  344. header("HTTP/1.0 409 Conflict");
  345. $tmpl = new OC_Template( '', 'error', 'user' );
  346. $errors = array(
  347. array(
  348. 'error' => $l->t('ZIP download is turned off.'),
  349. 'hint' => $l->t('Files need to be downloaded one by one.') . '<br/><a href="javascript:history.back()">' . $l->t('Back to Files') . '</a>',
  350. )
  351. );
  352. $tmpl->assign('errors', $errors);
  353. $tmpl->printPage();
  354. exit;
  355. }
  356. $zipLimit = OC_Config::getValue('maxZipInputSize', OC_Helper::computerFileSize('800 MB'));
  357. if($zipLimit > 0) {
  358. $totalsize = 0;
  359. if(is_array($files)) {
  360. foreach($files as $file) {
  361. $totalsize += OC_Filesystem::filesize($dir.'/'.$file);
  362. }
  363. }else{
  364. $totalsize += OC_Filesystem::filesize($dir.'/'.$files);
  365. }
  366. if($totalsize > $zipLimit) {
  367. $l = OC_L10N::get('lib');
  368. header("HTTP/1.0 409 Conflict");
  369. $tmpl = new OC_Template( '', 'error', 'user' );
  370. $errors = array(
  371. array(
  372. 'error' => $l->t('Selected files too large to generate zip file.'),
  373. '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>',
  374. )
  375. );
  376. $tmpl->assign('errors', $errors);
  377. $tmpl->printPage();
  378. exit;
  379. }
  380. }
  381. }
  382. /**
  383. * try to detect the mime type of a file
  384. *
  385. * @param string path
  386. * @return string guessed mime type
  387. */
  388. static function getMimeType($path) {
  389. return OC_Filesystem::getMimeType($path);
  390. }
  391. /**
  392. * get a file tree
  393. *
  394. * @param string path
  395. * @return array
  396. */
  397. static function getTree($path) {
  398. return OC_Filesystem::getTree($path);
  399. }
  400. /**
  401. * pull a file from a remote server
  402. * @param string source
  403. * @param string token
  404. * @param string dir
  405. * @param string file
  406. * @return string guessed mime type
  407. */
  408. static function pull($source, $token, $dir, $file) {
  409. $tmpfile=tempnam(get_temp_dir(), 'remoteCloudFile');
  410. $fp=fopen($tmpfile, 'w+');
  411. $url=$source.="/files/pull.php?token=$token";
  412. $ch=curl_init();
  413. curl_setopt($ch, CURLOPT_URL, $url);
  414. curl_setopt($ch, CURLOPT_FILE, $fp);
  415. curl_exec($ch);
  416. fclose($fp);
  417. $info=curl_getinfo($ch);
  418. $httpCode=$info['http_code'];
  419. curl_close($ch);
  420. if($httpCode==200 or $httpCode==0) {
  421. OC_Filesystem::fromTmpFile($tmpfile, $dir.'/'.$file);
  422. return true;
  423. }else{
  424. return false;
  425. }
  426. }
  427. /**
  428. * set the maximum upload size limit for apache hosts using .htaccess
  429. * @param int size filesisze in bytes
  430. * @return false on failure, size on success
  431. */
  432. static function setUploadLimit($size) {
  433. //don't allow user to break his config -- upper boundary
  434. if($size > PHP_INT_MAX) {
  435. //max size is always 1 byte lower than computerFileSize returns
  436. if($size > PHP_INT_MAX+1)
  437. return false;
  438. $size -=1;
  439. } else {
  440. $size=OC_Helper::humanFileSize($size);
  441. $size=substr($size, 0, -1);//strip the B
  442. $size=str_replace(' ', '', $size); //remove the space between the size and the postfix
  443. }
  444. //don't allow user to break his config -- broken or malicious size input
  445. if(intval($size) == 0) {
  446. return false;
  447. }
  448. $htaccess = @file_get_contents(OC::$SERVERROOT.'/.htaccess'); //supress errors in case we don't have permissions for
  449. if(!$htaccess) {
  450. return false;
  451. }
  452. $phpValueKeys = array(
  453. 'upload_max_filesize',
  454. 'post_max_size'
  455. );
  456. foreach($phpValueKeys as $key) {
  457. $pattern = '/php_value '.$key.' (\S)*/';
  458. $setting = 'php_value '.$key.' '.$size;
  459. $hasReplaced = 0;
  460. $content = preg_replace($pattern, $setting, $htaccess, 1, $hasReplaced);
  461. if($content !== null) {
  462. $htaccess = $content;
  463. }
  464. if($hasReplaced == 0) {
  465. $htaccess .= "\n" . $setting;
  466. }
  467. }
  468. //check for write permissions
  469. if(is_writable(OC::$SERVERROOT.'/.htaccess')) {
  470. file_put_contents(OC::$SERVERROOT.'/.htaccess', $htaccess);
  471. return OC_Helper::computerFileSize($size);
  472. } else { OC_Log::write('files', 'Can\'t write upload limit to '.OC::$SERVERROOT.'/.htaccess. Please check the file permissions', OC_Log::WARN); }
  473. return false;
  474. }
  475. /**
  476. * normalize a path, removing any double, add leading /, etc
  477. * @param string $path
  478. * @return string
  479. */
  480. static public function normalizePath($path) {
  481. $path='/'.$path;
  482. $old='';
  483. while($old!=$path) {//replace any multiplicity of slashes with a single one
  484. $old=$path;
  485. $path=str_replace('//', '/', $path);
  486. }
  487. return $path;
  488. }
  489. }
  490. function fileCmp($a, $b) {
  491. if($a['type']=='dir' and $b['type']!='dir') {
  492. return -1;
  493. }elseif($a['type']!='dir' and $b['type']=='dir') {
  494. return 1;
  495. }else{
  496. return strnatcasecmp($a['name'], $b['name']);
  497. }
  498. }