index.php 83 KB

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