server.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. <?php
  2. namespace KD2\WebDAV
  3. {
  4. //__KD2\WebDAV\Server__
  5. //__KD2\WebDAV\AbstractStorage__
  6. }
  7. namespace NanoKaraDAV
  8. {
  9. use KD2\WebDAV\AbstractStorage;
  10. use KD2\WebDAV\Exception as WebDAV_Exception;
  11. class Storage extends AbstractStorage
  12. {
  13. /**
  14. * These file names will be ignored when doing a PUT
  15. * as they are garbage, coming from some OS
  16. */
  17. const PUT_IGNORE_PATTERN = '!^~(?:lock\.|^\._)|^(?:\.DS_Store|Thumbs\.db|desktop\.ini)$!';
  18. protected string $path;
  19. public function __construct()
  20. {
  21. $this->path = __DIR__ . '/';
  22. }
  23. static protected function glob(string $path, string $pattern = '', int $flags = 0): array
  24. {
  25. $path = preg_replace('/[\*\?\[\]]/', '\\\\$0', $path);
  26. return glob($path . $pattern, $flags);
  27. }
  28. public function list(string $uri, ?array $properties): iterable
  29. {
  30. $dirs = self::glob($this->path . $uri, '/*', \GLOB_ONLYDIR);
  31. $dirs = array_map('basename', $dirs);
  32. natcasesort($dirs);
  33. $files = self::glob($this->path . $uri, '/*');
  34. $files = array_map('basename', $files);
  35. $files = array_diff($files, $dirs);
  36. // Remove PHP files from listings
  37. $files = array_filter($files, fn($a) => !preg_match('/\.(?:php\d?|phtml|phps)$/i', $a));
  38. if (!$uri) {
  39. $files = array_diff($files, ['webdav.js', 'webdav.css']);
  40. }
  41. natcasesort($files);
  42. $files = array_flip(array_merge($dirs, $files));
  43. $files = array_map(fn($a) => null, $files);
  44. return $files;
  45. }
  46. public function get(string $uri): ?array
  47. {
  48. $path = $this->path . $uri;
  49. if (!file_exists($path)) {
  50. return null;
  51. }
  52. return ['path' => $path];
  53. }
  54. public function exists(string $uri): bool
  55. {
  56. return file_exists($this->path . $uri);
  57. }
  58. public function get_file_property(string $uri, string $name, int $depth)
  59. {
  60. $target = $this->path . $uri;
  61. switch ($name) {
  62. case 'DAV::getcontentlength':
  63. return is_dir($target) ? null : filesize($target);
  64. case 'DAV::getcontenttype':
  65. // ownCloud app crashes if mimetype is provided for a directory
  66. // https://github.com/owncloud/android/issues/3768
  67. return is_dir($target) ? null : mime_content_type($target);
  68. case 'DAV::resourcetype':
  69. return is_dir($target) ? 'collection' : '';
  70. case 'DAV::getlastmodified':
  71. if (!$uri && $depth == 0 && is_dir($target)) {
  72. $mtime = self::getDirectoryMTime($target);
  73. }
  74. else {
  75. $mtime = filemtime($target);
  76. }
  77. if (!$mtime) {
  78. return null;
  79. }
  80. return new \DateTime('@' . $mtime);
  81. case 'DAV::displayname':
  82. return basename($target);
  83. case 'DAV::ishidden':
  84. return basename($target)[0] == '.';
  85. case 'DAV::getetag':
  86. $hash = filemtime($target) . filesize($target);
  87. return md5($hash . $target);
  88. case 'DAV::lastaccessed':
  89. return new \DateTime('@' . fileatime($target));
  90. case 'DAV::creationdate':
  91. return new \DateTime('@' . filectime($target));
  92. case WebDAV::PROP_DIGEST_MD5:
  93. if (!is_file($target)) {
  94. return null;
  95. }
  96. return md5_file($target);
  97. default:
  98. break;
  99. }
  100. return null;
  101. }
  102. public function properties(string $uri, ?array $properties, int $depth): ?array
  103. {
  104. $target = $this->path . $uri;
  105. if (!file_exists($target)) {
  106. return null;
  107. }
  108. if (null === $properties) {
  109. $properties = WebDAV::BASIC_PROPERTIES;
  110. }
  111. $out = [];
  112. foreach ($properties as $name) {
  113. $v = $this->get_file_property($uri, $name, $depth);
  114. if (null !== $v) {
  115. $out[$name] = $v;
  116. }
  117. }
  118. return $out;
  119. }
  120. public function put(string $uri, $pointer, ?string $hash, ?int $mtime): bool
  121. {
  122. if (preg_match(self::PUT_IGNORE_PATTERN, basename($uri))) {
  123. return false;
  124. }
  125. $target = $this->path . $uri;
  126. $parent = dirname($target);
  127. if (is_dir($target)) {
  128. throw new WebDAV_Exception('Target is a directory', 409);
  129. }
  130. if (!file_exists($parent)) {
  131. mkdir($parent, 0770, true);
  132. }
  133. $new = !file_exists($target);
  134. $delete = false;
  135. $size = 0;
  136. $quota = disk_free_space($this->path);
  137. $tmp_file = '.tmp.' . sha1($target);
  138. $out = fopen($tmp_file, 'w');
  139. while (!feof($pointer)) {
  140. $bytes = fread($pointer, 8192);
  141. $size += strlen($bytes);
  142. if ($size > $quota) {
  143. $delete = true;
  144. break;
  145. }
  146. fwrite($out, $bytes);
  147. }
  148. fclose($out);
  149. fclose($pointer);
  150. if ($delete) {
  151. @unlink($tmp_file);
  152. throw new WebDAV_Exception('Your quota is exhausted', 403);
  153. }
  154. elseif ($hash && md5_file($tmp_file) != $hash) {
  155. @unlink($tmp_file);
  156. throw new WebDAV_Exception('The data sent does not match the supplied MD5 hash', 400);
  157. }
  158. else {
  159. rename($tmp_file, $target);
  160. }
  161. if ($mtime) {
  162. @touch($target, $mtime);
  163. }
  164. return $new;
  165. }
  166. public function delete(string $uri): void
  167. {
  168. $target = $this->path . $uri;
  169. if (!file_exists($target)) {
  170. throw new WebDAV_Exception('Target does not exist', 404);
  171. }
  172. if (is_dir($target)) {
  173. foreach (self::glob($target, '/*') as $file) {
  174. $this->delete(substr($file, strlen($this->path)));
  175. }
  176. rmdir($target);
  177. }
  178. else {
  179. unlink($target);
  180. }
  181. }
  182. public function copymove(bool $move, string $uri, string $destination): bool
  183. {
  184. $source = $this->path . $uri;
  185. $target = $this->path . $destination;
  186. $parent = dirname($target);
  187. if (!file_exists($source)) {
  188. throw new WebDAV_Exception('File not found', 404);
  189. }
  190. $overwritten = file_exists($target);
  191. if (!is_dir($parent)) {
  192. throw new WebDAV_Exception('Target parent directory does not exist', 409);
  193. }
  194. if (false === $move) {
  195. $quota = disk_free_space($this->path);
  196. if (filesize($source) > $quota) {
  197. throw new WebDAV_Exception('Your quota is exhausted', 403);
  198. }
  199. }
  200. if ($overwritten) {
  201. $this->delete($destination);
  202. }
  203. $method = $move ? 'rename' : 'copy';
  204. if ($method == 'copy' && is_dir($source)) {
  205. @mkdir($target, 0770, true);
  206. foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST) as $item)
  207. {
  208. if ($item->isDir()) {
  209. @mkdir($target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  210. } else {
  211. copy($item, $target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  212. }
  213. }
  214. }
  215. else {
  216. $method($source, $target);
  217. $this->getResourceProperties($uri)->move($destination);
  218. }
  219. return $overwritten;
  220. }
  221. public function copy(string $uri, string $destination): bool
  222. {
  223. return $this->copymove(false, $uri, $destination);
  224. }
  225. public function move(string $uri, string $destination): bool
  226. {
  227. return $this->copymove(true, $uri, $destination);
  228. }
  229. public function mkcol(string $uri): void
  230. {
  231. if (!disk_free_space($this->path)) {
  232. throw new WebDAV_Exception('Your quota is exhausted', 403);
  233. }
  234. $target = $this->path . $uri;
  235. $parent = dirname($target);
  236. if (file_exists($target)) {
  237. throw new WebDAV_Exception('There is already a file with that name', 405);
  238. }
  239. if (!file_exists($parent)) {
  240. throw new WebDAV_Exception('The parent directory does not exist', 409);
  241. }
  242. mkdir($target, 0770);
  243. }
  244. static public function getDirectoryMTime(string $path): int
  245. {
  246. $last = 0;
  247. $path = rtrim($path, '/');
  248. foreach (self::glob($path, '/*', GLOB_NOSORT) as $f) {
  249. if (is_dir($f)) {
  250. $m = self::getDirectoryMTime($f);
  251. if ($m > $last) {
  252. $last = $m;
  253. }
  254. }
  255. $m = filemtime($f);
  256. if ($m > $last) {
  257. $last = $m;
  258. }
  259. }
  260. return $last;
  261. }
  262. }
  263. class Server extends \KD2\WebDAV\Server
  264. {
  265. protected function html_directory(string $uri, iterable $list): ?string
  266. {
  267. $out = parent::html_directory($uri, $list);
  268. if (null !== $out) {
  269. $out = str_replace('<body>', sprintf('<body style="opacity: 0"><script type="text/javascript" src="%s/webdav.js"></script>', rtrim($this->base_uri, '/')), $out);
  270. }
  271. return $out;
  272. }
  273. }
  274. }
  275. namespace {
  276. use NanoKaraDAV\Server;
  277. use NanoKaraDAV\Storage;
  278. $uri = strtok($_SERVER['REQUEST_URI'], '?');
  279. $root = substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));
  280. if (false !== strpos($uri, '..')) {
  281. http_response_code(404);
  282. die('Invalid URL');
  283. }
  284. $relative_uri = ltrim(substr($uri, strlen($root)), '/');
  285. if ($relative_uri == 'webdav.js' || $relative_uri == 'webdav.css') {
  286. http_response_code(200);
  287. if ($relative_uri == 'webdav.js') {
  288. header('Content-Type: text/javascript', true);
  289. }
  290. else {
  291. header('Content-Type: text/css', true);
  292. }
  293. $seconds_to_cache = 3600 * 24 * 365;
  294. $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  295. header("Expires: " . $ts);
  296. header("Pragma: cache");
  297. header("Cache-Control: max-age=" . $seconds_to_cache);
  298. $fp = fopen(__FILE__, 'r');
  299. if ($relative_uri == 'webdav.js') {
  300. fseek($fp, __PHP_SIZE__, SEEK_SET);
  301. echo fread($fp, __JS_SIZE__);
  302. }
  303. else {
  304. fseek($fp, __PHP_SIZE__ + __JS_SIZE__, SEEK_SET);
  305. echo fread($fp, __CSS_SIZE__);
  306. }
  307. fclose($fp);
  308. exit;
  309. }
  310. $dav = new Server;
  311. $dav->setStorage(new Storage);
  312. $dav->setBaseURI($root);
  313. if (!$dav->route($uri)) {
  314. http_response_code(404);
  315. die('Invalid URL, sorry');
  316. }
  317. exit;
  318. }