Filesystem.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. <?php
  2. require_once "HTTP/WebDAV/Server.php";
  3. require_once "System.php";
  4. /**
  5. * Filesystem access using WebDAV
  6. *
  7. * @access public
  8. */
  9. class HTTP_WebDAV_Server_Filesystem extends HTTP_WebDAV_Server
  10. {
  11. /**
  12. * Root directory for WebDAV access
  13. *
  14. * Defaults to webserver document root (set by ServeRequest)
  15. *
  16. * @access private
  17. * @var string
  18. */
  19. var $base = "";
  20. /**
  21. * Serve a webdav request
  22. *
  23. * @access public
  24. * @param string
  25. */
  26. function ServeRequest($base = false)
  27. {
  28. // special treatment for litmus compliance test
  29. // reply on its identifier header
  30. // not needed for the test itself but eases debugging
  31. if (function_exists("apache_request_headers")) {
  32. foreach(apache_request_headers() as $key => $value) {
  33. if (stristr($key,"litmus")) {
  34. error_log("Litmus test $value");
  35. header("X-Litmus-reply: ".$value);
  36. }
  37. }
  38. }
  39. // set root directory, defaults to webserver document root if not set
  40. if ($base) {
  41. $this->base = realpath($base); // TODO throw if not a directory
  42. } else if (!$this->base) {
  43. $this->base = $_SERVER['DOCUMENT_ROOT'];
  44. }
  45. // let the base class do all the work
  46. parent::ServeRequest();
  47. }
  48. /**
  49. * No authentication is needed here
  50. *
  51. * @access private
  52. * @param string HTTP Authentication type (Basic, Digest, ...)
  53. * @param string Username
  54. * @param string Password
  55. * @return bool true on successful authentication
  56. */
  57. function check_auth($type, $user, $pass)
  58. {
  59. return true;
  60. }
  61. /**
  62. * PROPFIND method handler
  63. *
  64. * @param array general parameter passing array
  65. * @param array return array for file properties
  66. * @return bool true on success
  67. */
  68. function PROPFIND(&$options, &$files)
  69. {
  70. // get absolute fs path to requested resource
  71. $fspath = $this->base . $options["path"];
  72. // sanity check
  73. if (!file_exists($fspath)) {
  74. return false;
  75. }
  76. // prepare property array
  77. $files["files"] = array();
  78. // store information for the requested path itself
  79. $files["files"][] = $this->fileinfo($options["path"]);
  80. // information for contained resources requested?
  81. if (!empty($options["depth"])) { // TODO check for is_dir() first?
  82. // make sure path ends with '/'
  83. $options["path"] = $this->_slashify($options["path"]);
  84. // try to open directory
  85. $handle = @opendir($fspath);
  86. if ($handle) {
  87. // ok, now get all its contents
  88. while ($filename = readdir($handle)) {
  89. if ($filename != "." && $filename != "..") {
  90. $files["files"][] = $this->fileinfo($options["path"].$filename);
  91. }
  92. }
  93. // TODO recursion needed if "Depth: infinite"
  94. }
  95. }
  96. // ok, all done
  97. return true;
  98. }
  99. /**
  100. * Get properties for a single file/resource
  101. *
  102. * @param string resource path
  103. * @return array resource properties
  104. */
  105. function fileinfo($path)
  106. {
  107. // map URI path to filesystem path
  108. $fspath = $this->base . $path;
  109. // create result array
  110. $info = array();
  111. // TODO remove slash append code when base clase is able to do it itself
  112. $info["path"] = is_dir($fspath) ? $this->_slashify($path) : $path;
  113. $info["props"] = array();
  114. // no special beautified displayname here ...
  115. $info["props"][] = $this->mkprop("displayname", strtoupper($path));
  116. // creation and modification time
  117. $info["props"][] = $this->mkprop("creationdate", filectime($fspath));
  118. $info["props"][] = $this->mkprop("getlastmodified", filemtime($fspath));
  119. // type and size (caller already made sure that path exists)
  120. if (is_dir($fspath)) {
  121. // directory (WebDAV collection)
  122. $info["props"][] = $this->mkprop("resourcetype", "collection");
  123. $info["props"][] = $this->mkprop("getcontenttype", "httpd/unix-directory");
  124. } else {
  125. // plain file (WebDAV resource)
  126. $info["props"][] = $this->mkprop("resourcetype", "");
  127. if (is_readable($fspath)) {
  128. $info["props"][] = $this->mkprop("getcontenttype", $this->_mimetype($fspath));
  129. } else {
  130. $info["props"][] = $this->mkprop("getcontenttype", "application/x-non-readable");
  131. }
  132. $info["props"][] = $this->mkprop("getcontentlength", filesize($fspath));
  133. }
  134. return $info;
  135. }
  136. /**
  137. * detect if a given program is found in the search PATH
  138. *
  139. * helper function used by _mimetype() to detect if the
  140. * external 'file' utility is available
  141. *
  142. * @param string program name
  143. * @param string optional search path, defaults to $PATH
  144. * @return bool true if executable program found in path
  145. */
  146. function _can_execute($name, $path = false)
  147. {
  148. // path defaults to PATH from environment if not set
  149. if ($path === false) {
  150. $path = getenv("PATH");
  151. }
  152. // check method depends on operating system
  153. if (!strncmp(PHP_OS, "WIN", 3)) {
  154. // on Windows an appropriate COM or EXE file needs to exist
  155. $exts = array(".exe", ".com");
  156. $check_fn = "file_exists";
  157. } else {
  158. // anywhere else we look for an executable file of that name
  159. $exts = array("");
  160. $check_fn = "is_executable";
  161. }
  162. // now check the directories in the path for the program
  163. foreach (explode(PATH_SEPARATOR, $path) as $dir) {
  164. // skip invalid path entries
  165. if (!file_exists($dir)) continue;
  166. if (!is_dir($dir)) continue;
  167. // and now look for the file
  168. foreach ($exts as $ext) {
  169. if ($check_fn("$dir/$name".$ext)) return true;
  170. }
  171. }
  172. return false;
  173. }
  174. /**
  175. * try to detect the mime type of a file
  176. *
  177. * @param string file path
  178. * @return string guessed mime type
  179. */
  180. function _mimetype($fspath)
  181. {
  182. if (@is_dir($fspath)) {
  183. // directories are easy
  184. return "httpd/unix-directory";
  185. } else if (function_exists("mime_content_type")) {
  186. // use mime magic extension if available
  187. $mime_type = mime_content_type($fspath);
  188. } else if ($this->_can_execute("file")) {
  189. // it looks like we have a 'file' command,
  190. // lets see it it does have mime support
  191. $fp = popen("file -i '$fspath' 2>/dev/null", "r");
  192. $reply = fgets($fp);
  193. pclose($fp);
  194. // popen will not return an error if the binary was not found
  195. // and find may not have mime support using "-i"
  196. // so we test the format of the returned string
  197. // the reply begins with the requested filename
  198. if (!strncmp($reply, "$fspath: ", strlen($fspath)+2)) {
  199. $reply = substr($reply, strlen($fspath)+2);
  200. // followed by the mime type (maybe including options)
  201. if (preg_match('/^[[:alnum:]_-]+/[[:alnum:]_-]+;?.*/', $reply, $matches)) {
  202. $mime_type = $matches[0];
  203. }
  204. }
  205. }
  206. if (empty($mime_type)) {
  207. // Fallback solution: try to guess the type by the file extension
  208. // TODO: add more ...
  209. // TODO: it has been suggested to delegate mimetype detection
  210. // to apache but this has at least three issues:
  211. // - works only with apache
  212. // - needs file to be within the document tree
  213. // - requires apache mod_magic
  214. // TODO: can we use the registry for this on Windows?
  215. // OTOH if the server is Windos the clients are likely to
  216. // be Windows, too, and tend do ignore the Content-Type
  217. // anyway (overriding it with information taken from
  218. // the registry)
  219. // TODO: have a seperate PEAR class for mimetype detection?
  220. switch (strtolower(strrchr(basename($fspath), "."))) {
  221. case ".html":
  222. $mime_type = "text/html";
  223. break;
  224. case ".gif":
  225. $mime_type = "image/gif";
  226. break;
  227. case ".jpg":
  228. $mime_type = "image/jpeg";
  229. break;
  230. default:
  231. $mime_type = "application/octet-stream";
  232. break;
  233. }
  234. }
  235. return $mime_type;
  236. }
  237. /**
  238. * GET method handler
  239. *
  240. * @param array parameter passing array
  241. * @return bool true on success
  242. */
  243. function GET(&$options)
  244. {
  245. // get absolute fs path to requested resource
  246. $fspath = $this->base . $options["path"];
  247. // sanity check
  248. if (!file_exists($fspath)) return false;
  249. // is this a collection?
  250. if (is_dir($fspath)) {
  251. return $this->GetDir($fspath, $options);
  252. }
  253. // detect resource type
  254. $options['mimetype'] = $this->_mimetype($fspath);
  255. // detect modification time
  256. // see rfc2518, section 13.7
  257. // some clients seem to treat this as a reverse rule
  258. // requiering a Last-Modified header if the getlastmodified header was set
  259. $options['mtime'] = filemtime($fspath);
  260. // detect resource size
  261. $options['size'] = filesize($fspath);
  262. // no need to check result here, it is handled by the base class
  263. $options['stream'] = fopen($fspath, "r");
  264. return true;
  265. }
  266. /**
  267. * GET method handler for directories
  268. *
  269. * This is a very simple mod_index lookalike.
  270. * See RFC 2518, Section 8.4 on GET/HEAD for collections
  271. *
  272. * @param string directory path
  273. * @return void function has to handle HTTP response itself
  274. */
  275. function GetDir($fspath, &$options)
  276. {
  277. $path = $this->_slashify($options["path"]);
  278. if ($path != $options["path"]) {
  279. header("Location: ".$this->base_uri.$path);
  280. exit;
  281. }
  282. // fixed width directory column format
  283. $format = "%15s %-19s %-s\n";
  284. $handle = @opendir($fspath);
  285. if (!$handle) {
  286. return false;
  287. }
  288. echo "<html><head><title>Index of ".htmlspecialchars($options['path'])."</title></head>\n";
  289. echo "<h1>Index of ".htmlspecialchars($options['path'])."</h1>\n";
  290. echo "<pre>";
  291. printf($format, "Size", "Last modified", "Filename");
  292. echo "<hr>";
  293. while ($filename = readdir($handle)) {
  294. if ($filename != "." && $filename != "..") {
  295. $fullpath = $fspath."/".$filename;
  296. $name = htmlspecialchars($filename);
  297. printf($format,
  298. number_format(filesize($fullpath)),
  299. strftime("%Y-%m-%d %H:%M:%S", filemtime($fullpath)),
  300. "<a href='$this->base_uri$path$name'>$name</a>");
  301. }
  302. }
  303. echo "</pre>";
  304. closedir($handle);
  305. echo "</html>\n";
  306. exit;
  307. }
  308. /**
  309. * PUT method handler
  310. *
  311. * @param array parameter passing array
  312. * @return bool true on success
  313. */
  314. function PUT(&$options)
  315. {
  316. $fspath = $this->base . $options["path"];
  317. if (!@is_dir(dirname($fspath))) {
  318. return "409 Conflict";
  319. }
  320. $options["new"] = ! file_exists($fspath);
  321. $fp = fopen($fspath, "w");
  322. return $fp;
  323. }
  324. /**
  325. * MKCOL method handler
  326. *
  327. * @param array general parameter passing array
  328. * @return bool true on success
  329. */
  330. function MKCOL($options)
  331. {
  332. $path = $this->base .$options["path"];
  333. $parent = dirname($path);
  334. $name = basename($path);
  335. if (!file_exists($parent)) {
  336. return "409 Conflict";
  337. }
  338. if (!is_dir($parent)) {
  339. return "403 Forbidden";
  340. }
  341. if ( file_exists($parent."/".$name) ) {
  342. return "405 Method not allowed";
  343. }
  344. if (!empty($_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
  345. return "415 Unsupported media type";
  346. }
  347. $stat = mkdir ($parent."/".$name,0777);
  348. if (!$stat) {
  349. return "403 Forbidden";
  350. }
  351. return ("201 Created");
  352. }
  353. /**
  354. * DELETE method handler
  355. *
  356. * @param array general parameter passing array
  357. * @return bool true on success
  358. */
  359. function DELETE($options)
  360. {
  361. $path = $this->base . "/" .$options["path"];
  362. if (!file_exists($path)) {
  363. return "404 Not found";
  364. }
  365. if (is_dir($path)) {
  366. System::rm("-rf $path");
  367. } else {
  368. unlink ($path);
  369. }
  370. return "204 No Content";
  371. }
  372. /**
  373. * MOVE method handler
  374. *
  375. * @param array general parameter passing array
  376. * @return bool true on success
  377. */
  378. function MOVE($options)
  379. {
  380. return $this->COPY($options, true);
  381. }
  382. /**
  383. * COPY method handler
  384. *
  385. * @param array general parameter passing array
  386. * @return bool true on success
  387. */
  388. function COPY($options, $del=false)
  389. {
  390. // TODO Property updates still broken (Litmus should detect this?)
  391. if (!empty($_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
  392. return "415 Unsupported media type";
  393. }
  394. // no copying to different WebDAV Servers yet
  395. if (isset($options["dest_url"])) {
  396. return "502 bad gateway";
  397. }
  398. $source = $this->base .$options["path"];
  399. if (!file_exists($source)) return "404 Not found";
  400. $dest = $this->base . $options["dest"];
  401. $new = !file_exists($dest);
  402. $existing_col = false;
  403. if (!$new) {
  404. if ($del && is_dir($dest)) {
  405. if (!$options["overwrite"]) {
  406. return "412 precondition failed";
  407. }
  408. $dest .= basename($source);
  409. if (file_exists($dest)) {
  410. $options["dest"] .= basename($source);
  411. } else {
  412. $new = true;
  413. $existing_col = true;
  414. }
  415. }
  416. }
  417. if (!$new) {
  418. if ($options["overwrite"]) {
  419. $stat = $this->DELETE(array("path" => $options["dest"]));
  420. if (($stat{0} != "2") && (substr($stat, 0, 3) != "404")) {
  421. return $stat;
  422. }
  423. } else {
  424. return "412 precondition failed";
  425. }
  426. }
  427. if (is_dir($source) && ($options["depth"] != "infinity")) {
  428. // RFC 2518 Section 9.2, last paragraph
  429. return "400 Bad request";
  430. }
  431. if ($del) {
  432. if (!rename($source, $dest)) {
  433. return "500 Internal server error";
  434. }
  435. $destpath = $this->_unslashify($options["dest"]);
  436. } else {
  437. if (is_dir($source)) {
  438. $files = System::find($source);
  439. $files = array_reverse($files);
  440. } else {
  441. $files = array($source);
  442. }
  443. if (!is_array($files) || empty($files)) {
  444. return "500 Internal server error";
  445. }
  446. foreach ($files as $file) {
  447. if (is_dir($file)) {
  448. $file = $this->_slashify($file);
  449. }
  450. $destfile = str_replace($source, $dest, $file);
  451. if (is_dir($file)) {
  452. if (!is_dir($destfile)) {
  453. // TODO "mkdir -p" here? (only natively supported by PHP 5)
  454. if (!mkdir($destfile)) {
  455. return "409 Conflict";
  456. }
  457. } else {
  458. error_log("existing dir '$destfile'");
  459. }
  460. } else {
  461. if (!copy($file, $destfile)) {
  462. return "409 Conflict";
  463. }
  464. }
  465. }
  466. }
  467. return ($new && !$existing_col) ? "201 Created" : "204 No Content";
  468. }
  469. /**
  470. * PROPPATCH method handler
  471. *
  472. * @param array general parameter passing array
  473. * @return bool true on success
  474. */
  475. function PROPPATCH(&$options)
  476. {
  477. global $prefs, $tab;
  478. $msg = "";
  479. $path = $options["path"];
  480. $dir = dirname($path)."/";
  481. $base = basename($path);
  482. foreach($options["props"] as $key => $prop) {
  483. if ($prop["ns"] == "DAV:") {
  484. $options["props"][$key]['status'] = "403 Forbidden";
  485. }
  486. }
  487. return "";
  488. }
  489. }
  490. ?>