index.php 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284
  1. <?php
  2. namespace KD2\WebDAV
  3. {
  4. class Exception extends \RuntimeException {}
  5. class Server
  6. {
  7. // List of basic DAV properties that you should return if $requested_properties is NULL
  8. const BASIC_PROPERTIES = [
  9. 'DAV::resourcetype', // should be empty for files, and 'collection' for directories
  10. 'DAV::getcontenttype', // MIME type
  11. 'DAV::getlastmodified', // File modification date (must be \DateTimeInterface)
  12. 'DAV::getcontentlength', // file size
  13. 'DAV::displayname', // File name for display
  14. ];
  15. const EXTENDED_PROPERTIES = [
  16. 'DAV::getetag',
  17. 'DAV::creationdate',
  18. 'DAV::lastaccessed',
  19. 'DAV::ishidden', // Microsoft thingy
  20. 'DAV::quota-used-bytes',
  21. 'DAV::quota-available-bytes',
  22. ];
  23. // Custom properties
  24. const PROP_DIGEST_MD5 = 'urn:karadav:digest_md5';
  25. const EMPTY_PROP_VALUE = 'DAV::empty';
  26. const SHARED_LOCK = 'shared';
  27. const EXCLUSIVE_LOCK = 'exclusive';
  28. protected string $base_uri;
  29. public string $original_uri;
  30. public string $prefix = '';
  31. protected AbstractStorage $storage;
  32. public function setStorage(AbstractStorage $storage)
  33. {
  34. $this->storage = $storage;
  35. }
  36. public function getStorage(): AbstractStorage
  37. {
  38. return $this->storage;
  39. }
  40. public function setBaseURI(string $uri): void
  41. {
  42. $this->base_uri = rtrim($uri, '/') . '/';
  43. }
  44. protected function _prefix(string $uri): string
  45. {
  46. if (!$this->prefix) {
  47. return $uri;
  48. }
  49. return rtrim(rtrim($this->prefix, '/') . '/' . ltrim($uri, '/'), '/');
  50. }
  51. protected function html_directory(string $uri, iterable $list): ?string
  52. {
  53. // Not a file: let's serve a directory listing if you are browsing with a web browser
  54. if (substr($this->original_uri, -1) != '/') {
  55. http_response_code(301);
  56. header(sprintf('Location: /%s/', trim($this->base_uri . $uri, '/')), true);
  57. return null;
  58. }
  59. $out = sprintf('<!DOCTYPE html><html data-webdav-url="%s"><head><meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=device-dpi" /><style>
  60. body { font-size: 1.1em; font-family: Arial, Helvetica, sans-serif; }
  61. table { border-collapse: collapse; }
  62. th, td { padding: .5em; text-align: left; border: 2px solid #ccc; }
  63. span { font-size: 40px; line-height: 40px; }
  64. </style>', '/' . ltrim($this->base_uri, '/'));
  65. $out .= sprintf('<title>%s</title></head><body><h1>%1$s</h1><table>', htmlspecialchars($uri ? str_replace('/', ' / ', $uri) . ' - Files' : 'Files'));
  66. if (trim($uri)) {
  67. $out .= '<tr><th colspan=3><a href="../"><b>Back</b></a></th></tr>';
  68. }
  69. $props = null;
  70. foreach ($list as $file => $props) {
  71. if (null === $props) {
  72. $props = $this->storage->properties(trim($uri . '/' . $file, '/'), self::BASIC_PROPERTIES, 0);
  73. }
  74. $collection = !empty($props['DAV::resourcetype']) && $props['DAV::resourcetype'] == 'collection';
  75. if ($collection) {
  76. $out .= sprintf('<tr><td>[DIR]</td><th><a href="%s/"><b>%s</b></a></th></tr>', rawurlencode($file), htmlspecialchars($file));
  77. }
  78. else {
  79. $size = $props['DAV::getcontentlength'];
  80. if ($size > 1024*1024) {
  81. $size = sprintf('%d MB', $size / 1024 / 1024);
  82. }
  83. elseif ($size) {
  84. $size = sprintf('%d KB', $size / 1024);
  85. }
  86. $date = $props['DAV::getlastmodified'];
  87. if ($date instanceof \DateTimeInterface) {
  88. $date = $date->format('d/m/Y H:i');
  89. }
  90. $out .= sprintf('<tr><td></td><th><a href="%s">%s</a></th><td>%s</td><td>%s</td></tr>',
  91. rawurlencode($file),
  92. htmlspecialchars($file),
  93. $size,
  94. $date
  95. );
  96. }
  97. }
  98. $out .= '</table>';
  99. if (null === $props) {
  100. $out .= '<p>This directory is empty.</p>';
  101. }
  102. $out .= '</body></html>';
  103. return $out;
  104. }
  105. public function http_delete(string $uri): ?string
  106. {
  107. // check RFC 2518 Section 9.2, last paragraph
  108. if (isset($_SERVER['HTTP_DEPTH']) && $_SERVER['HTTP_DEPTH'] != 'infinity') {
  109. throw new Exception('We can only delete to infinity', 400);
  110. }
  111. $uri = $this->_prefix($uri);
  112. $this->checkLock($uri);
  113. $this->storage->delete($uri);
  114. if ($token = $this->getLockToken()) {
  115. $this->storage->unlock($uri, $token);
  116. }
  117. http_response_code(204);
  118. header('Content-Length: 0', true);
  119. return null;
  120. }
  121. public function http_put(string $uri): ?string
  122. {
  123. if (!empty($_SERVER['HTTP_CONTENT_TYPE']) && !strncmp($_SERVER['HTTP_CONTENT_TYPE'], 'multipart/', 10)) {
  124. throw new Exception('Multipart PUT requests are not supported', 501);
  125. }
  126. if (!empty($_SERVER['HTTP_CONTENT_ENCODING'])) {
  127. if (false !== strpos($_SERVER['HTTP_CONTENT_ENCODING'], 'gzip')) {
  128. // Might be supported later?
  129. throw new Exception('Content Encoding is not supported', 501);
  130. }
  131. else {
  132. throw new Exception('Content Encoding is not supported', 501);
  133. }
  134. }
  135. if (!empty($_SERVER['HTTP_CONTENT_RANGE'])) {
  136. throw new Exception('Content Range is not supported', 501);
  137. }
  138. // See SabreDAV CorePlugin for reason why OS/X Finder is buggy
  139. if (isset($_SERVER['HTTP_X_EXPECTED_ENTITY_LENGTH'])) {
  140. throw new Exception('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.', 403);
  141. }
  142. $hash = null;
  143. // Support for checksum matching
  144. // https://dcache.org/old/manuals/UserGuide-6.0/webdav.shtml#checksums
  145. if (!empty($_SERVER['HTTP_CONTENT_MD5'])) {
  146. $hash = bin2hex(base64_decode($_SERVER['HTTP_CONTENT_MD5']));
  147. }
  148. $uri = $this->_prefix($uri);
  149. $this->checkLock($uri);
  150. if (!empty($_SERVER['HTTP_IF_MATCH'])) {
  151. $etag = trim($_SERVER['HTTP_IF_MATCH'], '" ');
  152. $prop = $this->storage->properties($uri, ['DAV::getetag'], 0);
  153. if (!empty($prop['DAV::getetag']) && $prop['DAV::getetag'] != $etag) {
  154. throw new Exception('ETag did not match condition', 412);
  155. }
  156. }
  157. // Specific to NextCloud/ownCloud
  158. $mtime = (int)($_SERVER['HTTP_X_OC_MTIME'] ?? 0) ?: null;
  159. if ($mtime) {
  160. header('X-OC-MTime: accepted');
  161. }
  162. $created = $this->storage->put($uri, fopen('php://input', 'r'), $hash, $mtime);
  163. $prop = $this->storage->properties($uri, ['DAV::getetag'], 0);
  164. if (!empty($prop['DAV::getetag'])) {
  165. $value = $prop['DAV::getetag'];
  166. if (substr($value, 0, 1) != '"') {
  167. $value = '"' . $value . '"';
  168. }
  169. header(sprintf('ETag: %s', $value));
  170. }
  171. http_response_code($created ? 201 : 204);
  172. return null;
  173. }
  174. public function http_head(string $uri, array &$props = []): ?string
  175. {
  176. $uri = $this->_prefix($uri);
  177. $requested_props = self::BASIC_PROPERTIES;
  178. $requested_props[] = 'DAV::getetag';
  179. // RFC 3230 https://www.rfc-editor.org/rfc/rfc3230.html
  180. if (!empty($_SERVER['HTTP_WANT_DIGEST'])) {
  181. $requested_props[] = self::PROP_DIGEST_MD5;
  182. }
  183. $props = $this->storage->properties($uri, $requested_props, 0);
  184. if (!$props) {
  185. throw new Exception('Resource Not Found', 404);
  186. }
  187. http_response_code(200);
  188. if (isset($props['DAV::getlastmodified'])
  189. && $props['DAV::getlastmodified'] instanceof \DateTimeInterface) {
  190. header(sprintf('Last-Modified: %s', $props['DAV::getlastmodified']->format(\DATE_RFC7231)));
  191. }
  192. if (!empty($props['DAV::getetag'])) {
  193. $value = $props['DAV::getetag'];
  194. if (substr($value, 0, 1) != '"') {
  195. $value = '"' . $value . '"';
  196. }
  197. header(sprintf('ETag: %s', $value));
  198. }
  199. if (empty($props['DAV::resourcetype']) || $props['DAV::resourcetype'] != 'collection') {
  200. if (!empty($props['DAV::getcontenttype'])) {
  201. header(sprintf('Content-Type: %s', $props['DAV::getcontenttype']));
  202. }
  203. if (!empty($props['DAV::getcontentlength'])) {
  204. header(sprintf('Content-Length: %d', $props['DAV::getcontentlength']));
  205. header('Accept-Ranges: bytes');
  206. }
  207. }
  208. if (!empty($props[self::PROP_DIGEST_MD5])) {
  209. header(sprintf('Digest: md5=%s', base64_encode(hex2bin($props[self::PROP_DIGEST_MD5]))));
  210. }
  211. return null;
  212. }
  213. public function http_get(string $uri): ?string
  214. {
  215. $props = [];
  216. $this->http_head($uri, $props);
  217. $uri = $this->_prefix($uri);
  218. $is_collection = !empty($props['DAV::resourcetype']) && $props['DAV::resourcetype'] == 'collection';
  219. $out = '';
  220. if ($is_collection) {
  221. $list = $this->storage->list($uri, self::BASIC_PROPERTIES);
  222. if (!isset($_SERVER['HTTP_ACCEPT']) || false === strpos($_SERVER['HTTP_ACCEPT'], 'html')) {
  223. $list = is_array($list) ? $list : iterator_to_array($list);
  224. if (!count($list)) {
  225. return "Nothing in this collection\n";
  226. }
  227. return implode("\n", array_keys($list));
  228. }
  229. header('Content-Type: text/html; charset=utf-8', true);
  230. return $this->html_directory($uri, $list);
  231. }
  232. $file = $this->storage->get($uri);
  233. if (!$file) {
  234. throw new Exception('File Not Found', 404);
  235. }
  236. // If the file was returned to the client by the storage backend, stop here
  237. if (!empty($file['stop'])) {
  238. return null;
  239. }
  240. if (!isset($file['content']) && !isset($file['resource']) && !isset($file['path'])) {
  241. throw new \RuntimeException('Invalid file array returned by ::get()');
  242. }
  243. $length = $start = $end = null;
  244. $gzip = false;
  245. if (isset($_SERVER['HTTP_RANGE'])
  246. && preg_match('/^bytes=(\d*)-(\d*)$/i', $_SERVER['HTTP_RANGE'], $match)
  247. && $match[1] . $match[2] !== '') {
  248. $start = $match[1] === '' ? null : (int) $match[1];
  249. $end = $match[2] === '' ? null : (int) $match[2];
  250. if (null !== $start && $start < 0) {
  251. throw new Exception('Start range cannot be satisfied', 416);
  252. }
  253. if (isset($props['DAV::getcontentlength']) && $start > $props['DAV::getcontentlength']) {
  254. throw new Exception('End range cannot be satisfied', 416);
  255. }
  256. $this->log('HTTP Range requested: %s-%s', $start, $end);
  257. }
  258. elseif (isset($_SERVER['HTTP_ACCEPT_ENCODING'])
  259. && false !== strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')
  260. // Don't compress already compressed content
  261. && !preg_match('/\.(?:mp4|m4a|zip|docx|xlsx|ods|odt|odp|7z|gz|bz2|rar|webm|ogg|mp3|ogm|flac|ogv|mkv|avi)$/i', $uri)) {
  262. $gzip = true;
  263. header('Content-Encoding: gzip', true);
  264. }
  265. // Try to avoid common issues with output buffering and stuff
  266. if (function_exists('apache_setenv'))
  267. {
  268. @apache_setenv('no-gzip', 1);
  269. }
  270. @ini_set('zlib.output_compression', 'Off');
  271. if (@ob_get_length()) {
  272. @ob_clean();
  273. }
  274. if (isset($file['content'])) {
  275. $length = strlen($file['content']);
  276. if ($start || $end) {
  277. if (null !== $end && $end > $length) {
  278. header('Content-Range: bytes */' . $length, true);
  279. throw new Exception('End range cannot be satisfied', 416);
  280. }
  281. if ($start === null) {
  282. $start = $length - $end;
  283. $end = $start + $end;
  284. }
  285. elseif ($end === null) {
  286. $end = $length;
  287. }
  288. http_response_code(206);
  289. header(sprintf('Content-Range: bytes %s-%s/%s', $start, $end - 1, $length));
  290. $file['content'] = substr($file['content'], $start, $end - $start);
  291. $length = $end - $start;
  292. }
  293. if ($gzip) {
  294. $file['content'] = gzencode($file['content'], 9);
  295. $length = strlen($file['content']);
  296. }
  297. header('Content-Length: ' . $length, true);
  298. echo $file['content'];
  299. return null;
  300. }
  301. if (isset($file['path'])) {
  302. $file['resource'] = fopen($file['path'], 'rb');
  303. }
  304. $seek = fseek($file['resource'], 0, SEEK_END);
  305. if ($seek === 0) {
  306. $length = ftell($file['resource']);
  307. fseek($file['resource'], 0, SEEK_SET);
  308. }
  309. if (($start || $end) && $seek === 0) {
  310. if (null !== $end && $end > $length) {
  311. header('Content-Range: bytes */' . $length, true);
  312. throw new Exception('End range cannot be satisfied', 416);
  313. }
  314. if ($start === null) {
  315. $start = $length - $end;
  316. $end = $start + $end;
  317. }
  318. elseif ($end === null) {
  319. $end = $length;
  320. }
  321. fseek($file['resource'], $start, SEEK_SET);
  322. http_response_code(206);
  323. header(sprintf('Content-Range: bytes %s-%s/%s', $start, $end - 1, $length), true);
  324. $length = $end - $start;
  325. $end -= $start;
  326. }
  327. elseif (null === $length && isset($file['path'])) {
  328. $end = $length = filesize($file['path']);
  329. }
  330. if ($gzip) {
  331. $this->log('Using gzip output compression');
  332. $gzip = deflate_init(ZLIB_ENCODING_GZIP, ['level' => 9]);
  333. $fp = fopen('php://memory', 'wb');
  334. while (!feof($file['resource'])) {
  335. fwrite($fp, deflate_add($gzip, fread($file['resource'], 8192), ZLIB_NO_FLUSH));
  336. }
  337. fwrite($fp, deflate_add($gzip, '', ZLIB_FINISH));
  338. $length = ftell($fp);
  339. rewind($fp);
  340. fclose($file['resource']);
  341. $file['resource'] = $fp;
  342. unset($fp);
  343. }
  344. if (null !== $length) {
  345. $this->log('Length: %s', $length);
  346. header('Content-Length: ' . $length, true);
  347. }
  348. while (!feof($file['resource']) && ($end === null || $end > 0)) {
  349. $l = $end !== null ? min(8192, $end) : 8192;
  350. echo fread($file['resource'], $l);
  351. flush();
  352. if (null !== $end) {
  353. $end -= 8192;
  354. }
  355. }
  356. fclose($file['resource']);
  357. return null;
  358. }
  359. public function http_copy(string $uri): ?string
  360. {
  361. return $this->_http_copymove($uri, 'copy');
  362. }
  363. public function http_move(string $uri): ?string
  364. {
  365. return $this->_http_copymove($uri, 'move');
  366. }
  367. protected function _http_copymove(string $uri, string $method): ?string
  368. {
  369. $uri = $this->_prefix($uri);
  370. $destination = $_SERVER['HTTP_DESTINATION'] ?? null;
  371. $depth = $_SERVER['HTTP_DEPTH'] ?? 1;
  372. if (!$destination) {
  373. throw new Exception('Destination not supplied', 400);
  374. }
  375. $destination = $this->getURI($destination);
  376. if (trim($destination, '/') == trim($uri, '/')) {
  377. throw new Exception('Cannot move file to itself', 403);
  378. }
  379. $overwrite = ($_SERVER['HTTP_OVERWRITE'] ?? null) == 'T';
  380. // Dolphin is removing the file name when moving to root directory
  381. if (empty($destination)) {
  382. $destination = basename($uri);
  383. }
  384. $this->log('<= Destination: %s', $destination);
  385. $this->log('<= Overwrite: %s (%s)', $overwrite ? 'Yes' : 'No', $_SERVER['HTTP_OVERWRITE'] ?? null);
  386. if (!$overwrite && $this->storage->exists($destination)) {
  387. throw new Exception('File already exists and overwriting is disabled', 412);
  388. }
  389. if ($method == 'move') {
  390. $this->checkLock($uri);
  391. }
  392. $this->checkLock($destination);
  393. // Moving/copy of directory to an existing destination and depth=0
  394. // should do just nothing, see 'depth_zero_copy' test in litmus
  395. if ($depth == 0
  396. && $this->storage->exists($destination)
  397. && current($this->storage->properties($destination, ['DAV::resourcetype'], 0)) == 'collection') {
  398. $overwritten = $this->storage->exists($uri);
  399. }
  400. else {
  401. $overwritten = $this->storage->$method($uri, $destination);
  402. }
  403. if ($method == 'move' && ($token = $this->getLockToken())) {
  404. $this->storage->unlock($uri, $token);
  405. }
  406. http_response_code($overwritten ? 204 : 201);
  407. return null;
  408. }
  409. public function http_mkcol(string $uri): ?string
  410. {
  411. if (!empty($_SERVER['CONTENT_LENGTH'])) {
  412. throw new Exception('Unsupported body for MKCOL', 415);
  413. }
  414. $uri = $this->_prefix($uri);
  415. $this->storage->mkcol($uri);
  416. http_response_code(201);
  417. return null;
  418. }
  419. protected function extractRequestedProperties(string $body): ?array
  420. {
  421. // We only care about properties if the client asked for it
  422. // If not, we consider that the client just requested to get everything
  423. if (!preg_match('!<(?:\w+:)?propfind!', $body)) {
  424. return null;
  425. }
  426. $ns = [];
  427. $dav_ns = null;
  428. $default_ns = null;
  429. if (preg_match('/<propfind[^>]+xmlns="DAV:"/', $body)) {
  430. $default_ns = 'DAV:';
  431. }
  432. preg_match_all('!xmlns:(\w+)\s*=\s*"([^"]+)"!', $body, $match, PREG_SET_ORDER);
  433. // Find all aliased xmlns
  434. foreach ($match as $found) {
  435. $ns[$found[2]] = $found[1];
  436. }
  437. if (isset($ns['DAV:'])) {
  438. $dav_ns = $ns['DAV:'] . ':';
  439. }
  440. $regexp = '/<(' . $dav_ns . 'prop(?!find))[^>]*?>(.*?)<\/\1\s*>/s';
  441. if (!preg_match($regexp, $body, $match)) {
  442. return null;
  443. }
  444. // Find all properties
  445. // Allow for empty namespace, see Litmus FAQ for propnullns
  446. // https://github.com/tolsen/litmus/blob/master/FAQ
  447. preg_match_all('!<([\w-]+)[^>]*xmlns="([^"]*)"|<(?:([\w-]+):)?([\w-]+)!', $match[2], $match, PREG_SET_ORDER);
  448. $properties = [];
  449. foreach ($match as $found) {
  450. if (isset($found[4])) {
  451. $url = array_search($found[3], $ns) ?: $default_ns;
  452. $name = $found[4];
  453. }
  454. else {
  455. $url = $found[2];
  456. $name = $found[1];
  457. }
  458. $properties[$url . ':' . $name] = [
  459. 'name' => $name,
  460. 'ns_alias' => $found[3] ?? null,
  461. 'ns_url' => $url,
  462. ];
  463. }
  464. return $properties;
  465. }
  466. public function http_propfind(string $uri): ?string
  467. {
  468. // We only support depth of 0 and 1
  469. $depth = isset($_SERVER['HTTP_DEPTH']) && empty($_SERVER['HTTP_DEPTH']) ? 0 : 1;
  470. $uri = $this->_prefix($uri);
  471. $body = file_get_contents('php://input');
  472. if (false !== strpos($body, '<!DOCTYPE ')) {
  473. throw new Exception('Invalid XML', 400);
  474. }
  475. $this->log('Requested depth: %s', $depth);
  476. // We don't really care about having a correct XML string,
  477. // but we can get better WebDAV compliance if we do
  478. if (isset($_SERVER['HTTP_X_LITMUS'])) {
  479. if (false !== strpos($body, '<!DOCTYPE ')) {
  480. throw new Exception('Invalid XML', 400);
  481. }
  482. $xml = @simplexml_load_string($body);
  483. if ($e = libxml_get_last_error()) {
  484. throw new Exception('Invalid XML', 400);
  485. }
  486. }
  487. $requested = $this->extractRequestedProperties($body);
  488. $requested_keys = $requested ? array_keys($requested) : null;
  489. // Find root element properties
  490. $properties = $this->storage->properties($uri, $requested_keys, $depth);
  491. if (null === $properties) {
  492. throw new Exception('This does not exist', 404);
  493. }
  494. $items = [$uri => $properties];
  495. if ($depth) {
  496. foreach ($this->storage->list($uri, $requested) as $file => $properties) {
  497. $path = trim($uri . '/' . $file, '/');
  498. $properties = $properties ?? $this->storage->properties($path, $requested_keys, 0);
  499. if (!$properties) {
  500. $this->log('!!! Cannot find "%s"', $path);
  501. continue;
  502. }
  503. $items[$path] = $properties;
  504. }
  505. }
  506. // http_response_code doesn't know the 207 status code
  507. header('HTTP/1.1 207 Multi-Status', true);
  508. $this->dav_header();
  509. header('Content-Type: application/xml; charset=utf-8');
  510. $root_namespaces = [
  511. 'DAV:' => 'd',
  512. // Microsoft Clients need this special namespace for date and time values (from PEAR/WebDAV)
  513. 'urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/' => 'ns0',
  514. ];
  515. $i = 0;
  516. $requested ??= [];
  517. foreach ($requested as $prop) {
  518. if ($prop['ns_url'] == 'DAV:' || !$prop['ns_url']) {
  519. continue;
  520. }
  521. if (!array_key_exists($prop['ns_url'], $root_namespaces)) {
  522. $root_namespaces[$prop['ns_url']] = $prop['ns_alias'] ?: 'rns' . $i++;
  523. }
  524. }
  525. foreach ($items as $properties) {
  526. foreach ($properties as $name => $value) {
  527. $pos = strrpos($name, ':');
  528. $ns = substr($name, 0, strrpos($name, ':'));
  529. // NULL namespace, see Litmus FAQ for propnullns
  530. if (!$ns) {
  531. continue;
  532. }
  533. if (!array_key_exists($ns, $root_namespaces)) {
  534. $root_namespaces[$ns] = 'rns' . $i++;
  535. }
  536. }
  537. }
  538. $out = '<?xml version="1.0" encoding="utf-8"?>';
  539. $out .= '<d:multistatus';
  540. foreach ($root_namespaces as $url => $alias) {
  541. $out .= sprintf(' xmlns:%s="%s"', $alias, $url);
  542. }
  543. $out .= '>';
  544. foreach ($items as $uri => $item) {
  545. $e = '<d:response>';
  546. if ($this->prefix) {
  547. $uri = substr($uri, strlen($this->prefix));
  548. }
  549. $uri = trim(rtrim($this->base_uri, '/') . '/' . ltrim($uri, '/'), '/');
  550. $path = '/' . str_replace('%2F', '/', rawurlencode($uri));
  551. if (($item['DAV::resourcetype'] ?? null) == 'collection' && $path != '/') {
  552. $path .= '/';
  553. }
  554. $e .= sprintf('<d:href>%s</d:href>', htmlspecialchars($path, ENT_XML1));
  555. $e .= '<d:propstat><d:prop>';
  556. foreach ($item as $name => $value) {
  557. if (null === $value) {
  558. continue;
  559. }
  560. $pos = strrpos($name, ':');
  561. $ns = substr($name, 0, strrpos($name, ':'));
  562. $tag_name = substr($name, strrpos($name, ':') + 1);
  563. $alias = $root_namespaces[$ns] ?? null;
  564. $attributes = '';
  565. // The ownCloud Android app doesn't like formatted dates, it makes it crash.
  566. // so force it to have a timestamp
  567. if ($name == 'DAV::creationdate'
  568. && ($value instanceof \DateTimeInterface)
  569. && false !== stripos($_SERVER['HTTP_USER_AGENT'] ?? '', 'owncloud')) {
  570. $value = $value->getTimestamp();
  571. }
  572. // ownCloud app crashes if mimetype is provided for a directory
  573. // https://github.com/owncloud/android/issues/3768
  574. elseif ($name == 'DAV::getcontenttype'
  575. && ($item['DAV::resourcetype'] ?? null) == 'collection') {
  576. $value = null;
  577. }
  578. if ($name == 'DAV::resourcetype' && $value == 'collection') {
  579. $value = '<d:collection />';
  580. }
  581. elseif ($name == 'DAV::getetag' && strlen($value) && $value[0] != '"') {
  582. $value = '"' . $value . '"';
  583. }
  584. elseif ($value instanceof \DateTimeInterface) {
  585. // Change value to GMT
  586. $value = clone $value;
  587. $value->setTimezone(new \DateTimeZone('GMT'));
  588. $value = $value->format(DATE_RFC7231);
  589. }
  590. elseif (is_array($value)) {
  591. $attributes = $value['attributes'] ?? '';
  592. $value = $value['xml'] ?? null;
  593. }
  594. else {
  595. $value = htmlspecialchars($value, ENT_XML1);
  596. }
  597. // NULL namespace, see Litmus FAQ for propnullns
  598. if (!$ns) {
  599. $attributes .= ' xmlns=""';
  600. }
  601. else {
  602. $tag_name = $alias . ':' . $tag_name;
  603. }
  604. if (null === $value || self::EMPTY_PROP_VALUE === $value) {
  605. $e .= sprintf('<%s%s />', $tag_name, $attributes ? ' ' . $attributes : '');
  606. }
  607. else {
  608. $e .= sprintf('<%s%s>%s</%1$s>', $tag_name, $attributes ? ' ' . $attributes : '', $value);
  609. }
  610. }
  611. $e .= '</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>' . "\n";
  612. // Append missing properties
  613. if (!empty($requested)) {
  614. $missing_properties = array_diff($requested_keys, array_keys($item));
  615. if (count($missing_properties)) {
  616. $e .= '<d:propstat><d:prop>';
  617. foreach ($missing_properties as $name) {
  618. $pos = strrpos($name, ':');
  619. $ns = substr($name, 0, strrpos($name, ':'));
  620. $name = substr($name, strrpos($name, ':') + 1);
  621. $alias = $root_namespaces[$ns] ?? null;
  622. // NULL namespace, see Litmus FAQ for propnullns
  623. if (!$alias) {
  624. $e .= sprintf('<%s xmlns="" />', $name);
  625. }
  626. else {
  627. $e .= sprintf('<%s:%s />', $alias, $name);
  628. }
  629. }
  630. $e .= '</d:prop><d:status>HTTP/1.1 404 Not Found</d:status></d:propstat>';
  631. }
  632. }
  633. $e .= '</d:response>' . "\n";
  634. $out .= $e;
  635. }
  636. $out .= '</d:multistatus>';
  637. return $out;
  638. }
  639. static public function parsePropPatch(string $body): array
  640. {
  641. if (false !== strpos($body, '<!DOCTYPE ')) {
  642. throw new Exception('Invalid XML', 400);
  643. }
  644. $xml = @simplexml_load_string($body);
  645. if (false === $xml) {
  646. throw new WebDAV_Exception('Invalid XML', 400);
  647. }
  648. $_ns = null;
  649. // Select correct namespace if required
  650. if (!empty(key($xml->getDocNameSpaces()))) {
  651. $_ns = 'DAV:';
  652. }
  653. $out = [];
  654. // Process set/remove instructions in order (important)
  655. foreach ($xml->children($_ns) as $child) {
  656. foreach ($child->children($_ns) as $prop) {
  657. $prop = $prop->children();
  658. if ($child->getName() == 'set') {
  659. $ns = $prop->getNamespaces(true);
  660. $ns = array_flip($ns);
  661. $name = key($ns) . ':' . $prop->getName();
  662. $attributes = $prop->attributes();
  663. $attributes = $attributes === null ? null : iterator_to_array($attributes);
  664. foreach ($ns as $xmlns => $alias) {
  665. foreach (iterator_to_array($prop->attributes($alias)) as $key => $v) {
  666. $attributes[$xmlns . ':' . $key] = $value;
  667. }
  668. }
  669. if ($prop->count() > 1) {
  670. $text = '';
  671. foreach ($prop->children() as $c) {
  672. $text .= $c->asXML();
  673. }
  674. }
  675. else {
  676. $text = (string)$prop;
  677. }
  678. $out[$name] = ['action' => 'set', 'attributes' => $attributes ?: null, 'content' => $text ?: null];
  679. }
  680. else {
  681. $ns = $prop->getNamespaces();
  682. $name = current($ns) . ':' . $prop->getName();
  683. $out[$name] = ['action' => 'remove'];
  684. }
  685. }
  686. }
  687. return $out;
  688. }
  689. public function http_proppatch(string $uri): ?string
  690. {
  691. $uri = $this->_prefix($uri);
  692. $this->checkLock($uri);
  693. $body = file_get_contents('php://input');
  694. $this->storage->setProperties($uri, $body);
  695. // http_response_code doesn't know the 207 status code
  696. header('HTTP/1.1 207 Multi-Status', true);
  697. header('Content-Type: application/xml; charset=utf-8');
  698. $out = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
  699. $out .= '<d:multistatus xmlns:d="DAV:">';
  700. $out .= '</d:multistatus>';
  701. return $out;
  702. }
  703. public function http_lock(string $uri): ?string
  704. {
  705. $uri = $this->_prefix($uri);
  706. // We don't use this currently, but maybe later?
  707. //$depth = !empty($this->_SERVER['HTTP_DEPTH']) ? 1 : 0;
  708. //$timeout = isset($_SERVER['HTTP_TIMEOUT']) ? explode(',', $_SERVER['HTTP_TIMEOUT']) : [];
  709. //$timeout = array_map('trim', $timeout);
  710. if (empty($_SERVER['CONTENT_LENGTH']) && !empty($_SERVER['HTTP_IF'])) {
  711. $token = $this->getLockToken();
  712. if (!$token) {
  713. throw new Exception('Invalid If header', 400);
  714. }
  715. $info = null;
  716. $ns = 'D';
  717. $scope = self::EXCLUSIVE_LOCK;
  718. $this->checkLock($uri, $token);
  719. $this->log('Requesting LOCK refresh: %s = %s', $uri, $scope);
  720. }
  721. else {
  722. $locked_scope = $this->storage->getLock($uri);
  723. if ($locked_scope == self::EXCLUSIVE_LOCK) {
  724. throw new Exception('Cannot acquire another lock, resource is locked for exclusive use', 423);
  725. }
  726. if ($locked_scope && $token = $this->getLockToken()) {
  727. $token = $this->getLockToken();
  728. if (!$token) {
  729. throw new Exception('Missing lock token', 423);
  730. }
  731. $this->checkLock($uri, $token);
  732. }
  733. $xml = file_get_contents('php://input');
  734. if (!preg_match('!<((?:(\w+):)?lockinfo)[^>]*>(.*?)</\1>!is', $xml, $match)) {
  735. throw new Exception('Invalid XML', 400);
  736. }
  737. $ns = $match[2];
  738. $info = $match[3];
  739. // Quick and dirty UUID
  740. $uuid = random_bytes(16);
  741. $uuid[6] = chr(ord($uuid[6]) & 0x0f | 0x40); // set version to 0100
  742. $uuid[8] = chr(ord($uuid[8]) & 0x3f | 0x80); // set bits 6-7 to 10
  743. $uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($uuid), 4));
  744. $token = 'opaquelocktoken:' . $uuid;
  745. $scope = false !== stripos($info, sprintf('<%sexclusive', $ns ? $ns . ':' : '')) ? self::EXCLUSIVE_LOCK : self::SHARED_LOCK;
  746. $this->log('Requesting LOCK: %s = %s', $uri, $scope);
  747. }
  748. $this->storage->lock($uri, $token, $scope);
  749. $timeout = 60*5;
  750. $info = sprintf('
  751. <d:lockscope><d:%s /></d:lockscope>
  752. <d:locktype><d:write /></d:locktype>
  753. <d:owner>unknown</d:owner>
  754. <d:depth>%d</d:depth>
  755. <d:timeout>Second-%d</d:timeout>
  756. <d:locktoken><d:href>%s</d:href></d:locktoken>
  757. ', $scope, 1, $timeout, $token);
  758. http_response_code(200);
  759. header('Content-Type: application/xml; charset=utf-8');
  760. header(sprintf('Lock-Token: <%s>', $token));
  761. $out = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
  762. $out .= '<d:prop xmlns:d="DAV:">';
  763. $out .= '<d:lockdiscovery><d:activelock>';
  764. $out .= $info;
  765. $out .= '</d:activelock></d:lockdiscovery></d:prop>';
  766. if ($ns != 'D') {
  767. $out = str_replace('D:', $ns ? $ns . ':' : '', $out);
  768. $out = str_replace('xmlns:D', $ns ? 'xmlns:' . $ns : 'xmlns', $out);
  769. }
  770. return $out;
  771. }
  772. public function http_unlock(string $uri): ?string
  773. {
  774. $uri = $this->_prefix($uri);
  775. $token = $this->getLockToken();
  776. if (!$token) {
  777. throw new Exception('Invalid Lock-Token header', 400);
  778. }
  779. $this->log('<= Lock Token: %s', $token);
  780. $this->checkLock($uri, $token);
  781. $this->storage->unlock($uri, $token);
  782. http_response_code(204);
  783. return null;
  784. }
  785. protected function getLockToken(): ?string
  786. {
  787. if (isset($_SERVER['HTTP_LOCK_TOKEN'])
  788. && preg_match('/<(.*?)>/', trim($_SERVER['HTTP_LOCK_TOKEN']), $match)) {
  789. return $match[1];
  790. }
  791. elseif (isset($_SERVER['HTTP_IF'])
  792. && preg_match('/\(<(.*?)>\)/', trim($_SERVER['HTTP_IF']), $match)) {
  793. return $match[1];
  794. }
  795. else {
  796. return null;
  797. }
  798. }
  799. protected function checkLock(string $uri, ?string $token = null): void
  800. {
  801. if ($token === null) {
  802. $token = $this->getLockToken();
  803. }
  804. // Trying to access using a parent directory
  805. if (isset($_SERVER['HTTP_IF'])
  806. && preg_match('/<([^>]+)>\s*\(<[^>]*>\)/', $_SERVER['HTTP_IF'], $match)) {
  807. $root = $this->getURI($match[1]);
  808. if (0 !== strpos($uri, $root)) {
  809. throw new Exception('Invalid "If" header path: ' . $root, 400);
  810. }
  811. $uri = $root;
  812. }
  813. // Try to validate token
  814. elseif (isset($_SERVER['HTTP_IF'])
  815. && preg_match('/\(<([^>]*)>\s+\["([^""]+)"\]\)/', $_SERVER['HTTP_IF'], $match)) {
  816. $token = $match[1];
  817. $request_etag = $match[2];
  818. $etag = current($this->storage->properties($uri, ['DAV::getetag'], 0));
  819. if ($request_etag != $etag) {
  820. throw new Exception('Resource is locked and etag does not match', 412);
  821. }
  822. }
  823. if ($token == 'DAV:no-lock') {
  824. throw new Exception('Resource is locked', 412);
  825. }
  826. // Token is valid
  827. if ($token && $this->storage->getLock($uri, $token)) {
  828. return;
  829. }
  830. elseif ($token) {
  831. throw new Exception('Invalid token', 400);
  832. }
  833. // Resource is locked
  834. elseif ($this->storage->getLock($uri)) {
  835. throw new Exception('Resource is locked', 423);
  836. }
  837. }
  838. protected function dav_header()
  839. {
  840. header('DAV: 1, 2, 3');
  841. }
  842. public function http_options(): void
  843. {
  844. http_response_code(200);
  845. $methods = 'GET HEAD PUT DELETE COPY MOVE PROPFIND MKCOL LOCK UNLOCK';
  846. $this->dav_header();
  847. header('Allow: ' . $methods);
  848. header('Content-length: 0');
  849. header('Accept-Ranges: bytes');
  850. header('MS-Author-Via: DAV');
  851. }
  852. public function log(string $message, ...$params)
  853. {
  854. if (PHP_SAPI == 'cli-server') {
  855. file_put_contents('php://stderr', vsprintf($message, $params) . "\n");
  856. }
  857. }
  858. protected function getURI(string $source): string
  859. {
  860. $uri = parse_url($source, PHP_URL_PATH);
  861. $uri = rawurldecode($uri);
  862. $uri = rtrim($uri, '/');
  863. if ($uri . '/' == $this->base_uri) {
  864. $uri .= '/';
  865. }
  866. if (strpos($uri, $this->base_uri) !== 0) {
  867. throw new Exception(sprintf('Invalid URI, "%s" is outside of scope "%s"', $uri, $this->base_uri), 400);
  868. }
  869. $uri = preg_replace('!/{2,}!', '/', $uri);
  870. if (false !== strpos($uri, '..')) {
  871. throw new Exception(sprintf('Invalid URI: "%s"', $uri), 403);
  872. }
  873. $uri = substr($uri, strlen($this->base_uri));
  874. $uri = $this->_prefix($uri);
  875. return $uri;
  876. }
  877. public function route(?string $uri = null): bool
  878. {
  879. if (null === $uri) {
  880. $uri = $_SERVER['REQUEST_URI'] ?? '/';
  881. }
  882. $this->original_uri = $uri;
  883. if ($uri . '/' == $this->base_uri) {
  884. $uri .= '/';
  885. }
  886. if (0 === strpos($uri, $this->base_uri)) {
  887. $uri = substr($uri, strlen($this->base_uri));
  888. }
  889. else {
  890. $this->log('<= %s is not a managed URL', $uri);
  891. return false;
  892. }
  893. // Add some extra-logging for Litmus tests
  894. if (isset($_SERVER['HTTP_X_LITMUS']) || isset($_SERVER['HTTP_X_LITMUS_SECOND'])) {
  895. $this->log('X-Litmus: %s', $_SERVER['HTTP_X_LITMUS'] ?? $_SERVER['HTTP_X_LITMUS_SECOND']);
  896. }
  897. $method = $_SERVER['REQUEST_METHOD'] ?? null;
  898. header_remove('Expires');
  899. header_remove('Pragma');
  900. header_remove('Cache-Control');
  901. header('X-Server: KD2', true);
  902. // Stop and send reply to OPTIONS before anything else
  903. if ($method == 'OPTIONS') {
  904. $this->log('<= OPTIONS');
  905. $this->http_options();
  906. return true;
  907. }
  908. $uri = rawurldecode($uri);
  909. $uri = trim($uri, '/');
  910. $uri = preg_replace('!/{2,}!', '/', $uri);
  911. $this->log('<= %s /%s', $method, $uri);
  912. try {
  913. if (false !== strpos($uri, '..')) {
  914. throw new Exception(sprintf('Invalid URI: "%s"', $uri), 403);
  915. }
  916. // Call 'http_method' class method
  917. $method = 'http_' . strtolower($method);
  918. if (!method_exists($this, $method)) {
  919. throw new Exception('Invalid request method', 405);
  920. }
  921. $out = $this->$method($uri);
  922. $this->log('=> %d', http_response_code());
  923. if (null !== $out) {
  924. $this->log('=> %s', $out);
  925. }
  926. echo $out;
  927. }
  928. catch (Exception $e) {
  929. $this->error($e);
  930. }
  931. return true;
  932. }
  933. function error(Exception $e)
  934. {
  935. $this->log('=> %d - %s', $e->getCode(), $e->getMessage());
  936. if ($e->getCode() == 423) {
  937. // http_response_code doesn't know about 423 Locked
  938. header('HTTP/1.1 423 Locked');
  939. }
  940. else {
  941. http_response_code($e->getCode());
  942. }
  943. header('Content-Type: application/xml; charset=utf-8', true);
  944. printf('<?xml version="1.0" encoding="utf-8"?><d:error xmlns:d="DAV:" xmlns:s="http://sabredav.org/ns"><s:message>%s</s:message></d:error>', htmlspecialchars($e->getMessage(), ENT_XML1));
  945. }
  946. static public function hmac(array $data, string $key = '')
  947. {
  948. // Protect against length attacks by pre-hashing data
  949. $data = array_map('sha1', $data);
  950. $data = implode(':', $data);
  951. return hash_hmac('sha1', $data, sha1($key));
  952. }
  953. }
  954. abstract class AbstractStorage
  955. {
  956. abstract public function get(string $uri): ?array;
  957. abstract public function exists(string $uri): bool;
  958. abstract public function properties(string $uri, ?array $requested_properties, int $depth): ?array;
  959. public function setProperties(string $uri, string $body): void
  960. {
  961. // By default, properties are not saved
  962. }
  963. abstract public function put(string $uri, $pointer, ?string $hash, ?int $mtime): bool;
  964. abstract public function delete(string $uri): void;
  965. abstract public function copy(string $uri, string $destination): bool;
  966. abstract public function move(string $uri, string $destination): bool;
  967. abstract public function mkcol(string $uri): void;
  968. abstract public function list(string $uri, array $properties): iterable;
  969. public function lock(string $uri, string $token, string $scope): void
  970. {
  971. // By default locking is not implemented
  972. }
  973. public function unlock(string $uri, string $token): void
  974. {
  975. // By default locking is not implemented
  976. }
  977. public function getLock(string $uri, ?string $token = null): ?string
  978. {
  979. // By default locking is not implemented, so NULL is always returned
  980. return null;
  981. }
  982. }
  983. }
  984. namespace PicoDAV
  985. {
  986. use KD2\WebDAV\AbstractStorage;
  987. use KD2\WebDAV\Exception as WebDAV_Exception;
  988. class Storage extends AbstractStorage
  989. {
  990. /**
  991. * These file names will be ignored when doing a PUT
  992. * as they are garbage, coming from some OS
  993. */
  994. const PUT_IGNORE_PATTERN = '!^~(?:lock\.|^\._)|^(?:\.DS_Store|Thumbs\.db|desktop\.ini)$!';
  995. protected string $path;
  996. protected ?string $user = null;
  997. public array $users = [];
  998. public function __construct()
  999. {
  1000. $this->path = __DIR__ . '/';
  1001. }
  1002. public function auth(): bool
  1003. {
  1004. if (ANONYMOUS_WRITE && ANONYMOUS_READ) {
  1005. return true;
  1006. }
  1007. if ($this->user) {
  1008. return true;
  1009. }
  1010. $user = $_SERVER['PHP_AUTH_USER'] ?? null;
  1011. $password = $_SERVER['PHP_AUTH_PW'] ?? null;
  1012. $hash = $this->users[$user]['password'] ?? null;
  1013. if (!$hash) {
  1014. return false;
  1015. }
  1016. if (!password_verify($password, $hash)) {
  1017. return false;
  1018. }
  1019. $this->user = $user;
  1020. return true;
  1021. }
  1022. static protected function glob(string $path, string $pattern = '', int $flags = 0): array
  1023. {
  1024. $path = preg_replace('/[\*\?\[\]]/', '\\\\$0', $path);
  1025. return glob($path . $pattern, $flags);
  1026. }
  1027. public function canRead(string $uri): bool
  1028. {
  1029. if (in_array($uri, INTERNAL_FILES)) {
  1030. return false;
  1031. }
  1032. if (preg_match('/\.(?:php\d?|phtml|phps)$|^\./i', $uri)) {
  1033. return false;
  1034. }
  1035. if (ANONYMOUS_READ) {
  1036. return true;
  1037. }
  1038. if (!$this->auth()) {
  1039. return false;
  1040. }
  1041. $restrict = $this->users[$this->user]['restrict'] ?? [];
  1042. if (!is_array($restrict) || empty($restrict)) {
  1043. return true;
  1044. }
  1045. foreach ($restrict as $match) {
  1046. if (0 === strpos($uri, $match)) {
  1047. return true;
  1048. }
  1049. }
  1050. return false;
  1051. }
  1052. public function canWrite(string $uri): bool
  1053. {
  1054. if (!$this->auth() && !ANONYMOUS_WRITE) {
  1055. return false;
  1056. }
  1057. if (!$this->canRead($uri)) {
  1058. return false;
  1059. }
  1060. if (ANONYMOUS_WRITE) {
  1061. return true;
  1062. }
  1063. if (!$this->auth() || empty($this->users[$this->user]['write'])) {
  1064. return false;
  1065. }
  1066. $restrict = $this->users[$this->user]['restrict_write'] ?? [];
  1067. if (!is_array($restrict) || empty($restrict)) {
  1068. return true;
  1069. }
  1070. foreach ($restrict as $match) {
  1071. if (0 === strpos($uri, $match)) {
  1072. return true;
  1073. }
  1074. }
  1075. return false;
  1076. }
  1077. public function canOnlyCreate(string $uri): bool
  1078. {
  1079. $restrict = $this->users[$this->user]['restrict_write'] ?? [];
  1080. if (in_array($uri, $restrict, true)) {
  1081. return true;
  1082. }
  1083. $restrict = $this->users[$this->user]['restrict'] ?? [];
  1084. if (in_array($uri, $restrict, true)) {
  1085. return true;
  1086. }
  1087. return false;
  1088. }
  1089. public function list(string $uri, ?array $properties): iterable
  1090. {
  1091. if (!$this->canRead($uri . '/')) {
  1092. //throw new WebDAV_Exception('Access forbidden', 403);
  1093. }
  1094. $dirs = self::glob($this->path . $uri, '/*', \GLOB_ONLYDIR);
  1095. $dirs = array_map('basename', $dirs);
  1096. $dirs = array_filter($dirs, fn($a) => $this->canRead(ltrim($uri . '/' . $a, '/') . '/'));
  1097. natcasesort($dirs);
  1098. $files = self::glob($this->path . $uri, '/*');
  1099. $files = array_map('basename', $files);
  1100. $files = array_diff($files, $dirs);
  1101. // Remove PHP files and dot-files from listings
  1102. $files = array_filter($files, fn($a) => $this->canRead(ltrim($uri . '/' . $a, '/')));
  1103. natcasesort($files);
  1104. $files = array_flip(array_merge($dirs, $files));
  1105. $files = array_map(fn($a) => null, $files);
  1106. return $files;
  1107. }
  1108. public function get(string $uri): ?array
  1109. {
  1110. if (!$this->canRead($uri)) {
  1111. throw new WebDAV_Exception('Access forbidden', 403);
  1112. }
  1113. $path = $this->path . $uri;
  1114. if (!file_exists($path)) {
  1115. return null;
  1116. }
  1117. return ['path' => $path];
  1118. }
  1119. public function exists(string $uri): bool
  1120. {
  1121. return file_exists($this->path . $uri);
  1122. }
  1123. public function get_file_property(string $uri, string $name, int $depth)
  1124. {
  1125. $target = $this->path . $uri;
  1126. switch ($name) {
  1127. case 'DAV::getcontentlength':
  1128. return is_dir($target) ? null : filesize($target);
  1129. case 'DAV::getcontenttype':
  1130. // ownCloud app crashes if mimetype is provided for a directory
  1131. // https://github.com/owncloud/android/issues/3768
  1132. return is_dir($target) ? null : mime_content_type($target);
  1133. case 'DAV::resourcetype':
  1134. return is_dir($target) ? 'collection' : '';
  1135. case 'DAV::getlastmodified':
  1136. if (!$uri && $depth == 0 && is_dir($target)) {
  1137. $mtime = self::getDirectoryMTime($target);
  1138. }
  1139. else {
  1140. $mtime = filemtime($target);
  1141. }
  1142. if (!$mtime) {
  1143. return null;
  1144. }
  1145. return new \DateTime('@' . $mtime);
  1146. case 'DAV::ishidden':
  1147. return basename($target)[0] == '.';
  1148. case 'DAV::getetag':
  1149. $hash = filemtime($target) . filesize($target);
  1150. return md5($hash . $target);
  1151. case 'DAV::lastaccessed':
  1152. return new \DateTime('@' . fileatime($target));
  1153. case 'DAV::creationdate':
  1154. return new \DateTime('@' . filectime($target));
  1155. case 'http://owncloud.org/ns:permissions':
  1156. $permissions = 'G';
  1157. if (is_dir($target)) {
  1158. $uri .= '/';
  1159. }
  1160. if (is_writeable($target) && $this->canWrite($uri)) {
  1161. // If the directory is one of the restricted paths,
  1162. // then we can only do stuff INSIDE, and not delete/rename the directory itself
  1163. if ($this->canOnlyCreate($uri)) {
  1164. $permissions .= 'CK';
  1165. }
  1166. else {
  1167. $permissions .= 'DNVWCK';
  1168. }
  1169. }
  1170. return $permissions;
  1171. case Server::PROP_DIGEST_MD5:
  1172. if (!is_file($target)) {
  1173. return null;
  1174. }
  1175. return md5_file($target);
  1176. default:
  1177. break;
  1178. }
  1179. return null;
  1180. }
  1181. public function properties(string $uri, ?array $properties, int $depth): ?array
  1182. {
  1183. $target = $this->path . $uri;
  1184. if (!file_exists($target)) {
  1185. return null;
  1186. }
  1187. if (null === $properties) {
  1188. $properties = WebDAV::BASIC_PROPERTIES;
  1189. }
  1190. $out = [];
  1191. foreach ($properties as $name) {
  1192. $v = $this->get_file_property($uri, $name, $depth);
  1193. if (null !== $v) {
  1194. $out[$name] = $v;
  1195. }
  1196. }
  1197. return $out;
  1198. }
  1199. public function put(string $uri, $pointer, ?string $hash, ?int $mtime): bool
  1200. {
  1201. if (preg_match(self::PUT_IGNORE_PATTERN, basename($uri))) {
  1202. return false;
  1203. }
  1204. if (!$this->canWrite($uri)) {
  1205. throw new WebDAV_Exception('Access forbidden', 403);
  1206. }
  1207. $target = $this->path . $uri;
  1208. $parent = dirname($target);
  1209. if (is_dir($target)) {
  1210. throw new WebDAV_Exception('Target is a directory', 409);
  1211. }
  1212. if (!file_exists($parent)) {
  1213. mkdir($parent, 0770, true);
  1214. }
  1215. $new = !file_exists($target);
  1216. $delete = false;
  1217. $size = 0;
  1218. $quota = disk_free_space($this->path);
  1219. $tmp_file = '.tmp.' . sha1($target);
  1220. $out = fopen($tmp_file, 'w');
  1221. while (!feof($pointer)) {
  1222. $bytes = fread($pointer, 8192);
  1223. $size += strlen($bytes);
  1224. if ($size > $quota) {
  1225. $delete = true;
  1226. break;
  1227. }
  1228. fwrite($out, $bytes);
  1229. }
  1230. fclose($out);
  1231. fclose($pointer);
  1232. if ($delete) {
  1233. @unlink($tmp_file);
  1234. throw new WebDAV_Exception('Your quota is exhausted', 403);
  1235. }
  1236. elseif ($hash && md5_file($tmp_file) != $hash) {
  1237. @unlink($tmp_file);
  1238. throw new WebDAV_Exception('The data sent does not match the supplied MD5 hash', 400);
  1239. }
  1240. else {
  1241. rename($tmp_file, $target);
  1242. }
  1243. if ($mtime) {
  1244. @touch($target, $mtime);
  1245. }
  1246. return $new;
  1247. }
  1248. public function delete(string $uri): void
  1249. {
  1250. if (!$this->canWrite($uri)) {
  1251. throw new WebDAV_Exception('Access forbidden', 403);
  1252. }
  1253. if ($this->canOnlyCreate($uri)) {
  1254. throw new WebDAV_Exception('Access forbidden', 403);
  1255. }
  1256. $target = $this->path . $uri;
  1257. if (!file_exists($target)) {
  1258. throw new WebDAV_Exception('Target does not exist', 404);
  1259. }
  1260. if (!is_writeable($target)) {
  1261. throw new WebDAV_Exception('File permissions says that you cannot delete this, sorry.', 403);
  1262. }
  1263. if (is_dir($target)) {
  1264. foreach (self::glob($target, '/*') as $file) {
  1265. $this->delete(substr($file, strlen($this->path)));
  1266. }
  1267. rmdir($target);
  1268. }
  1269. else {
  1270. unlink($target);
  1271. }
  1272. }
  1273. public function copymove(bool $move, string $uri, string $destination): bool
  1274. {
  1275. if (!$this->canWrite($uri)
  1276. || !$this->canWrite($destination)
  1277. || $this->canOnlyCreate($uri)) {
  1278. throw new WebDAV_Exception('Access forbidden', 403);
  1279. }
  1280. $source = $this->path . $uri;
  1281. $target = $this->path . $destination;
  1282. $parent = dirname($target);
  1283. if (!file_exists($source)) {
  1284. throw new WebDAV_Exception('File not found', 404);
  1285. }
  1286. $overwritten = file_exists($target);
  1287. if (!is_dir($parent)) {
  1288. throw new WebDAV_Exception('Target parent directory does not exist', 409);
  1289. }
  1290. if (false === $move) {
  1291. $quota = disk_free_space($this->path);
  1292. if (filesize($source) > $quota) {
  1293. throw new WebDAV_Exception('Your quota is exhausted', 403);
  1294. }
  1295. }
  1296. if ($overwritten) {
  1297. $this->delete($destination);
  1298. }
  1299. $method = $move ? 'rename' : 'copy';
  1300. if ($method == 'copy' && is_dir($source)) {
  1301. @mkdir($target, 0770, true);
  1302. foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST) as $item)
  1303. {
  1304. if ($item->isDir()) {
  1305. @mkdir($target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  1306. } else {
  1307. copy($item, $target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  1308. }
  1309. }
  1310. }
  1311. else {
  1312. $method($source, $target);
  1313. $this->getResourceProperties($uri)->move($destination);
  1314. }
  1315. return $overwritten;
  1316. }
  1317. public function copy(string $uri, string $destination): bool
  1318. {
  1319. return $this->copymove(false, $uri, $destination);
  1320. }
  1321. public function move(string $uri, string $destination): bool
  1322. {
  1323. return $this->copymove(true, $uri, $destination);
  1324. }
  1325. public function mkcol(string $uri): void
  1326. {
  1327. if (!$this->canWrite($uri)) {
  1328. throw new WebDAV_Exception('Access forbidden', 403);
  1329. }
  1330. if (!disk_free_space($this->path)) {
  1331. throw new WebDAV_Exception('Your quota is exhausted', 403);
  1332. }
  1333. $target = $this->path . $uri;
  1334. $parent = dirname($target);
  1335. if (file_exists($target)) {
  1336. throw new WebDAV_Exception('There is already a file with that name', 405);
  1337. }
  1338. if (!file_exists($parent)) {
  1339. throw new WebDAV_Exception('The parent directory does not exist', 409);
  1340. }
  1341. mkdir($target, 0770);
  1342. }
  1343. static public function getDirectoryMTime(string $path): int
  1344. {
  1345. $last = 0;
  1346. $path = rtrim($path, '/');
  1347. foreach (self::glob($path, '/*', GLOB_NOSORT) as $f) {
  1348. if (is_dir($f)) {
  1349. $m = self::getDirectoryMTime($f);
  1350. if ($m > $last) {
  1351. $last = $m;
  1352. }
  1353. }
  1354. $m = filemtime($f);
  1355. if ($m > $last) {
  1356. $last = $m;
  1357. }
  1358. }
  1359. return $last;
  1360. }
  1361. }
  1362. class Server extends \KD2\WebDAV\Server
  1363. {
  1364. protected function html_directory(string $uri, iterable $list): ?string
  1365. {
  1366. $out = parent::html_directory($uri, $list);
  1367. if (null !== $out) {
  1368. $out = str_replace('<body>', sprintf('<body style="opacity: 0"><script type="text/javascript" src="%s/.webdav/webdav.js"></script>', rtrim($this->base_uri, '/')), $out);
  1369. }
  1370. return $out;
  1371. }
  1372. function error(WebDAV_Exception $e)
  1373. {
  1374. if ($e->getCode() == 403 && !$this->storage->auth() && count($this->storage->users)) {
  1375. $user = $_SERVER['PHP_AUTH_USER'] ?? null;
  1376. http_response_code(401);
  1377. header('WWW-Authenticate: Basic realm="Please login"');
  1378. echo '<h2>Error 401</h2><h1>You need to login to access this.</h1>';
  1379. return;
  1380. }
  1381. parent::error($e);
  1382. }
  1383. }
  1384. }
  1385. namespace {
  1386. use PicoDAV\Server;
  1387. use PicoDAV\Storage;
  1388. $uri = strtok($_SERVER['REQUEST_URI'], '?');
  1389. $root = substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));
  1390. if (false !== strpos($uri, '..')) {
  1391. http_response_code(404);
  1392. die('Invalid URL');
  1393. }
  1394. $relative_uri = ltrim(substr($uri, strlen($root)), '/');
  1395. if (!empty($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'apache') && !file_exists(__DIR__ . '/.htaccess')) {
  1396. file_put_contents(__DIR__ . '/.htaccess', 'DirectoryIndex disabled
  1397. RedirectMatch 404 \\.picodav\\.ini
  1398. RewriteEngine On
  1399. RewriteBase /
  1400. # Uncomment the following 2 lignes to make things a bit faster for
  1401. # downloading files, AND you don\'t use PicoDAV users to manage access,
  1402. # but a regular .htpasswd file and config for your web server.
  1403. #RewriteCond %{REQUEST_FILENAME} !-f [OR]
  1404. #RewriteCond %{REQUEST_METHOD} !GET
  1405. RewriteRule ^.*$ /index.php [END]
  1406. ');
  1407. }
  1408. if ($relative_uri == '.webdav/webdav.js' || $relative_uri == '.webdav/webdav.css') {
  1409. http_response_code(200);
  1410. if ($relative_uri == '.webdav/webdav.js') {
  1411. header('Content-Type: text/javascript', true);
  1412. }
  1413. else {
  1414. header('Content-Type: text/css', true);
  1415. }
  1416. $seconds_to_cache = 3600 * 24 * 5;
  1417. $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  1418. header("Expires: " . $ts);
  1419. header("Pragma: cache");
  1420. header("Cache-Control: max-age=" . $seconds_to_cache);
  1421. $fp = fopen(__FILE__, 'r');
  1422. if ($relative_uri == '.webdav/webdav.js') {
  1423. fseek($fp, 49803, SEEK_SET);
  1424. echo fread($fp, 27769);
  1425. }
  1426. else {
  1427. fseek($fp, 49803 + 27769, SEEK_SET);
  1428. echo fread($fp, 6988);
  1429. }
  1430. fclose($fp);
  1431. exit;
  1432. }
  1433. const CONFIG_FILE = __DIR__ . '/.picodav.ini';
  1434. define('PicoDAV\INTERNAL_FILES', ['.picodav.ini', basename(__FILE__), '.webdav/webdav.js', '.webdav/webdav.css']);
  1435. const DEFAULT_CONFIG = [
  1436. 'ANONYMOUS_READ' => true,
  1437. 'ANONYMOUS_WRITE' => false,
  1438. ];
  1439. $config = [];
  1440. $storage = new Storage;
  1441. if (file_exists(CONFIG_FILE)) {
  1442. $config = parse_ini_file(CONFIG_FILE, true);
  1443. $users = array_filter($config, 'is_array');
  1444. $config = array_diff_key($config, $users);
  1445. $config = array_change_key_case($config, \CASE_UPPER);
  1446. $replace = [];
  1447. // Encrypt plaintext passwords
  1448. foreach ($users as $name => $properties) {
  1449. if (isset($properties['password']) && substr($properties['password'], 0, 1) != '$') {
  1450. $users[$name]['password'] = $replace[$name] = password_hash($properties['password'], null);
  1451. }
  1452. }
  1453. if (count($replace)) {
  1454. $lines = file(CONFIG_FILE);
  1455. $current = null;
  1456. foreach ($lines as &$line) {
  1457. if (preg_match('/^\s*\[(\w+)\]\s*$/', $line, $match)) {
  1458. $current = $match[1];
  1459. continue;
  1460. }
  1461. if ($current && isset($replace[$current]) && preg_match('/^\s*password\s*=/', $line)) {
  1462. $line = sprintf("password = %s\n", var_export($replace[$current], true));
  1463. }
  1464. }
  1465. unset($line, $current);
  1466. file_put_contents(CONFIG_FILE, implode('', $lines));
  1467. }
  1468. $storage->users = $users;
  1469. }
  1470. foreach (DEFAULT_CONFIG as $key => $value) {
  1471. if (array_key_exists($key, $config)) {
  1472. $value = $config[$key];
  1473. }
  1474. if (is_bool(DEFAULT_CONFIG[$key])) {
  1475. $value = boolval($value);
  1476. }
  1477. define('PicoDAV\\' . $key, $value);
  1478. }
  1479. $dav = new Server;
  1480. $dav->setStorage($storage);
  1481. $dav->setBaseURI($root);
  1482. if (!$dav->route($uri)) {
  1483. http_response_code(404);
  1484. die('Invalid URL, sorry');
  1485. }
  1486. exit;
  1487. ?>
  1488. var css_url = document.currentScript.src.replace(/\/[^\/]+$/, '') + '/webdav.css';
  1489. const WebDAVNavigator = (url, options) => {
  1490. // Microdown
  1491. // https://github.com/commit-intl/micro-down
  1492. const microdown=function(){function l(n,e,r){return"<"+n+(r?" "+Object.keys(r).map(function(n){return r[n]?n+'="'+(a(r[n])||"")+'"':""}).join(" "):"")+">"+e+"</"+n+">"}function c(n,e){return e=n.match(/^[+-]/m)?"ul":"ol",n?"<"+e+">"+n.replace(/(?:[+-]|\d+\.) +(.*)\n?(([ \t].*\n?)*)/g,function(n,e,r){return"<li>"+g(e+"\n"+(t=r||"").replace(new RegExp("^"+(t.match(/^\s+/)||"")[0],"gm"),"").replace(o,c))+"</li>";var t})+"</"+e+">":""}function e(r,t,u,c){return function(n,e){return n=n.replace(t,u),l(r,c?c(n):n)}}function t(n,u){return f(n,[/<!--((.|\n)*?)-->/g,"\x3c!--$1--\x3e",/^("""|```)(.*)\n((.*\n)*?)\1/gm,function(n,e,r,t){return'"""'===e?l("div",p(t,u),{class:r}):u&&u.preCode?l("pre",l("code",a(t),{class:r})):l("pre",a(t),{class:r})},/(^>.*\n?)+/gm,e("blockquote",/^> ?(.*)$/gm,"$1",r),/((^|\n)\|.+)+/g,e("table",/^.*(\n\|---.*?)?$/gm,function(n,t){return e("tr",/\|(-?)([^|]*)\1(\|$)?/gm,function(n,e,r){return l(e||t?"th":"td",g(r))})(n.slice(0,n.length-(t||"").length))}),o,c,/#\[([^\]]+?)]/g,'<a name="$1"></a>',/^(#+) +(.*)(?:$)/gm,function(n,e,r){return l("h"+e.length,g(r))},/^(===+|---+)(?=\s*$)/gm,"<hr>"],p,u)}var i=this,a=function(n){return n?n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""},o=/(?:(^|\n)([+-]|\d+\.) +(.*(\n[ \t]+.*)*))+/g,g=function c(n,i){var o=[];return n=(n||"").trim().replace(/`([^`]*)`/g,function(n,e){return"\\"+o.push(l("code",a(e)))}).replace(/[!&]?\[([!&]?\[.*?\)|[^\]]*?)]\((.*?)( .*?)?\)|(\w+:\/\/[$\-.+!*'()/,\w]+)/g,function(n,e,r,t,u){return u?i?n:"\\"+o.push(l("a",u,{href:u})):"&"==n[0]?(e=e.match(/^(.+),(.+),([^ \]]+)( ?.+?)?$/),"\\"+o.push(l("iframe","",{width:e[1],height:e[2],frameborder:e[3],class:e[4],src:r,title:t}))):"\\"+o.push("!"==n[0]?l("img","",{src:r,alt:e,title:t}):l("a",c(e,1),{href:r,title:t}))}),n=function r(n){return n.replace(/\\(\d+)/g,function(n,e){return r(o[Number.parseInt(e)-1])})}(i?n:r(n))},r=function t(n){return f(n,[/([*_]{1,3})((.|\n)+?)\1/g,function(n,e,r){return e=e.length,r=t(r),1<e&&(r=l("strong",r)),e%2&&(r=l("em",r)),r},/(~{1,3})((.|\n)+?)\1/g,function(n,e,r){return l([,"u","s","del"][e.length],t(r))},/ \n|\n /g,"<br>"],t)},f=function(n,e,r,t){for(var u,c=0;c<e.length;){if(u=e[c++].exec(n))return r(n.slice(0,u.index),t)+("string"==typeof e[c]?e[c].replace(/\$(\d)/g,function(n,e){return u[e]}):e[c].apply(i,u))+r(n.slice(u.index+u[0].length),t);c++}return n},p=function(n,e){n=n.replace(/[\r\v\b\f]/g,"").replace(/\\./g,function(n){return"&#"+n.charCodeAt(1)+";"});var r=t(n,e);return r!==n||r.match(/^[\s\n]*$/i)||(r=g(r).replace(/((.|\n)+?)(\n\n+|$)/g,function(n,e){return l("p",e)})),r.replace(/&#(\d+);/g,function(n,e){return String.fromCharCode(parseInt(e))})};return{parse:p,block:t,inline:r,inlineBlock:g}}();
  1493. const PREVIEW_TYPES = /^image\/(png|webp|svg|jpeg|jpg|gif|png)|^application\/pdf|^text\/|^audio\/|^video\//;
  1494. const _ = key => typeof lang_strings != 'undefined' && key in lang_strings ? lang_strings[key] : key;
  1495. const rename_button = `<input class="rename" type="button" value="${_('Rename')}" />`;
  1496. const delete_button = `<input class="delete" type="button" value="${_('Delete')}" />`;
  1497. const edit_button = `<input class="edit" type="button" value="${_('Edit')}" />`;
  1498. const mkdir_dialog = `<input type="text" name="mkdir" placeholder="${_('Directory name')}" />`;
  1499. const mkfile_dialog = `<input type="text" name="mkfile" placeholder="${_('File name')}" />`;
  1500. const rename_dialog = `<input type="text" name="rename" placeholder="${_('New file name')}" />`;
  1501. const paste_upload_dialog = `<h3>Upload this file?</h3><input type="text" name="paste_name" placeholder="${_('New file name')}" />`;
  1502. const edit_dialog = `<textarea name="edit" cols="70" rows="30"></textarea>`;
  1503. const markdown_dialog = `<div id="mdp"><textarea name="edit" cols="70" rows="30"></textarea><div id="md"></div></div>`;
  1504. const delete_dialog = `<h3>${_('Confirm delete?')}</h3>`;
  1505. const wopi_dialog = `<iframe id="wopi_frame" name="wopi_frame" allowfullscreen="true" allow="autoplay camera microphone display-capture"
  1506. sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation allow-popups-to-escape-sandbox allow-downloads allow-modals">
  1507. </iframe>`;
  1508. const dialog_tpl = `<dialog open><p class="close"><input type="button" value="&#x2716; ${_('Close')}" class="close" /></p><form><div>%s</div>%b</form></dialog>`;
  1509. const html_tpl = `<!DOCTYPE html><html>
  1510. <head><title>Files</title><link rel="stylesheet" type="text/css" href="${css_url}" /></head>
  1511. <body><main></main><div class="bg"></div></body></html>`;
  1512. const body_tpl = `<h1>%title%</h1>
  1513. <div class="upload">
  1514. <select class="sortorder btn">
  1515. <option value="name">${_('Sort by name')}</option>
  1516. <option value="date">${_('Sort by date')}</option>
  1517. <option value="size">${_('Sort by size')}</option>
  1518. </select>
  1519. <input type="button" class="download_all" value="${_('Download all files')}" />
  1520. </div>
  1521. <table>%table%</table>`;
  1522. const create_buttons = `<input class="mkdir" type="button" value="${_('New directory')}" />
  1523. <input type="file" style="display: none;" />
  1524. <input class="mkfile" type="button" value="${_('New text file')}" />
  1525. <input class="uploadfile" type="button" value="${_('Upload file')}" />`;
  1526. const dir_row_tpl = `<tr data-permissions="%permissions%"><td class="thumb"><span class="icon dir"><b>%icon%</b></span></td><th colspan="2"><a href="%uri%">%name%</a></th><td>%modified%</td><td class="buttons"><div></div></td></tr>`;
  1527. const file_row_tpl = `<tr data-permissions="%permissions%" data-mime="%mime%" data-size="%size%"><td class="thumb"><span class="icon %icon%"><b>%icon%</b></span></td><th><a href="%uri%">%name%</a></th><td class="size">%size_bytes%</td><td>%modified%</td><td class="buttons"><div><a href="%uri%" download class="btn">${_('Download')}</a></div></td></tr>`;
  1528. const propfind_tpl = `<?xml version="1.0" encoding="UTF-8"?>
  1529. <D:propfind xmlns:D="DAV:" xmlns:oc="http://owncloud.org/ns">
  1530. <D:prop>
  1531. <D:getlastmodified/><D:getcontenttype/><D:getcontentlength/><D:resourcetype/><D:displayname/><oc:permissions/>
  1532. </D:prop>
  1533. </D:propfind>`;
  1534. const wopi_propfind_tpl = `<?xml version="1.0" encoding="UTF-8"?>
  1535. <D:propfind xmlns:D="DAV:" xmlns:W="https://interoperability.blob.core.windows.net/files/MS-WOPI/">
  1536. <D:prop>
  1537. <W:file-url/><W:token/><W:token-ttl/>
  1538. </D:prop>
  1539. </D:propfind>`;
  1540. const html = (unsafe) => {
  1541. return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
  1542. };
  1543. const reqXML = (method, url, body, headers) => {
  1544. return req(method, url, body, headers).then((r) => {
  1545. if (!r.ok) {
  1546. throw new Error(r.status + ' ' + r.statusText);
  1547. }
  1548. return r.text();
  1549. }).then(str => new window.DOMParser().parseFromString(str, "text/xml"));
  1550. };
  1551. const reqAndReload = (method, url, body, headers) => {
  1552. animateLoading();
  1553. req(method, url, body, headers).then(r => {
  1554. stopLoading();
  1555. if (!r.ok) {
  1556. return r.text().then(t => {
  1557. var message;
  1558. if (a = t.match(/<((?:\w+:)?message)>(.*)<\/\1>/)) {
  1559. message = "\n" + a[2];
  1560. }
  1561. throw new Error(r.status + ' ' + r.statusText + message); });
  1562. }
  1563. reloadListing();
  1564. }).catch(e => {
  1565. console.error(e);
  1566. alert(e);
  1567. });
  1568. return false;
  1569. };
  1570. const req = (method, url, body, headers) => {
  1571. if (!headers) {
  1572. headers = {};
  1573. }
  1574. if (auth_header) {
  1575. headers.Authorization = auth_header;
  1576. }
  1577. return fetch(url, {method, body, headers});
  1578. };
  1579. const xhr = (method, url, progress_callback) => {
  1580. var xhr = new XMLHttpRequest();
  1581. current_xhr = xhr;
  1582. xhr.responseType = 'blob';
  1583. var p = new Promise((resolve, reject) => {
  1584. xhr.open(method, url);
  1585. xhr.onload = function () {
  1586. if (this.status >= 200 && this.status < 300) {
  1587. resolve(xhr.response);
  1588. } else {
  1589. reject({
  1590. status: this.status,
  1591. statusText: xhr.statusText
  1592. });
  1593. }
  1594. };
  1595. xhr.onerror = function () {
  1596. reject({
  1597. status: this.status,
  1598. statusText: xhr.statusText
  1599. });
  1600. };
  1601. xhr.onprogress = progress_callback;
  1602. xhr.send();
  1603. });
  1604. return p;
  1605. };
  1606. const get_url = async (url) => {
  1607. var progress = (e) => {
  1608. var p = $('progress');
  1609. if (!p || e.loaded <= 0) return;
  1610. p.value = e.loaded;
  1611. $('.progress_bytes').innerHTML = formatBytes(e.loaded);
  1612. };
  1613. if (temp_object_url) {
  1614. window.URL.revokeObjectURL(temp_object_url);
  1615. }
  1616. return await xhr('GET', url, progress).then(blob => {
  1617. temp_object_url = window.URL.createObjectURL(blob);
  1618. return temp_object_url;
  1619. });
  1620. };
  1621. const wopi_init = async () => {
  1622. if (!wopi_discovery_url) {
  1623. return;
  1624. }
  1625. var d = await reqXML('GET', wopi_discovery_url);
  1626. d.querySelectorAll('app').forEach(app => {
  1627. var mime = (a = app.getAttribute('name').match(/^.*\/.*$/)) ? a[0] : null;
  1628. wopi_mimes[mime] = {};
  1629. app.querySelectorAll('action').forEach(action => {
  1630. var ext = action.getAttribute('ext').toUpperCase();
  1631. var url = action.getAttribute('urlsrc').replace(/<[^>]*&>/g, '');
  1632. var name = action.getAttribute('name');
  1633. if (mime) {
  1634. wopi_mimes[mime][name] = url;
  1635. }
  1636. else {
  1637. if (!wopi_extensions.hasOwnProperty(ext)) {
  1638. wopi_extensions[ext] = {};
  1639. }
  1640. wopi_extensions[ext][name] = url;
  1641. }
  1642. });
  1643. });
  1644. reloadListing();
  1645. };
  1646. const wopi_getEditURL = (name, mime) => {
  1647. var file_ext = name.replace(/^.*\.(\w+)$/, '$1').toUpperCase();
  1648. if (wopi_mimes.hasOwnProperty(mime) && wopi_mimes[mime].hasOwnProperty('edit')) {
  1649. return wopi_mimes[mime].edit;
  1650. }
  1651. else if (wopi_extensions.hasOwnProperty(file_ext) && wopi_extensions[file_ext].hasOwnProperty('edit')) {
  1652. return wopi_extensions[file_ext].edit;
  1653. }
  1654. return null;
  1655. };
  1656. const wopi_getViewURL = (name, mime) => {
  1657. var file_ext = name.replace(/^.*\.(\w+)$/, '$1').toUpperCase();
  1658. if (wopi_mimes.hasOwnProperty(mime) && wopi_mimes[mime].hasOwnProperty('view')) {
  1659. return wopi_mimes[mime].view;
  1660. }
  1661. else if (wopi_extensions.hasOwnProperty(file_ext) && wopi_extensions[file_ext].hasOwnProperty('view')) {
  1662. return wopi_extensions[file_ext].view;
  1663. }
  1664. return wopi_getEditURL(name, mime);
  1665. };
  1666. const wopi_open = async (document_url, wopi_url) => {
  1667. var properties = await reqXML('PROPFIND', document_url, wopi_propfind_tpl, {'Depth': '0'});
  1668. var src = (a = properties.querySelector('file-url')) ? a.textContent : null;
  1669. var token = (a = properties.querySelector('token')) ? a.textContent : null;
  1670. var token_ttl = (a = properties.querySelector('token-ttl')) ? a.textContent : +(new Date(Date.now() + 3600 * 1000));
  1671. if (!src || !token) {
  1672. alert('Cannot open document: WebDAV server did not return WOPI properties');
  1673. }
  1674. wopi_url += '&WOPISrc=' + encodeURIComponent(src);
  1675. openDialog(wopi_dialog, false);
  1676. $('dialog').className = 'preview';
  1677. var f = $('dialog form');
  1678. f.target = 'wopi_frame';
  1679. f.action = wopi_url;
  1680. f.method = 'post';
  1681. f.insertAdjacentHTML('beforeend', `<input name="access_token" value="${token}" type="hidden" /><input name="access_token_ttl" value="${token_ttl}" type="hidden" />`);
  1682. f.submit();
  1683. };
  1684. const template = (tpl, params) => {
  1685. return tpl.replace(/%(\w+)%/g, (a, b) => {
  1686. return params[b];
  1687. });
  1688. };
  1689. const openDialog = (html, ok_btn = true) => {
  1690. var tpl = dialog_tpl.replace(/%b/, ok_btn ? `<p><input type="submit" value="${_('OK')}" /></p>` : '');
  1691. $('body').classList.add('dialog');
  1692. $('body').insertAdjacentHTML('beforeend', tpl.replace(/%s/, html));
  1693. $('.close input').onclick = closeDialog;
  1694. evt = window.addEventListener('keyup', (e) => {
  1695. if (e.key != 'Escape') return;
  1696. closeDialog();
  1697. return false;
  1698. });
  1699. if (a = $('dialog form input, dialog form textarea')) a.focus();
  1700. };
  1701. const closeDialog = (e) => {
  1702. if (!$('body').classList.contains('dialog')) {
  1703. return;
  1704. }
  1705. if (current_xhr) {
  1706. current_xhr.abort();
  1707. current_xhr = null;
  1708. }
  1709. window.onbeforeunload = null;
  1710. $('body').classList.remove('dialog');
  1711. if (!$('dialog')) return;
  1712. $('dialog').remove();
  1713. window.removeEventListener('keyup', evt);
  1714. evt = null;
  1715. };
  1716. const download = async (name, size, url) => {
  1717. window.onbeforeunload = () => {
  1718. if (current_xhr) {
  1719. current_xhr.abort();
  1720. }
  1721. return true;
  1722. };
  1723. openDialog(`<p class="spinner"><span></span></p>
  1724. <h3>${html(name)}</h3>
  1725. <progress max="${size}"></progress>
  1726. <p><span class="progress_bytes"></span> / ${formatBytes(size)}</p>`, false);
  1727. await get_url(url);
  1728. const a = document.createElement('a');
  1729. a.style.display = 'none';
  1730. a.href = temp_object_url;
  1731. a.download = name;
  1732. document.body.appendChild(a);
  1733. a.click();
  1734. window.URL.revokeObjectURL(temp_object_url);
  1735. a.remove();
  1736. closeDialog();
  1737. window.onbeforeunload = null;
  1738. };
  1739. const download_all = async () => {
  1740. for (var i = 0; i < items.length; i++) {
  1741. var item = items[i];
  1742. if (item.is_dir) {
  1743. continue;
  1744. }
  1745. await download(item.name, item.size, item.uri)
  1746. }
  1747. };
  1748. const preview = (type, url) => {
  1749. if (type.match(/^image\//)) {
  1750. openDialog(`<img src="${url}" />`, false);
  1751. }
  1752. else if (type.match(/^audio\//)) {
  1753. openDialog(`<audio controls="true" autoplay="true" src="${url}" />`, false);
  1754. }
  1755. else if (type.match(/^video\//)) {
  1756. openDialog(`<video controls="true" autoplay="true" src="${url}" />`, false);
  1757. }
  1758. else {
  1759. openDialog(`<iframe src="${url}" />`, false);
  1760. }
  1761. $('dialog').className = 'preview';
  1762. };
  1763. const $ = (a) => document.querySelector(a);
  1764. const formatBytes = (bytes) => {
  1765. const unit = _('B');
  1766. if (bytes >= 1024*1024*1024) {
  1767. return Math.round(bytes / (1024*1024*1024)) + ' G' + unit;
  1768. }
  1769. else if (bytes >= 1024*1024) {
  1770. return Math.round(bytes / (1024*1024)) + ' M' + unit;
  1771. }
  1772. else if (bytes >= 1024) {
  1773. return Math.round(bytes / 1024) + ' K' + unit;
  1774. }
  1775. else {
  1776. return bytes + ' ' + unit;
  1777. }
  1778. };
  1779. const formatDate = (date) => {
  1780. var now = new Date;
  1781. var nb_hours = (+(now) - +(date)) / 3600 / 1000;
  1782. if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() == now.getDate()) {
  1783. if (nb_hours <= 1) {
  1784. return _('%d minutes ago').replace(/%d/, Math.round(nb_hours * 60));
  1785. }
  1786. else {
  1787. return _('%d hours ago').replace(/%d/, Math.round(nb_hours));
  1788. }
  1789. }
  1790. else if (nb_hours <= 24) {
  1791. return _('Yesterday, %s').replace(/%s/, date.toLocaleTimeString());
  1792. }
  1793. return date.toLocaleString();
  1794. };
  1795. const openListing = (uri, push) => {
  1796. closeDialog();
  1797. reqXML('PROPFIND', uri, propfind_tpl, {'Depth': 1}).then((xml) => {
  1798. buildListing(uri, xml)
  1799. current_url = uri;
  1800. changeURL(uri, push);
  1801. }).catch((e) => {
  1802. console.error(e);
  1803. alert(e);
  1804. });
  1805. };
  1806. const reloadListing = () => {
  1807. stopLoading();
  1808. openListing(current_url, false);
  1809. };
  1810. const normalizeURL = (url) => {
  1811. if (!url.match(/^https?:\/\//)) {
  1812. url = base_url.replace(/^(https?:\/\/[^\/]+\/).*$/, '$1') + url.replace(/^\/+/, '');
  1813. }
  1814. return url;
  1815. };
  1816. const changeURL = (uri, push) => {
  1817. try {
  1818. if (push) {
  1819. history.pushState(1, null, uri);
  1820. }
  1821. else {
  1822. history.replaceState(1, null, uri);
  1823. }
  1824. if (popstate_evt) return;
  1825. popstate_evt = window.addEventListener('popstate', (e) => {
  1826. var url = location.pathname;
  1827. openListing(url, false);
  1828. });
  1829. }
  1830. catch (e) {
  1831. // If using a HTML page on another origin
  1832. location.hash = uri;
  1833. }
  1834. };
  1835. const animateLoading = () => {
  1836. document.body.classList.add('loading');
  1837. };
  1838. const stopLoading = () => {
  1839. document.body.classList.remove('loading');
  1840. };
  1841. const buildListing = (uri, xml) => {
  1842. uri = normalizeURL(uri);
  1843. items = [[], []];
  1844. var title = null;
  1845. var root_permissions = null;
  1846. xml.querySelectorAll('response').forEach((node) => {
  1847. var item_uri = normalizeURL(node.querySelector('href').textContent);
  1848. var props = null;
  1849. node.querySelectorAll('propstat').forEach((propstat) => {
  1850. if (propstat.querySelector('status').textContent.match(/200/)) {
  1851. props = propstat;
  1852. }
  1853. });
  1854. // This item didn't return any properties, everything is 404?
  1855. if (!props) {
  1856. console.error('Cannot find properties for: ' + item_uri);
  1857. return;
  1858. }
  1859. var name = item_uri.replace(/\/$/, '').split('/').pop();
  1860. name = decodeURIComponent(name);
  1861. var permissions = (prop = node.querySelector('permissions')) ? prop.textContent : null;
  1862. if (item_uri == uri) {
  1863. title = name;
  1864. root_permissions = permissions;
  1865. return;
  1866. }
  1867. var is_dir = node.querySelector('resourcetype collection') ? true : false;
  1868. var index = sort_order == 'name' && is_dir ? 0 : 1;
  1869. items[index].push({
  1870. 'uri': item_uri,
  1871. 'name': name,
  1872. 'size': !is_dir && (prop = node.querySelector('getcontentlength')) ? parseInt(prop.textContent, 10) : null,
  1873. 'mime': !is_dir && (prop = node.querySelector('getcontenttype')) ? prop.textContent : null,
  1874. 'modified': (prop = node.querySelector('getlastmodified')) ? new Date(prop.textContent) : null,
  1875. 'is_dir': is_dir,
  1876. 'permissions': permissions,
  1877. });
  1878. });
  1879. if (sort_order == 'name') {
  1880. items[0].sort((a, b) => a.name.localeCompare(b.name));
  1881. }
  1882. items[1].sort((a, b) => {
  1883. if (sort_order == 'date') {
  1884. return b.modified - a.modified;
  1885. }
  1886. else if (sort_order == 'size') {
  1887. return b.size - a.size;
  1888. }
  1889. else {
  1890. return a.name.localeCompare(b.name);
  1891. }
  1892. });
  1893. if (sort_order == 'name') {
  1894. // Sort with directories first
  1895. items = items[0].concat(items[1]);
  1896. }
  1897. else {
  1898. items = items[1];
  1899. }
  1900. var table = '';
  1901. var parent = uri.replace(/\/+$/, '').split('/').slice(0, -1).join('/') + '/';
  1902. if (parent.length >= base_url.length) {
  1903. table += template(dir_row_tpl, {'name': _('Back'), 'uri': parent, 'icon': '&#x21B2;'});
  1904. }
  1905. else {
  1906. title = 'My files';
  1907. }
  1908. items.forEach(item => {
  1909. // Don't include files we cannot read
  1910. if (item.permissions !== null && item.permissions.indexOf('G') == -1) {
  1911. console.error('OC permissions deny read access to this file: ' + item.name, 'Permissions: ', item.permissions);
  1912. return;
  1913. }
  1914. var row = item.is_dir ? dir_row_tpl : file_row_tpl;
  1915. item.size_bytes = item.size !== null ? formatBytes(item.size).replace(/ /g, '&nbsp;') : null;
  1916. item.icon = item.is_dir ? '&#x1F4C1;' : (item.uri.indexOf('.') > 0 ? item.uri.replace(/^.*\.(\w+)$/, '$1').toUpperCase() : '');
  1917. item.modified = item.modified !== null ? formatDate(item.modified) : null;
  1918. item.name = html(item.name);
  1919. table += template(row, item);
  1920. });
  1921. document.title = title;
  1922. document.querySelector('main').innerHTML = template(body_tpl, {'title': html(document.title), 'base_url': base_url, 'table': table});
  1923. var select = $('.sortorder');
  1924. select.value = sort_order;
  1925. select.onchange = () => {
  1926. sort_order = select.value;
  1927. window.localStorage.setItem('sort_order', sort_order);
  1928. reloadListing();
  1929. };
  1930. if (!items.length) {
  1931. $('.download_all').disabled = true;
  1932. }
  1933. else {
  1934. $('.download_all').onclick = download_all;
  1935. }
  1936. if (!root_permissions || root_permissions.indexOf('CK') != -1) {
  1937. $('.upload').insertAdjacentHTML('afterbegin', create_buttons);
  1938. $('.mkdir').onclick = () => {
  1939. openDialog(mkdir_dialog);
  1940. document.forms[0].onsubmit = () => {
  1941. var name = $('input[name=mkdir]').value;
  1942. if (!name) return false;
  1943. name = encodeURIComponent(name);
  1944. req('MKCOL', current_url + name).then(() => openListing(current_url + name + '/'));
  1945. return false;
  1946. };
  1947. };
  1948. $('.mkfile').onclick = () => {
  1949. openDialog(mkfile_dialog);
  1950. var t = $('input[name=mkfile]');
  1951. t.value = '.md';
  1952. t.focus();
  1953. t.selectionStart = t.selectionEnd = 0;
  1954. document.forms[0].onsubmit = () => {
  1955. var name = t.value;
  1956. if (!name) return false;
  1957. name = encodeURIComponent(name);
  1958. return reqAndReload('PUT', current_url + name, '');
  1959. };
  1960. };
  1961. var fi = $('input[type=file]');
  1962. $('.uploadfile').onclick = () => fi.click();
  1963. fi.onchange = () => {
  1964. if (!fi.files.length) return;
  1965. var body = new Blob(fi.files);
  1966. var name = fi.files[0].name;
  1967. name = encodeURIComponent(name);
  1968. return reqAndReload('PUT', current_url + name, body);
  1969. };
  1970. }
  1971. Array.from($('table').rows).forEach((tr) => {
  1972. var $$ = (a) => tr.querySelector(a);
  1973. var file_url = $$('a').href;
  1974. var file_name = $$('a').innerText;
  1975. var dir = $$('[colspan]');
  1976. var mime = !dir ? tr.getAttribute('data-mime') : 'dir';
  1977. var buttons = $$('td.buttons div');
  1978. var permissions = tr.getAttribute('data-permissions');
  1979. var size = tr.getAttribute('data-size');
  1980. if (permissions == 'null') {
  1981. permissions = null;
  1982. }
  1983. if (dir) {
  1984. $$('a').onclick = () => {
  1985. openListing(file_url, true);
  1986. return false;
  1987. };
  1988. }
  1989. // For back link
  1990. if (dir && $$('a').getAttribute('href').length < uri.length) {
  1991. dir.setAttribute('colspan', 4);
  1992. tr.querySelector('td:last-child').remove();
  1993. tr.querySelector('td:last-child').remove();
  1994. return;
  1995. }
  1996. // This is to get around CORS when not on the same domain
  1997. if (user && password && (a = tr.querySelector('a[download]'))) {
  1998. a.onclick = () => {
  1999. download(file_name, size, url);
  2000. return false;
  2001. };
  2002. }
  2003. // Add rename/delete buttons
  2004. if (!permissions || permissions.indexOf('NV') != -1) {
  2005. buttons.insertAdjacentHTML('afterbegin', rename_button);
  2006. $$('.rename').onclick = () => {
  2007. openDialog(rename_dialog);
  2008. let t = $('input[name=rename]');
  2009. t.value = file_name;
  2010. t.focus();
  2011. t.selectionStart = 0;
  2012. t.selectionEnd = file_name.lastIndexOf('.');
  2013. document.forms[0].onsubmit = () => {
  2014. var name = t.value;
  2015. if (!name) return false;
  2016. name = encodeURIComponent(name);
  2017. name = name.replace(/%2F/, '/');
  2018. var dest = current_url + name;
  2019. dest = normalizeURL(dest);
  2020. return reqAndReload('MOVE', file_url, '', {'Destination': dest});
  2021. };
  2022. };
  2023. }
  2024. if (!permissions || permissions.indexOf('D') != -1) {
  2025. buttons.insertAdjacentHTML('afterbegin', delete_button);
  2026. $$('.delete').onclick = (e) => {
  2027. openDialog(delete_dialog);
  2028. document.forms[0].onsubmit = () => {
  2029. return reqAndReload('DELETE', file_url);
  2030. };
  2031. };
  2032. }
  2033. var view_url, edit_url;
  2034. // Don't preview PDF in mobile
  2035. if (mime.match(PREVIEW_TYPES)
  2036. && !(mime == 'application/pdf' && window.navigator.userAgent.match(/Mobi|Tablet|Android|iPad|iPhone/))) {
  2037. $$('a').onclick = () => {
  2038. if (file_url.match(/\.md$/)) {
  2039. openDialog('<div class="md_preview"></div>', false);
  2040. $('dialog').className = 'preview';
  2041. req('GET', file_url).then(r => r.text()).then(t => {
  2042. $('.md_preview').innerHTML = microdown.parse(html(t));
  2043. });
  2044. return false;
  2045. }
  2046. if (user && password) {
  2047. (async () => { preview(mime, await get_url(file_url)); })();
  2048. }
  2049. else {
  2050. preview(mime, file_url);
  2051. }
  2052. return false;
  2053. };
  2054. }
  2055. else if (view_url = wopi_getViewURL(file_url, mime)) {
  2056. $$('.icon').classList.add('document');
  2057. $$('a').onclick = () => { wopi_open(file_url, view_url); return false; };
  2058. }
  2059. else if (user && password && !dir) {
  2060. $$('a').onclick = () => { download(file_name, size, file_url); return false; };
  2061. }
  2062. else {
  2063. $$('a').download = file_name;
  2064. }
  2065. if (!permissions || permissions.indexOf('W') != -1) {
  2066. if ( mime.match(/^text\/|application\/x-empty/)) {
  2067. buttons.insertAdjacentHTML('beforeend', edit_button);
  2068. $$('.edit').onclick = (e) => {
  2069. req('GET', file_url).then((r) => r.text().then((t) => {
  2070. let md = file_url.match(/\.md$/);
  2071. openDialog(md ? markdown_dialog : edit_dialog);
  2072. var txt = $('textarea[name=edit]');
  2073. txt.value = t;
  2074. // Markdown editor
  2075. if (md) {
  2076. let pre = $('#md');
  2077. txt.oninput = () => {
  2078. pre.innerHTML = microdown.parse(html(txt.value));
  2079. };
  2080. txt.oninput();
  2081. // Sync scroll, not perfect but better than nothing
  2082. txt.onscroll = (e) => {
  2083. var p = e.target.scrollTop / (e.target.scrollHeight - e.target.offsetHeight);
  2084. var target = e.target == pre ? txt : pre;
  2085. target.scrollTop = p * (target.scrollHeight - target.offsetHeight);
  2086. e.preventDefault();
  2087. return false;
  2088. };
  2089. }
  2090. document.forms[0].onsubmit = () => {
  2091. var content = txt.value;
  2092. return reqAndReload('PUT', file_url, content);
  2093. };
  2094. }));
  2095. };
  2096. }
  2097. else if (edit_url = wopi_getEditURL(file_url, mime)) {
  2098. buttons.insertAdjacentHTML('beforeend', edit_button);
  2099. $$('.icon').classList.add('document');
  2100. $$('.edit').onclick = () => { wopi_open(file_url, edit_url); return false; };
  2101. }
  2102. }
  2103. });
  2104. };
  2105. var items = [[], []];
  2106. var current_xhr = null;
  2107. var current_url = url;
  2108. var base_url = url;
  2109. const user = options.user || null;
  2110. const password = options.password || null;
  2111. var auth_header = (user && password) ? 'Basic ' + btoa(user + ':' + password) : null;
  2112. if (location.pathname.indexOf(base_url) === 0) {
  2113. current_url = location.pathname;
  2114. }
  2115. if (!base_url.match(/^https?:/)) {
  2116. base_url = location.href.replace(/^(https?:\/\/[^\/]+\/).*$/, '$1') + base_url.replace(/^\/+/, '');
  2117. }
  2118. var evt, paste_upload, popstate_evt, temp_object_url;
  2119. var sort_order = window.localStorage.getItem('sort_order') || 'name';
  2120. var wopi_mimes = {}, wopi_extensions = {};
  2121. const wopi_discovery_url = options.wopi_discovery_url || null;
  2122. document.querySelector('html').innerHTML = html_tpl;
  2123. if (wopi_discovery_url) {
  2124. // Wait for WOPI discovery before creating the list
  2125. wopi_init();
  2126. }
  2127. else {
  2128. reloadListing();
  2129. }
  2130. window.addEventListener('paste', (e) => {
  2131. let items = e.clipboardData.items;
  2132. const IMAGE_MIME_REGEX = /^image\/(p?jpeg|gif|png)$/i;
  2133. for (var i = 0; i < items.length; i++) {
  2134. if (items[i].kind === 'file' || IMAGE_MIME_REGEX.test(items[i].type)) {
  2135. e.preventDefault();
  2136. let f = items[i].getAsFile();
  2137. let name = f.name == 'image.png' ? f.name.replace(/\./, '-' + (+(new Date)) + '.') : f.name;
  2138. paste_upload = f;
  2139. openDialog(paste_upload_dialog);
  2140. let t = $('input[name=paste_name]');
  2141. t.value = name;
  2142. t.focus();
  2143. t.selectionStart = 0;
  2144. t.selectionEnd = name.lastIndexOf('.');
  2145. document.forms[0].onsubmit = () => {
  2146. name = encodeURIComponent(t.value);
  2147. return reqAndReload('PUT', current_url + name, paste_upload);
  2148. };
  2149. return;
  2150. }
  2151. }
  2152. });
  2153. var dragcounter = 0;
  2154. window.addEventListener('dragover', (e) => {
  2155. e.preventDefault();
  2156. e.stopPropagation();
  2157. });
  2158. window.addEventListener('dragenter', (e) => {
  2159. e.preventDefault();
  2160. e.stopPropagation();
  2161. if (!dragcounter) {
  2162. document.body.classList.add('dragging');
  2163. }
  2164. dragcounter++;
  2165. });
  2166. window.addEventListener('dragleave', (e) => {
  2167. e.preventDefault();
  2168. e.stopPropagation();
  2169. dragcounter--;
  2170. if (!dragcounter) {
  2171. document.body.classList.remove('dragging');
  2172. }
  2173. });
  2174. window.addEventListener('drop', (e) => {
  2175. e.preventDefault();
  2176. e.stopPropagation();
  2177. document.body.classList.remove('dragging');
  2178. dragcounter = 0;
  2179. const files = [...e.dataTransfer.items].map(item => item.getAsFile());
  2180. if (!files.length) return;
  2181. animateLoading();
  2182. (async () => {
  2183. for (var i = 0; i < files.length; i++) {
  2184. var f = files[i]
  2185. await req('PUT', current_url + encodeURIComponent(f.name), f);
  2186. }
  2187. window.setTimeout(() => {
  2188. stopLoading();
  2189. reloadListing();
  2190. }, 500);
  2191. })();
  2192. });
  2193. };
  2194. if (url = document.querySelector('html').getAttribute('data-webdav-url')) {
  2195. WebDAVNavigator(url, {
  2196. 'wopi_discovery_url': document.querySelector('html').getAttribute('data-wopi-discovery-url'),
  2197. });
  2198. }
  2199. :root {
  2200. --bg-color: #fff;
  2201. --fg-color: #000;
  2202. --g1-color: #eee;
  2203. --g2-color: #ccc;
  2204. --g3-color: #999;
  2205. --link-color: blue;
  2206. --visited-color: purple;
  2207. --active-color: darkred;
  2208. }
  2209. body {
  2210. text-align: center;
  2211. font-size: 1.1em;
  2212. font-family: Arial, Helvetica, sans-serif;
  2213. background: var(--bg-color);
  2214. color: var(--fg-color);
  2215. }
  2216. a:link {
  2217. color: var(--link-color);
  2218. }
  2219. a:visited {
  2220. color: var(--visited-color);
  2221. }
  2222. a:hover {
  2223. color: var(--active-color);
  2224. }
  2225. table {
  2226. margin: 2em auto;
  2227. border-collapse: collapse;
  2228. width: 90%;
  2229. }
  2230. th, td {
  2231. padding: .5em;
  2232. text-align: left;
  2233. border: 2px solid var(--g2-color);
  2234. }
  2235. th {
  2236. word-break: break-all;
  2237. }
  2238. td.thumb {
  2239. width: 5%;
  2240. }
  2241. td.buttons {
  2242. text-align: right;
  2243. width: 20em;
  2244. }
  2245. td.buttons div {
  2246. display: flex;
  2247. flex-direction: row-reverse;
  2248. }
  2249. table tr:nth-child(even) {
  2250. background: var(--g1-color);
  2251. }
  2252. .icon {
  2253. width: 2.6em;
  2254. height: 2.6em;
  2255. display: block;
  2256. border-radius: .2em;
  2257. background:var(--g3-color);
  2258. overflow: hidden;
  2259. color: var(--bg-color);
  2260. text-align: center;
  2261. }
  2262. .icon b {
  2263. font-weight: normal;
  2264. display: inline-block;
  2265. transform: rotate(-30deg);
  2266. line-height: 2.6rem;
  2267. }
  2268. .icon.JPEG, .icon.PNG, .icon.JPG, .icon.GIF, .icon.SVG, .icon.WEBP {
  2269. background: #966;
  2270. }
  2271. .icon.TXT, .icon.MD {
  2272. background: var(--fg-color);
  2273. }
  2274. .icon.MP4, .icon.MKV, .icon.MP3, .icon.M4A, .icon.WAV, .icon.FLAC, .icon.OGG, .icon.OGV, .icon.AAC, .icon.WEBM {
  2275. background: #669;
  2276. }
  2277. .icon.document {
  2278. background: #696;
  2279. }
  2280. .icon.PDF {
  2281. background: #969;
  2282. }
  2283. .icon.dir {
  2284. background: var(--g2-color);
  2285. color: var(--fg-color);
  2286. }
  2287. .icon.dir b {
  2288. font-size: 2em;
  2289. transform: none;
  2290. }
  2291. .size {
  2292. text-align: right;
  2293. }
  2294. input[type=button], input[type=submit], .btn {
  2295. font-size: 1.2em;
  2296. padding: .3em .5em;
  2297. margin: .2em .3em;
  2298. border: none;
  2299. background: var(--g2-color);
  2300. border-radius: .2em;
  2301. cursor: pointer;
  2302. text-decoration: none;
  2303. color: var(--fg-color) !important;
  2304. font-family: inherit;
  2305. }
  2306. td input[type=button], td input[type=submit], td .btn {
  2307. font-size: 1em;
  2308. }
  2309. input[type=text], textarea {
  2310. font-size: 1.2em;
  2311. padding: .3em .5em;
  2312. border: none;
  2313. background: var(--bg-color);
  2314. border-radius: .2em;
  2315. width: calc(100% - 1em);
  2316. color: var(--fg-color);
  2317. }
  2318. input:focus, textarea:focus {
  2319. box-shadow: 0px 0px 5px var(--active-color);
  2320. outline: 1px solid var(--active-color);
  2321. }
  2322. input[type=button]:hover, input[type=submit]:hover, .btn:hover {
  2323. color: var(--active-color);
  2324. text-decoration: underline;
  2325. background: var(--bg-color);
  2326. box-shadow: 0px 0px 5px var(--fg-color);
  2327. }
  2328. .close {
  2329. text-align: right;
  2330. margin: 0;
  2331. }
  2332. .close input {
  2333. font-size: .8em;
  2334. }
  2335. input[type=submit] {
  2336. float: right;
  2337. }
  2338. dialog {
  2339. position: fixed;
  2340. top: 1em;
  2341. right: 1em;
  2342. bottom: 1em;
  2343. left: 1em;
  2344. box-shadow: 0px 0px 5px var(--fg-color);
  2345. background: var(--g1-color);
  2346. color: var(--fg-color);
  2347. border: none;
  2348. border-radius: .5em;
  2349. }
  2350. dialog form div {
  2351. clear: both;
  2352. margin: 2em 0;
  2353. text-align: center;
  2354. }
  2355. .upload {
  2356. margin: 1em 0;
  2357. }
  2358. #mdp div, #mdp textarea {
  2359. width: calc(100% - 1em);
  2360. padding: .5em;
  2361. font-size: 1em;
  2362. height: calc(100% - 1em);
  2363. text-align: left;
  2364. margin: 0;
  2365. }
  2366. #md {
  2367. overflow: hidden;
  2368. overflow-x: auto;
  2369. }
  2370. #mdp {
  2371. display: grid;
  2372. grid-template-columns: 1fr 1fr;
  2373. grid-gap: .2em;
  2374. background: var(--g1-color);
  2375. height: 82vh;
  2376. }
  2377. dialog.preview {
  2378. height: calc(100%);
  2379. width: calc(100%);
  2380. top: 0;
  2381. left: 0;
  2382. right: 0;
  2383. bottom: 0;
  2384. padding: 0;
  2385. border-radius: 0;
  2386. background: var(--g1-color);
  2387. overflow: hidden;
  2388. }
  2389. iframe, .md_preview {
  2390. overflow: auto;
  2391. position: absolute;
  2392. top: 0;
  2393. left: 0;
  2394. right: 0;
  2395. bottom: 0;
  2396. padding: 0;
  2397. margin: 0;
  2398. width: 100%;
  2399. height: 100%;
  2400. border: none;
  2401. }
  2402. iframe, iframe body, .md_preview {
  2403. background-color: #fff;
  2404. color: #000;
  2405. }
  2406. .preview form {
  2407. height: calc(100% - 2em);
  2408. display: flex;
  2409. align-items: center;
  2410. justify-content: center;
  2411. }
  2412. .preview form > div {
  2413. width: calc(100vw);
  2414. height: 100%;
  2415. position: relative;
  2416. margin: 0;
  2417. display: flex;
  2418. align-items: center;
  2419. justify-content: center;
  2420. }
  2421. .preview div video {
  2422. max-width: 100%;
  2423. max-height: 100%;
  2424. }
  2425. .md_preview {
  2426. width: calc(100vw - 2em);
  2427. height: calc(100vh - 2em);
  2428. padding: 1em;
  2429. text-align: left;
  2430. }
  2431. .preview .close {
  2432. height: 2em;
  2433. text-align: center;
  2434. font-size: 1em;
  2435. display: block;
  2436. width: 100%;
  2437. margin: 0;
  2438. padding: 0;
  2439. border-radius: 0;
  2440. background: var(--g2-color);
  2441. color: var(--fg-color);
  2442. box-shadow: 0px 0px 5px var(--g2-color);
  2443. }
  2444. .preview img {
  2445. max-width: 95%;
  2446. max-height: 95%;
  2447. }
  2448. input[name=rename], input[name=paste_name] {
  2449. width: 30em;
  2450. }
  2451. .bg {
  2452. align-items: center;
  2453. justify-content: center;
  2454. position: fixed;
  2455. top: 0;
  2456. left: 0;
  2457. right: 0;
  2458. bottom: 0;
  2459. margin: 0;
  2460. padding: 0;
  2461. width: 0;
  2462. height: 0;
  2463. border: none;
  2464. align-items: center;
  2465. justify-content: center;
  2466. opacity: 0;
  2467. }
  2468. .loading .bg::after, .spinner span::after {
  2469. display: block;
  2470. content: " ";
  2471. width: 70px;
  2472. height: 70px;
  2473. border: 5px solid var(--g2-color);
  2474. border-radius: 50%;
  2475. border-top-color: var(--fg-color);
  2476. animation: spin 1s ease-in-out infinite;
  2477. filter: none;
  2478. }
  2479. .loading .bg::before {
  2480. display: block;
  2481. content: " ";
  2482. width: 70px;
  2483. height: 70px;
  2484. border: 20px solid var(--bg-color);
  2485. border-radius: 50%;
  2486. background: var(--bg-color);
  2487. position: absolute;
  2488. }
  2489. .spinner {
  2490. align-items: center;
  2491. justify-content: center;
  2492. display: flex;
  2493. }
  2494. .spinner span::after {
  2495. width: 30px;
  2496. height: 30px;
  2497. }
  2498. .loading .bg, .dragging .bg, .dialog .bg {
  2499. backdrop-filter: blur(5px);
  2500. background: rgba(0, 0, 0, 0.5);
  2501. opacity: 1;
  2502. width: 100%;
  2503. height: 100%;
  2504. }
  2505. dialog {
  2506. transition: all .3s;
  2507. }
  2508. progress {
  2509. height: 2em;
  2510. width: 90%;
  2511. }
  2512. @keyframes spin { to { transform: rotate(360deg); } }
  2513. @media screen and (max-width: 800px) {
  2514. .upload {
  2515. display: flex;
  2516. flex-direction: row;
  2517. justify-content: center;
  2518. flex-wrap: wrap;
  2519. }
  2520. body {
  2521. margin: 0;
  2522. font-size: 1em;
  2523. }
  2524. table {
  2525. margin: 2em 0;
  2526. width: 100%;
  2527. display: flex;
  2528. flex-direction: column;
  2529. }
  2530. table tr {
  2531. display: block;
  2532. border-top: 5px solid var(--bg-color);
  2533. padding: 0;
  2534. padding-left: 2em;
  2535. position: relative;
  2536. text-align: left;
  2537. min-height: 2.5em;
  2538. }
  2539. table td, table th {
  2540. border: none;
  2541. display: inline-block;
  2542. padding: .2em .5em;
  2543. }
  2544. table td.buttons {
  2545. display: block;
  2546. width: auto;
  2547. text-align: left;
  2548. }
  2549. td.buttons div {
  2550. display: inline-block;
  2551. }
  2552. table td.thumb {
  2553. padding: 0;
  2554. width: 2em;
  2555. position: absolute;
  2556. left: 0;
  2557. top: 0;
  2558. bottom: 0;
  2559. }
  2560. table th {
  2561. display: block;
  2562. }
  2563. .icon {
  2564. font-size: 12px;
  2565. height: 100%;
  2566. border-radius: 0;
  2567. }
  2568. .icon:not(.dir) b {
  2569. line-height: 3em;
  2570. display: block;
  2571. transform: translateX(-50%) translateY(-50%) rotate(-90deg);
  2572. font-size: 2em;
  2573. height: 3em;
  2574. position: absolute;
  2575. top: 50%;
  2576. left: 50%;
  2577. }
  2578. table th a {
  2579. font-size: 1.2em;
  2580. }
  2581. input[name=rename], input[name=paste_name] {
  2582. width: auto;
  2583. }
  2584. }
  2585. @media (prefers-color-scheme: dark) {
  2586. :root {
  2587. --bg-color: #000;
  2588. --fg-color: #fff;
  2589. --g1-color: #222;
  2590. --g2-color: #555;
  2591. --g3-color: #777;
  2592. --link-color: #99f;
  2593. --visited-color: #ccf;
  2594. --active-color: orange;
  2595. }
  2596. }
  2597. <?php } ?>