index.php 83 KB

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