index.php 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126
  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') {
  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 true;
  1040. }
  1041. return false;
  1042. }
  1043. public function canWrite(string $uri): bool
  1044. {
  1045. if (!$this->user && !ANONYMOUS_WRITE) {
  1046. return false;
  1047. }
  1048. if (!$this->canRead($uri)) {
  1049. return false;
  1050. }
  1051. if (ANONYMOUS_WRITE) {
  1052. return true;
  1053. }
  1054. if (!empty($this->users[$this->user]['write'])) {
  1055. return true;
  1056. }
  1057. return false;
  1058. }
  1059. public function list(string $uri, ?array $properties): iterable
  1060. {
  1061. if (!$this->canRead($uri)) {
  1062. throw new WebDAV_Exception('Access forbidden', 403);
  1063. }
  1064. $dirs = self::glob($this->path . $uri, '/*', \GLOB_ONLYDIR);
  1065. $dirs = array_map('basename', $dirs);
  1066. $dirs = array_filter($dirs, fn($a) => $this->canRead(ltrim($uri . '/' . $a, '/')));
  1067. natcasesort($dirs);
  1068. $files = self::glob($this->path . $uri, '/*');
  1069. $files = array_map('basename', $files);
  1070. $files = array_diff($files, $dirs);
  1071. // Remove PHP files and dot-files from listings
  1072. $files = array_filter($files, fn($a) => $this->canRead(ltrim($uri . '/' . $a, '/')));
  1073. natcasesort($files);
  1074. $files = array_flip(array_merge($dirs, $files));
  1075. $files = array_map(fn($a) => null, $files);
  1076. return $files;
  1077. }
  1078. public function get(string $uri): ?array
  1079. {
  1080. if (!$this->canRead($uri)) {
  1081. throw new WebDAV_Exception('Access forbidden', 403);
  1082. }
  1083. $path = $this->path . $uri;
  1084. if (!file_exists($path)) {
  1085. return null;
  1086. }
  1087. return ['path' => $path];
  1088. }
  1089. public function exists(string $uri): bool
  1090. {
  1091. return file_exists($this->path . $uri);
  1092. }
  1093. public function get_file_property(string $uri, string $name, int $depth)
  1094. {
  1095. $target = $this->path . $uri;
  1096. switch ($name) {
  1097. case 'DAV::getcontentlength':
  1098. return is_dir($target) ? null : filesize($target);
  1099. case 'DAV::getcontenttype':
  1100. // ownCloud app crashes if mimetype is provided for a directory
  1101. // https://github.com/owncloud/android/issues/3768
  1102. return is_dir($target) ? null : mime_content_type($target);
  1103. case 'DAV::resourcetype':
  1104. return is_dir($target) ? 'collection' : '';
  1105. case 'DAV::getlastmodified':
  1106. if (!$uri && $depth == 0 && is_dir($target)) {
  1107. $mtime = self::getDirectoryMTime($target);
  1108. }
  1109. else {
  1110. $mtime = filemtime($target);
  1111. }
  1112. if (!$mtime) {
  1113. return null;
  1114. }
  1115. return new \DateTime('@' . $mtime);
  1116. case 'DAV::displayname':
  1117. return basename($target);
  1118. case 'DAV::ishidden':
  1119. return basename($target)[0] == '.';
  1120. case 'DAV::getetag':
  1121. $hash = filemtime($target) . filesize($target);
  1122. return md5($hash . $target);
  1123. case 'DAV::lastaccessed':
  1124. return new \DateTime('@' . fileatime($target));
  1125. case 'DAV::creationdate':
  1126. return new \DateTime('@' . filectime($target));
  1127. case 'http://owncloud.org/ns:permissions':
  1128. $permissions = 'G';
  1129. if (is_writeable($target) && $this->canWrite($uri)) {
  1130. $permissions .= 'DNVWCK';
  1131. }
  1132. return $permissions;
  1133. case WebDAV::PROP_DIGEST_MD5:
  1134. if (!is_file($target)) {
  1135. return null;
  1136. }
  1137. return md5_file($target);
  1138. default:
  1139. break;
  1140. }
  1141. return null;
  1142. }
  1143. public function properties(string $uri, ?array $properties, int $depth): ?array
  1144. {
  1145. $target = $this->path . $uri;
  1146. if (!file_exists($target)) {
  1147. return null;
  1148. }
  1149. if (null === $properties) {
  1150. $properties = WebDAV::BASIC_PROPERTIES;
  1151. }
  1152. $out = [];
  1153. foreach ($properties as $name) {
  1154. $v = $this->get_file_property($uri, $name, $depth);
  1155. if (null !== $v) {
  1156. $out[$name] = $v;
  1157. }
  1158. }
  1159. return $out;
  1160. }
  1161. public function put(string $uri, $pointer, ?string $hash, ?int $mtime): bool
  1162. {
  1163. if (preg_match(self::PUT_IGNORE_PATTERN, basename($uri))) {
  1164. return false;
  1165. }
  1166. if (!$this->canWrite($uri)) {
  1167. throw new WebDAV_Exception('Access forbidden', 403);
  1168. }
  1169. $target = $this->path . $uri;
  1170. $parent = dirname($target);
  1171. if (is_dir($target)) {
  1172. throw new WebDAV_Exception('Target is a directory', 409);
  1173. }
  1174. if (!file_exists($parent)) {
  1175. mkdir($parent, 0770, true);
  1176. }
  1177. $new = !file_exists($target);
  1178. $delete = false;
  1179. $size = 0;
  1180. $quota = disk_free_space($this->path);
  1181. $tmp_file = '.tmp.' . sha1($target);
  1182. $out = fopen($tmp_file, 'w');
  1183. while (!feof($pointer)) {
  1184. $bytes = fread($pointer, 8192);
  1185. $size += strlen($bytes);
  1186. if ($size > $quota) {
  1187. $delete = true;
  1188. break;
  1189. }
  1190. fwrite($out, $bytes);
  1191. }
  1192. fclose($out);
  1193. fclose($pointer);
  1194. if ($delete) {
  1195. @unlink($tmp_file);
  1196. throw new WebDAV_Exception('Your quota is exhausted', 403);
  1197. }
  1198. elseif ($hash && md5_file($tmp_file) != $hash) {
  1199. @unlink($tmp_file);
  1200. throw new WebDAV_Exception('The data sent does not match the supplied MD5 hash', 400);
  1201. }
  1202. else {
  1203. rename($tmp_file, $target);
  1204. }
  1205. if ($mtime) {
  1206. @touch($target, $mtime);
  1207. }
  1208. return $new;
  1209. }
  1210. public function delete(string $uri): void
  1211. {
  1212. if (!$this->canWrite($uri)) {
  1213. throw new WebDAV_Exception('Access forbidden', 403);
  1214. }
  1215. $target = $this->path . $uri;
  1216. if (!file_exists($target)) {
  1217. throw new WebDAV_Exception('Target does not exist', 404);
  1218. }
  1219. if (!is_writeable($target)) {
  1220. throw new WebDAV_Exception('File permissions says that you cannot delete this, sorry.', 403);
  1221. }
  1222. if (is_dir($target)) {
  1223. foreach (self::glob($target, '/*') as $file) {
  1224. $this->delete(substr($file, strlen($this->path)));
  1225. }
  1226. rmdir($target);
  1227. }
  1228. else {
  1229. unlink($target);
  1230. }
  1231. }
  1232. public function copymove(bool $move, string $uri, string $destination): bool
  1233. {
  1234. if (!$this->canWrite($uri)) {
  1235. throw new WebDAV_Exception('Access forbidden', 403);
  1236. }
  1237. if (!$this->canWrite($destination)) {
  1238. throw new WebDAV_Exception('Access forbidden', 403);
  1239. }
  1240. $source = $this->path . $uri;
  1241. $target = $this->path . $destination;
  1242. $parent = dirname($target);
  1243. if (!file_exists($source)) {
  1244. throw new WebDAV_Exception('File not found', 404);
  1245. }
  1246. $overwritten = file_exists($target);
  1247. if (!is_dir($parent)) {
  1248. throw new WebDAV_Exception('Target parent directory does not exist', 409);
  1249. }
  1250. if (false === $move) {
  1251. $quota = disk_free_space($this->path);
  1252. if (filesize($source) > $quota) {
  1253. throw new WebDAV_Exception('Your quota is exhausted', 403);
  1254. }
  1255. }
  1256. if ($overwritten) {
  1257. $this->delete($destination);
  1258. }
  1259. $method = $move ? 'rename' : 'copy';
  1260. if ($method == 'copy' && is_dir($source)) {
  1261. @mkdir($target, 0770, true);
  1262. foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST) as $item)
  1263. {
  1264. if ($item->isDir()) {
  1265. @mkdir($target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  1266. } else {
  1267. copy($item, $target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  1268. }
  1269. }
  1270. }
  1271. else {
  1272. $method($source, $target);
  1273. $this->getResourceProperties($uri)->move($destination);
  1274. }
  1275. return $overwritten;
  1276. }
  1277. public function copy(string $uri, string $destination): bool
  1278. {
  1279. return $this->copymove(false, $uri, $destination);
  1280. }
  1281. public function move(string $uri, string $destination): bool
  1282. {
  1283. return $this->copymove(true, $uri, $destination);
  1284. }
  1285. public function mkcol(string $uri): void
  1286. {
  1287. if (!$this->canWrite($uri)) {
  1288. throw new WebDAV_Exception('Access forbidden', 403);
  1289. }
  1290. if (!disk_free_space($this->path)) {
  1291. throw new WebDAV_Exception('Your quota is exhausted', 403);
  1292. }
  1293. $target = $this->path . $uri;
  1294. $parent = dirname($target);
  1295. if (file_exists($target)) {
  1296. throw new WebDAV_Exception('There is already a file with that name', 405);
  1297. }
  1298. if (!file_exists($parent)) {
  1299. throw new WebDAV_Exception('The parent directory does not exist', 409);
  1300. }
  1301. mkdir($target, 0770);
  1302. }
  1303. static public function getDirectoryMTime(string $path): int
  1304. {
  1305. $last = 0;
  1306. $path = rtrim($path, '/');
  1307. foreach (self::glob($path, '/*', GLOB_NOSORT) as $f) {
  1308. if (is_dir($f)) {
  1309. $m = self::getDirectoryMTime($f);
  1310. if ($m > $last) {
  1311. $last = $m;
  1312. }
  1313. }
  1314. $m = filemtime($f);
  1315. if ($m > $last) {
  1316. $last = $m;
  1317. }
  1318. }
  1319. return $last;
  1320. }
  1321. }
  1322. class Server extends \KD2\WebDAV\Server
  1323. {
  1324. protected function html_directory(string $uri, iterable $list): ?string
  1325. {
  1326. $out = parent::html_directory($uri, $list);
  1327. if (null !== $out) {
  1328. $out = str_replace('<body>', sprintf('<body style="opacity: 0"><script type="text/javascript" src="%s/webdav.js"></script>', rtrim($this->base_uri, '/')), $out);
  1329. }
  1330. return $out;
  1331. }
  1332. function error(WebDAV_Exception $e)
  1333. {
  1334. if ($e->getCode() == 403 && !$this->storage->auth() && count($this->storage->users)) {
  1335. $user = $_SERVER['PHP_AUTH_USER'] ?? null;
  1336. http_response_code(401);
  1337. header('WWW-Authenticate: Basic realm="Please login"');
  1338. echo '<h2>Error 401</h2><h1>You need to login to access this.</h1>';
  1339. return;
  1340. }
  1341. parent::error($e);
  1342. }
  1343. }
  1344. }
  1345. namespace {
  1346. use PicoDAV\Server;
  1347. use PicoDAV\Storage;
  1348. $uri = strtok($_SERVER['REQUEST_URI'], '?');
  1349. $root = substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));
  1350. if (false !== strpos($uri, '..')) {
  1351. http_response_code(404);
  1352. die('Invalid URL');
  1353. }
  1354. $relative_uri = ltrim(substr($uri, strlen($root)), '/');
  1355. if (!empty($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'apache') && !file_exists(__DIR__ . '/.htaccess')) {
  1356. file_put_contents(__DIR__ . '/.htaccess', 'DirectoryIndex disabled
  1357. RedirectMatch 404 \\.picodav\\.ini
  1358. RewriteEngine On
  1359. RewriteBase /
  1360. RewriteCond %{REQUEST_FILENAME} !-f [OR]
  1361. RewriteCond %{REQUEST_URI} \\.picodav\\.ini [OR]
  1362. RewriteCond %{REQUEST_METHOD} !GET
  1363. RewriteRule ^.*$ /index.php [END]
  1364. ');
  1365. }
  1366. if ($relative_uri == 'webdav.js' || $relative_uri == 'webdav.css') {
  1367. http_response_code(200);
  1368. if ($relative_uri == 'webdav.js') {
  1369. header('Content-Type: text/javascript', true);
  1370. }
  1371. else {
  1372. header('Content-Type: text/css', true);
  1373. }
  1374. $seconds_to_cache = 3600 * 24 * 365;
  1375. $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  1376. header("Expires: " . $ts);
  1377. header("Pragma: cache");
  1378. header("Cache-Control: max-age=" . $seconds_to_cache);
  1379. $fp = fopen(__FILE__, 'r');
  1380. if ($relative_uri == 'webdav.js') {
  1381. fseek($fp, 48399, SEEK_SET);
  1382. echo fread($fp, 25889);
  1383. }
  1384. else {
  1385. fseek($fp, 48399 + 25889, SEEK_SET);
  1386. echo fread($fp, 6760);
  1387. }
  1388. fclose($fp);
  1389. exit;
  1390. }
  1391. const CONFIG_FILE = __DIR__ . '/.picodav.ini';
  1392. const INTERNAL_FILES = ['.picodav.ini', 'index.php', 'webdav.js', 'webdav.css'];
  1393. const DEFAULT_CONFIG = [
  1394. 'ANONYMOUS_READ' => false,
  1395. 'ANONYMOUS_WRITE' => false,
  1396. ];
  1397. $config = [];
  1398. $storage = new Storage;
  1399. if (file_exists(CONFIG_FILE)) {
  1400. $config = parse_ini_file(CONFIG_FILE, true);
  1401. $users = array_filter($config, 'is_array');
  1402. $config = array_diff_key($config, $users);
  1403. $config = array_change_key_case($config, \CASE_UPPER);
  1404. $replace = [];
  1405. // Encrypt plaintext passwords
  1406. foreach ($users as $name => $properties) {
  1407. if (isset($properties['password']) && substr($properties['password'], 0, 1) != '$') {
  1408. $users[$name]['password'] = $replace[$name] = password_hash($properties['password'], null);
  1409. }
  1410. }
  1411. if (count($replace)) {
  1412. $lines = file(CONFIG_FILE);
  1413. $current = null;
  1414. foreach ($lines as &$line) {
  1415. if (preg_match('/^\s*\[(\w+)\]\s*$/', $line, $match)) {
  1416. $current = $match[1];
  1417. continue;
  1418. }
  1419. if ($current && isset($replace[$current]) && preg_match('/^\s*password\s*=/', $line)) {
  1420. $line = sprintf("password = %s\n", var_export($replace[$current], true));
  1421. }
  1422. }
  1423. unset($line, $current);
  1424. file_put_contents(CONFIG_FILE, implode('', $lines));
  1425. }
  1426. $storage->users = $users;
  1427. }
  1428. foreach (DEFAULT_CONFIG as $key => $value) {
  1429. if (array_key_exists($key, $config)) {
  1430. $value = $config[$key];
  1431. }
  1432. if (is_bool(DEFAULT_CONFIG[$key])) {
  1433. $value = boolval($value);
  1434. }
  1435. define('PicoDAV\\' . $key, $value);
  1436. }
  1437. $dav = new Server;
  1438. $dav->setStorage($storage);
  1439. $dav->setBaseURI($root);
  1440. if (!$dav->route($uri)) {
  1441. http_response_code(404);
  1442. die('Invalid URL, sorry');
  1443. }
  1444. exit;
  1445. ?>
  1446. var css_url = document.currentScript.src.replace(/\/[^\/]+$/, '') + '/webdav.css';
  1447. const WebDAVNavigator = (url, options) => {
  1448. // Microdown
  1449. // https://github.com/commit-intl/micro-down
  1450. 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}}();
  1451. const PREVIEW_TYPES = /^image\/(png|webp|svg|jpeg|jpg|gif|png)|^application\/pdf|^text\/|^audio\/|^video\//;
  1452. const _ = key => typeof lang_strings != 'undefined' && key in lang_strings ? lang_strings[key] : key;
  1453. const rename_button = `<input class="rename" type="button" value="${_('Rename')}" />`;
  1454. const delete_button = `<input class="delete" type="button" value="${_('Delete')}" />`;
  1455. const edit_button = `<input class="edit" type="button" value="${_('Edit')}" />`;
  1456. const mkdir_dialog = `<input type="text" name="mkdir" placeholder="${_('Directory name')}" />`;
  1457. const mkfile_dialog = `<input type="text" name="mkfile" placeholder="${_('File name')}" />`;
  1458. const rename_dialog = `<input type="text" name="rename" placeholder="${_('New file name')}" />`;
  1459. const paste_upload_dialog = `<h3>Upload this file?</h3><input type="text" name="paste_name" placeholder="${_('New file name')}" />`;
  1460. const edit_dialog = `<textarea name="edit" cols="70" rows="30"></textarea>`;
  1461. const markdown_dialog = `<div id="mdp"><textarea name="edit" cols="70" rows="30"></textarea><div id="md"></div></div>`;
  1462. const delete_dialog = `<h3>${_('Confirm delete?')}</h3>`;
  1463. const wopi_dialog = `<iframe id="wopi_frame" name="wopi_frame" allowfullscreen="true" allow="autoplay camera microphone display-capture"
  1464. sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation allow-popups-to-escape-sandbox allow-downloads allow-modals">
  1465. </iframe>`;
  1466. const dialog_tpl = `<dialog open><p class="close"><input type="button" value="&#x2716; ${_('Close')}" class="close" /></p><form><div>%s</div>%b</form></dialog>`;
  1467. const html_tpl = `<!DOCTYPE html><html>
  1468. <head><title>Files</title><link rel="stylesheet" type="text/css" href="${css_url}" /></head>
  1469. <body><main></main><div class="bg"></div></body></html>`;
  1470. const body_tpl = `<h1>%title%</h1>
  1471. <div class="upload">
  1472. <select class="sortorder btn">
  1473. <option value="name">${_('Sort by name')}</option>
  1474. <option value="date">${_('Sort by date')}</option>
  1475. <option value="size">${_('Sort by size')}</option>
  1476. </select>
  1477. </div>
  1478. <table>%table%</table>`;
  1479. const create_buttons = `<input class="mkdir" type="button" value="${_('New directory')}" />
  1480. <input type="file" style="display: none;" />
  1481. <input class="mkfile" type="button" value="${_('New text file')}" />
  1482. <input class="uploadfile" type="button" value="${_('Upload file')}" />`;
  1483. 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>`;
  1484. const file_row_tpl = `<tr data-permissions="%permissions%" data-mime="%mime%"><td class="thumb"><span class="icon %icon%"><b>%icon%</b></span></td><th><a href="%uri%">%name%</a></th><td class="size">%size%</td><td>%modified%</td><td class="buttons"><div><a href="%uri%" download class="btn">${_('Download')}</a></div></td></tr>`;
  1485. const propfind_tpl = `<?xml version="1.0" encoding="UTF-8"?>
  1486. <D:propfind xmlns:D="DAV:" xmlns:oc="http://owncloud.org/ns">
  1487. <D:prop>
  1488. <D:getlastmodified/><D:getcontenttype/><D:getcontentlength/><D:resourcetype/><D:displayname/><oc:permissions/>
  1489. </D:prop>
  1490. </D:propfind>`;
  1491. const wopi_propfind_tpl = `<?xml version="1.0" encoding="UTF-8"?>
  1492. <D:propfind xmlns:D="DAV:" xmlns:W="https://interoperability.blob.core.windows.net/files/MS-WOPI/">
  1493. <D:prop>
  1494. <W:file-url/><W:token/><W:token-ttl/>
  1495. </D:prop>
  1496. </D:propfind>`;
  1497. const html = (unsafe) => {
  1498. return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
  1499. };
  1500. const reqXML = (method, url, body, headers) => {
  1501. return req(method, url, body, headers).then((r) => {
  1502. if (!r.ok) {
  1503. throw new Error(r.status + ' ' + r.statusText);
  1504. }
  1505. return r.text();
  1506. }).then(str => new window.DOMParser().parseFromString(str, "text/xml"));
  1507. };
  1508. const reqAndReload = (method, url, body, headers) => {
  1509. animateLoading();
  1510. req(method, url, body, headers).then(r => {
  1511. stopLoading();
  1512. if (!r.ok) {
  1513. return r.text().then(t => {
  1514. var message;
  1515. if (a = t.match(/<((?:\w+:)?message)>(.*)<\/\1>/)) {
  1516. message = "\n" + a[2];
  1517. }
  1518. throw new Error(r.status + ' ' + r.statusText + message); });
  1519. }
  1520. reloadListing();
  1521. }).catch(e => {
  1522. console.error(e);
  1523. alert(e);
  1524. });
  1525. return false;
  1526. };
  1527. const get_url = async (url) => {
  1528. if (temp_object_url) {
  1529. window.URL.revokeObjectURL(temp_object_url);
  1530. }
  1531. return req('GET', url).then(r => r.blob()).then(blob => {
  1532. temp_object_url = window.URL.createObjectURL(blob);
  1533. return temp_object_url;
  1534. });
  1535. }
  1536. const req = (method, url, body, headers) => {
  1537. if (!headers) {
  1538. headers = {};
  1539. }
  1540. if (auth_header) {
  1541. headers.Authorization = auth_header;
  1542. }
  1543. return fetch(url, {method, body, headers});
  1544. };
  1545. const wopi_init = async () => {
  1546. if (!wopi_discovery_url) {
  1547. return;
  1548. }
  1549. var d = await reqXML('GET', wopi_discovery_url);
  1550. d.querySelectorAll('app').forEach(app => {
  1551. var mime = (a = app.getAttribute('name').match(/^.*\/.*$/)) ? a[0] : null;
  1552. wopi_mimes[mime] = {};
  1553. app.querySelectorAll('action').forEach(action => {
  1554. var ext = action.getAttribute('ext').toUpperCase();
  1555. var url = action.getAttribute('urlsrc').replace(/<[^>]*&>/g, '');
  1556. var name = action.getAttribute('name');
  1557. if (mime) {
  1558. wopi_mimes[mime][name] = url;
  1559. }
  1560. else {
  1561. if (!wopi_extensions.hasOwnProperty(ext)) {
  1562. wopi_extensions[ext] = {};
  1563. }
  1564. wopi_extensions[ext][name] = url;
  1565. }
  1566. });
  1567. });
  1568. reloadListing();
  1569. };
  1570. const wopi_getEditURL = (name, mime) => {
  1571. var file_ext = name.replace(/^.*\.(\w+)$/, '$1').toUpperCase();
  1572. if (wopi_mimes.hasOwnProperty(mime) && wopi_mimes[mime].hasOwnProperty('edit')) {
  1573. return wopi_mimes[mime].edit;
  1574. }
  1575. else if (wopi_extensions.hasOwnProperty(file_ext) && wopi_extensions[file_ext].hasOwnProperty('edit')) {
  1576. return wopi_extensions[file_ext].edit;
  1577. }
  1578. return null;
  1579. };
  1580. const wopi_getViewURL = (name, mime) => {
  1581. var file_ext = name.replace(/^.*\.(\w+)$/, '$1').toUpperCase();
  1582. if (wopi_mimes.hasOwnProperty(mime) && wopi_mimes[mime].hasOwnProperty('view')) {
  1583. return wopi_mimes[mime].view;
  1584. }
  1585. else if (wopi_extensions.hasOwnProperty(file_ext) && wopi_extensions[file_ext].hasOwnProperty('view')) {
  1586. return wopi_extensions[file_ext].view;
  1587. }
  1588. return wopi_getEditURL(name, mime);
  1589. };
  1590. const wopi_open = async (document_url, wopi_url) => {
  1591. var properties = await reqXML('PROPFIND', document_url, wopi_propfind_tpl, {'Depth': '0'});
  1592. var src = (a = properties.querySelector('file-url')) ? a.textContent : null;
  1593. var token = (a = properties.querySelector('token')) ? a.textContent : null;
  1594. var token_ttl = (a = properties.querySelector('token-ttl')) ? a.textContent : +(new Date(Date.now() + 3600 * 1000));
  1595. if (!src || !token) {
  1596. alert('Cannot open document: WebDAV server did not return WOPI properties');
  1597. }
  1598. wopi_url += '&WOPISrc=' + encodeURIComponent(src);
  1599. openDialog(wopi_dialog, false);
  1600. $('dialog').className = 'preview';
  1601. var f = $('dialog form');
  1602. f.target = 'wopi_frame';
  1603. f.action = wopi_url;
  1604. f.method = 'post';
  1605. f.insertAdjacentHTML('beforeend', `<input name="access_token" value="${token}" type="hidden" /><input name="access_token_ttl" value="${token_ttl}" type="hidden" />`);
  1606. f.submit();
  1607. };
  1608. const template = (tpl, params) => {
  1609. return tpl.replace(/%(\w+)%/g, (a, b) => {
  1610. return params[b];
  1611. });
  1612. };
  1613. const openDialog = (html, ok_btn = true) => {
  1614. var tpl = dialog_tpl.replace(/%b/, ok_btn ? `<p><input type="submit" value="${_('OK')}" /></p>` : '');
  1615. $('body').classList.add('dialog');
  1616. $('body').insertAdjacentHTML('beforeend', tpl.replace(/%s/, html));
  1617. $('.close input').onclick = closeDialog;
  1618. evt = window.addEventListener('keyup', (e) => {
  1619. if (e.key != 'Escape') return;
  1620. closeDialog();
  1621. return false;
  1622. });
  1623. if (a = $('dialog form input, dialog form textarea')) a.focus();
  1624. };
  1625. const closeDialog = (e) => {
  1626. $('body').classList.remove('dialog');
  1627. if (!$('dialog')) return;
  1628. $('dialog').remove();
  1629. window.removeEventListener('keyup', evt);
  1630. evt = null;
  1631. };
  1632. const download = async (name, url) => {
  1633. var url = await get_url(url);
  1634. const a = document.createElement('a');
  1635. a.style.display = 'none';
  1636. a.href = url;
  1637. a.download = name;
  1638. document.body.appendChild(a);
  1639. a.click();
  1640. window.URL.revokeObjectURL(url);
  1641. a.remove();
  1642. };
  1643. const preview = (type, url) => {
  1644. if (type.match(/^image\//)) {
  1645. openDialog(`<img src="${url}" />`, false);
  1646. }
  1647. else if (type.match(/^audio\//)) {
  1648. openDialog(`<audio controls="true" autoplay="true" src="${url}" />`, false);
  1649. }
  1650. else if (type.match(/^video\//)) {
  1651. openDialog(`<video controls="true" autoplay="true" src="${url}" />`, false);
  1652. }
  1653. else {
  1654. openDialog(`<iframe src="${url}" />`, false);
  1655. }
  1656. $('dialog').className = 'preview';
  1657. };
  1658. const $ = (a) => document.querySelector(a);
  1659. const formatBytes = (bytes) => {
  1660. const unit = _('B');
  1661. if (bytes >= 1024*1024*1024) {
  1662. return Math.round(bytes / (1024*1024*1024)) + ' G' + unit;
  1663. }
  1664. else if (bytes >= 1024*1024) {
  1665. return Math.round(bytes / (1024*1024)) + ' M' + unit;
  1666. }
  1667. else if (bytes >= 1024) {
  1668. return Math.round(bytes / 1024) + ' K' + unit;
  1669. }
  1670. else {
  1671. return bytes + ' ' + unit;
  1672. }
  1673. };
  1674. const formatDate = (date) => {
  1675. var now = new Date;
  1676. var nb_hours = (+(now) - +(date)) / 3600 / 1000;
  1677. if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() == now.getDate()) {
  1678. if (nb_hours <= 1) {
  1679. return _('%d minutes ago').replace(/%d/, Math.round(nb_hours * 60));
  1680. }
  1681. else {
  1682. return _('%d hours ago').replace(/%d/, Math.round(nb_hours));
  1683. }
  1684. }
  1685. else if (nb_hours <= 24) {
  1686. return _('Yesterday, %s').replace(/%s/, date.toLocaleTimeString());
  1687. }
  1688. return date.toLocaleString();
  1689. };
  1690. const openListing = (uri, push) => {
  1691. closeDialog();
  1692. reqXML('PROPFIND', uri, propfind_tpl, {'Depth': 1}).then((xml) => {
  1693. buildListing(uri, xml)
  1694. current_url = uri;
  1695. changeURL(uri, push);
  1696. }).catch((e) => {
  1697. console.error(e);
  1698. alert(e);
  1699. });
  1700. };
  1701. const reloadListing = () => {
  1702. stopLoading();
  1703. openListing(current_url, false);
  1704. };
  1705. const normalizeURL = (url) => {
  1706. if (!url.match(/^https?:\/\//)) {
  1707. url = base_url.replace(/^(https?:\/\/[^\/]+\/).*$/, '$1') + url.replace(/^\/+/, '');
  1708. }
  1709. return url;
  1710. };
  1711. const changeURL = (uri, push) => {
  1712. try {
  1713. if (push) {
  1714. history.pushState(1, null, uri);
  1715. }
  1716. else {
  1717. history.replaceState(1, null, uri);
  1718. }
  1719. if (popstate_evt) return;
  1720. popstate_evt = window.addEventListener('popstate', (e) => {
  1721. var url = location.pathname;
  1722. openListing(url, false);
  1723. });
  1724. }
  1725. catch (e) {
  1726. // If using a HTML page on another origin
  1727. location.hash = uri;
  1728. }
  1729. };
  1730. const animateLoading = () => {
  1731. document.body.classList.add('loading');
  1732. };
  1733. const stopLoading = () => {
  1734. document.body.classList.remove('loading');
  1735. };
  1736. const buildListing = (uri, xml) => {
  1737. uri = normalizeURL(uri);
  1738. var items = [[], []];
  1739. var title = null;
  1740. var root_permissions = null;
  1741. xml.querySelectorAll('response').forEach((node) => {
  1742. var item_uri = normalizeURL(node.querySelector('href').textContent);
  1743. var props = null;
  1744. node.querySelectorAll('propstat').forEach((propstat) => {
  1745. if (propstat.querySelector('status').textContent.match(/200/)) {
  1746. props = propstat;
  1747. }
  1748. });
  1749. // This item didn't return any properties, everything is 404?
  1750. if (!props) {
  1751. console.error('Cannot find properties for: ' + item_uri);
  1752. return;
  1753. }
  1754. var name = item_uri.replace(/\/$/, '').split('/').pop();
  1755. name = decodeURIComponent(name);
  1756. var permissions = (prop = node.querySelector('permissions')) ? prop.textContent : null;
  1757. if (item_uri == uri) {
  1758. title = name;
  1759. root_permissions = permissions;
  1760. return;
  1761. }
  1762. var is_dir = node.querySelector('resourcetype collection') ? true : false;
  1763. var index = sort_order == 'name' && is_dir ? 0 : 1;
  1764. items[index].push({
  1765. 'uri': item_uri,
  1766. 'name': name,
  1767. 'size': !is_dir && (prop = node.querySelector('getcontentlength')) ? parseInt(prop.textContent, 10) : null,
  1768. 'mime': !is_dir && (prop = node.querySelector('getcontenttype')) ? prop.textContent : null,
  1769. 'modified': (prop = node.querySelector('getlastmodified')) ? new Date(prop.textContent) : null,
  1770. 'is_dir': is_dir,
  1771. 'permissions': permissions,
  1772. });
  1773. });
  1774. if (sort_order == 'name') {
  1775. items[0].sort((a, b) => a.name.localeCompare(b.name));
  1776. }
  1777. items[1].sort((a, b) => {
  1778. if (sort_order == 'date') {
  1779. return b.modified - a.modified;
  1780. }
  1781. else if (sort_order == 'size') {
  1782. return b.size - a.size;
  1783. }
  1784. else {
  1785. return a.name.localeCompare(b.name);
  1786. }
  1787. });
  1788. if (sort_order == 'name') {
  1789. // Sort with directories first
  1790. items = items[0].concat(items[1]);
  1791. }
  1792. else {
  1793. items = items[1];
  1794. }
  1795. var table = '';
  1796. var parent = uri.replace(/\/+$/, '').split('/').slice(0, -1).join('/') + '/';
  1797. if (parent.length >= base_url.length) {
  1798. table += template(dir_row_tpl, {'name': _('Back'), 'uri': parent, 'icon': '&#x21B2;'});
  1799. }
  1800. else {
  1801. title = 'My files';
  1802. }
  1803. items.forEach(item => {
  1804. // Don't include files we cannot read
  1805. if (item.permissions !== null && item.permissions.indexOf('G') == -1) {
  1806. console.error('OC permissions deny read access to this file: ' + item.name, 'Permissions: ', item.permissions);
  1807. return;
  1808. }
  1809. var row = item.is_dir ? dir_row_tpl : file_row_tpl;
  1810. item.size = item.size !== null ? formatBytes(item.size).replace(/ /g, '&nbsp;') : null;
  1811. item.icon = item.is_dir ? '&#x1F4C1;' : (item.uri.indexOf('.') > 0 ? item.uri.replace(/^.*\.(\w+)$/, '$1').toUpperCase() : '');
  1812. item.modified = item.modified !== null ? formatDate(item.modified) : null;
  1813. item.name = html(item.name);
  1814. table += template(row, item);
  1815. });
  1816. document.title = title;
  1817. document.querySelector('main').innerHTML = template(body_tpl, {'title': html(document.title), 'base_url': base_url, 'table': table});
  1818. var select = $('.sortorder');
  1819. select.value = sort_order;
  1820. select.onchange = () => {
  1821. sort_order = select.value;
  1822. window.localStorage.setItem('sort_order', sort_order);
  1823. reloadListing();
  1824. };
  1825. if (!root_permissions || root_permissions.indexOf('CK') != -1) {
  1826. $('.upload').insertAdjacentHTML('afterbegin', create_buttons);
  1827. $('.mkdir').onclick = () => {
  1828. openDialog(mkdir_dialog);
  1829. document.forms[0].onsubmit = () => {
  1830. var name = $('input[name=mkdir]').value;
  1831. if (!name) return false;
  1832. name = encodeURIComponent(name);
  1833. req('MKCOL', current_url + name).then(() => openListing(current_url + name + '/'));
  1834. return false;
  1835. };
  1836. };
  1837. $('.mkfile').onclick = () => {
  1838. openDialog(mkfile_dialog);
  1839. var t = $('input[name=mkfile]');
  1840. t.value = '.md';
  1841. t.focus();
  1842. t.selectionStart = t.selectionEnd = 0;
  1843. document.forms[0].onsubmit = () => {
  1844. var name = t.value;
  1845. if (!name) return false;
  1846. name = encodeURIComponent(name);
  1847. return reqAndReload('PUT', current_url + name, '');
  1848. };
  1849. };
  1850. var fi = $('input[type=file]');
  1851. $('.uploadfile').onclick = () => fi.click();
  1852. fi.onchange = () => {
  1853. if (!fi.files.length) return;
  1854. var body = new Blob(fi.files);
  1855. var name = fi.files[0].name;
  1856. name = encodeURIComponent(name);
  1857. return reqAndReload('PUT', current_url + name, body);
  1858. };
  1859. }
  1860. Array.from($('table').rows).forEach((tr) => {
  1861. var $$ = (a) => tr.querySelector(a);
  1862. var file_url = $$('a').href;
  1863. var file_name = $$('a').innerText;
  1864. var dir = $$('[colspan]');
  1865. var mime = !dir ? tr.getAttribute('data-mime') : 'dir';
  1866. var buttons = $$('td.buttons div');
  1867. var permissions = tr.getAttribute('data-permissions');
  1868. if (permissions == 'null') {
  1869. permissions = null;
  1870. }
  1871. if (dir) {
  1872. $$('a').onclick = () => {
  1873. openListing(file_url, true);
  1874. return false;
  1875. };
  1876. }
  1877. // For back link
  1878. if (dir && $$('a').getAttribute('href').length < uri.length) {
  1879. dir.setAttribute('colspan', 4);
  1880. tr.querySelector('td:last-child').remove();
  1881. tr.querySelector('td:last-child').remove();
  1882. return;
  1883. }
  1884. // This is to get around CORS when not on the same domain
  1885. if (user && password && (a = tr.querySelector('a[download]'))) {
  1886. a.onclick = () => {
  1887. download(file_name, url);
  1888. return false;
  1889. };
  1890. }
  1891. // Add rename/delete buttons
  1892. if (!permissions || permissions.indexOf('NV') != -1) {
  1893. buttons.insertAdjacentHTML('afterbegin', rename_button);
  1894. $$('.rename').onclick = () => {
  1895. openDialog(rename_dialog);
  1896. let t = $('input[name=rename]');
  1897. t.value = file_name;
  1898. t.focus();
  1899. t.selectionStart = 0;
  1900. t.selectionEnd = file_name.lastIndexOf('.');
  1901. document.forms[0].onsubmit = () => {
  1902. var name = t.value;
  1903. if (!name) return false;
  1904. name = encodeURIComponent(name);
  1905. name = name.replace(/%2F/, '/');
  1906. var dest = current_url + name;
  1907. dest = normalizeURL(dest);
  1908. return reqAndReload('MOVE', file_url, '', {'Destination': dest});
  1909. };
  1910. };
  1911. }
  1912. if (!permissions || permissions.indexOf('D') != -1) {
  1913. buttons.insertAdjacentHTML('afterbegin', delete_button);
  1914. $$('.delete').onclick = (e) => {
  1915. openDialog(delete_dialog);
  1916. document.forms[0].onsubmit = () => {
  1917. return reqAndReload('DELETE', file_url);
  1918. };
  1919. };
  1920. }
  1921. var view_url, edit_url;
  1922. // Don't preview PDF in mobile
  1923. if (mime.match(PREVIEW_TYPES)
  1924. && !(mime == 'application/pdf' && window.navigator.userAgent.match(/Mobi|Tablet|Android|iPad|iPhone/))) {
  1925. $$('a').onclick = () => {
  1926. if (file_url.match(/\.md$/)) {
  1927. openDialog('<div class="md_preview"></div>', false);
  1928. $('dialog').className = 'preview';
  1929. req('GET', file_url).then(r => r.text()).then(t => {
  1930. $('.md_preview').innerHTML = microdown.parse(html(t));
  1931. });
  1932. return false;
  1933. }
  1934. if (user && password) {
  1935. (async () => { preview(mime, await get_url(file_url)); })();
  1936. }
  1937. else {
  1938. preview(mime, file_url);
  1939. }
  1940. return false;
  1941. };
  1942. }
  1943. else if (view_url = wopi_getViewURL(file_url, mime)) {
  1944. $$('.icon').classList.add('document');
  1945. $$('a').onclick = () => { wopi_open(file_url, view_url); return false; };
  1946. }
  1947. else if (user && password && !dir) {
  1948. $$('a').onclick = () => { download(file_name, file_url); return false; };
  1949. }
  1950. else {
  1951. $$('a').download = file_name;
  1952. }
  1953. if (!permissions || permissions.indexOf('W') != -1) {
  1954. if ( mime.match(/^text\/|application\/x-empty/)) {
  1955. buttons.insertAdjacentHTML('beforeend', edit_button);
  1956. $$('.edit').onclick = (e) => {
  1957. req('GET', file_url).then((r) => r.text().then((t) => {
  1958. let md = file_url.match(/\.md$/);
  1959. openDialog(md ? markdown_dialog : edit_dialog);
  1960. var txt = $('textarea[name=edit]');
  1961. txt.value = t;
  1962. // Markdown editor
  1963. if (md) {
  1964. let pre = $('#md');
  1965. txt.oninput = () => {
  1966. pre.innerHTML = microdown.parse(html(txt.value));
  1967. };
  1968. txt.oninput();
  1969. // Sync scroll, not perfect but better than nothing
  1970. txt.onscroll = (e) => {
  1971. var p = e.target.scrollTop / (e.target.scrollHeight - e.target.offsetHeight);
  1972. var target = e.target == pre ? txt : pre;
  1973. target.scrollTop = p * (target.scrollHeight - target.offsetHeight);
  1974. e.preventDefault();
  1975. return false;
  1976. };
  1977. }
  1978. document.forms[0].onsubmit = () => {
  1979. var content = txt.value;
  1980. return reqAndReload('PUT', file_url, content);
  1981. };
  1982. }));
  1983. };
  1984. }
  1985. else if (edit_url = wopi_getEditURL(file_url, mime)) {
  1986. buttons.insertAdjacentHTML('beforeend', edit_button);
  1987. $$('.icon').classList.add('document');
  1988. $$('.edit').onclick = () => { wopi_open(file_url, edit_url); return false; };
  1989. }
  1990. }
  1991. });
  1992. };
  1993. var current_url = url;
  1994. var base_url = url;
  1995. const user = options.user || null;
  1996. const password = options.password || null;
  1997. var auth_header = (user && password) ? 'Basic ' + btoa(user + ':' + password) : null;
  1998. if (location.pathname.indexOf(base_url) === 0) {
  1999. current_url = location.pathname;
  2000. }
  2001. if (!base_url.match(/^https?:/)) {
  2002. base_url = location.href.replace(/^(https?:\/\/[^\/]+\/).*$/, '$1') + base_url.replace(/^\/+/, '');
  2003. }
  2004. var evt, paste_upload, popstate_evt, temp_object_url;
  2005. var sort_order = window.localStorage.getItem('sort_order') || 'name';
  2006. var wopi_mimes = {}, wopi_extensions = {};
  2007. const wopi_discovery_url = options.wopi_discovery_url || null;
  2008. document.querySelector('html').innerHTML = html_tpl;
  2009. if (wopi_discovery_url) {
  2010. // Wait for WOPI discovery before creating the list
  2011. wopi_init();
  2012. }
  2013. else {
  2014. reloadListing();
  2015. }
  2016. window.addEventListener('paste', (e) => {
  2017. let items = e.clipboardData.items;
  2018. const IMAGE_MIME_REGEX = /^image\/(p?jpeg|gif|png)$/i;
  2019. for (var i = 0; i < items.length; i++) {
  2020. if (items[i].kind === 'file' || IMAGE_MIME_REGEX.test(items[i].type)) {
  2021. e.preventDefault();
  2022. let f = items[i].getAsFile();
  2023. let name = f.name == 'image.png' ? f.name.replace(/\./, '-' + (+(new Date)) + '.') : f.name;
  2024. paste_upload = f;
  2025. openDialog(paste_upload_dialog);
  2026. let t = $('input[name=paste_name]');
  2027. t.value = name;
  2028. t.focus();
  2029. t.selectionStart = 0;
  2030. t.selectionEnd = name.lastIndexOf('.');
  2031. document.forms[0].onsubmit = () => {
  2032. name = encodeURIComponent(t.value);
  2033. return reqAndReload('PUT', current_url + name, paste_upload);
  2034. };
  2035. return;
  2036. }
  2037. }
  2038. });
  2039. var dragcounter = 0;
  2040. window.addEventListener('dragover', (e) => {
  2041. e.preventDefault();
  2042. e.stopPropagation();
  2043. });
  2044. window.addEventListener('dragenter', (e) => {
  2045. e.preventDefault();
  2046. e.stopPropagation();
  2047. if (!dragcounter) {
  2048. document.body.classList.add('dragging');
  2049. }
  2050. dragcounter++;
  2051. });
  2052. window.addEventListener('dragleave', (e) => {
  2053. e.preventDefault();
  2054. e.stopPropagation();
  2055. dragcounter--;
  2056. if (!dragcounter) {
  2057. document.body.classList.remove('dragging');
  2058. }
  2059. });
  2060. window.addEventListener('drop', (e) => {
  2061. e.preventDefault();
  2062. e.stopPropagation();
  2063. document.body.classList.remove('dragging');
  2064. dragcounter = 0;
  2065. const files = [...e.dataTransfer.items].map(item => item.getAsFile());
  2066. if (!files.length) return;
  2067. animateLoading();
  2068. (async () => {
  2069. for (var i = 0; i < files.length; i++) {
  2070. var f = files[i]
  2071. await req('PUT', current_url + encodeURIComponent(f.name), f);
  2072. }
  2073. window.setTimeout(() => {
  2074. stopLoading();
  2075. reloadListing();
  2076. }, 500);
  2077. })();
  2078. });
  2079. };
  2080. if (url = document.querySelector('html').getAttribute('data-webdav-url')) {
  2081. WebDAVNavigator(url, {
  2082. 'wopi_discovery_url': document.querySelector('html').getAttribute('data-wopi-discovery-url'),
  2083. });
  2084. }
  2085. :root {
  2086. --bg-color: #fff;
  2087. --fg-color: #000;
  2088. --g1-color: #eee;
  2089. --g2-color: #ccc;
  2090. --g3-color: #999;
  2091. --link-color: blue;
  2092. --visited-color: purple;
  2093. --active-color: darkred;
  2094. }
  2095. body {
  2096. text-align: center;
  2097. font-size: 1.1em;
  2098. font-family: Arial, Helvetica, sans-serif;
  2099. background: var(--bg-color);
  2100. color: var(--fg-color);
  2101. }
  2102. a:link {
  2103. color: var(--link-color);
  2104. }
  2105. a:visited {
  2106. color: var(--visited-color);
  2107. }
  2108. a:hover {
  2109. color: var(--active-color);
  2110. }
  2111. table {
  2112. margin: 2em auto;
  2113. border-collapse: collapse;
  2114. width: 90%;
  2115. }
  2116. th, td {
  2117. padding: .5em;
  2118. text-align: left;
  2119. border: 2px solid var(--g2-color);
  2120. }
  2121. th {
  2122. word-break: break-all;
  2123. }
  2124. td.thumb {
  2125. width: 5%;
  2126. }
  2127. td.buttons {
  2128. text-align: right;
  2129. width: 20em;
  2130. }
  2131. td.buttons div {
  2132. display: flex;
  2133. flex-direction: row-reverse;
  2134. }
  2135. table tr:nth-child(even) {
  2136. background: var(--g1-color);
  2137. }
  2138. .icon {
  2139. width: 2.6em;
  2140. height: 2.6em;
  2141. display: block;
  2142. border-radius: .2em;
  2143. background:var(--g3-color);
  2144. overflow: hidden;
  2145. color: var(--bg-color);
  2146. text-align: center;
  2147. }
  2148. .icon b {
  2149. font-weight: normal;
  2150. display: inline-block;
  2151. transform: rotate(-30deg);
  2152. line-height: 2.6rem;
  2153. }
  2154. .icon.JPEG, .icon.PNG, .icon.JPG, .icon.GIF, .icon.SVG, .icon.WEBP {
  2155. background: #966;
  2156. }
  2157. .icon.TXT, .icon.MD {
  2158. background: var(--fg-color);
  2159. }
  2160. .icon.MP4, .icon.MKV, .icon.MP3, .icon.M4A, .icon.WAV, .icon.FLAC, .icon.OGG, .icon.OGV, .icon.AAC, .icon.WEBM {
  2161. background: #669;
  2162. }
  2163. .icon.document {
  2164. background: #696;
  2165. }
  2166. .icon.PDF {
  2167. background: #969;
  2168. }
  2169. .icon.dir {
  2170. background: var(--g2-color);
  2171. color: var(--fg-color);
  2172. }
  2173. .icon.dir b {
  2174. font-size: 2em;
  2175. transform: none;
  2176. }
  2177. .size {
  2178. text-align: right;
  2179. }
  2180. input[type=button], input[type=submit], .btn {
  2181. font-size: 1.2em;
  2182. padding: .3em .5em;
  2183. margin: .2em .3em;
  2184. border: none;
  2185. background: var(--g2-color);
  2186. border-radius: .2em;
  2187. cursor: pointer;
  2188. text-decoration: none;
  2189. color: var(--fg-color) !important;
  2190. font-family: inherit;
  2191. }
  2192. td input[type=button], td input[type=submit], td .btn {
  2193. font-size: 1em;
  2194. }
  2195. input[type=text], textarea {
  2196. font-size: 1.2em;
  2197. padding: .3em .5em;
  2198. border: none;
  2199. background: var(--bg-color);
  2200. border-radius: .2em;
  2201. width: calc(100% - 1em);
  2202. color: var(--fg-color);
  2203. }
  2204. input:focus, textarea:focus {
  2205. box-shadow: 0px 0px 5px var(--active-color);
  2206. outline: 1px solid var(--active-color);
  2207. }
  2208. input[type=button]:hover, input[type=submit]:hover, .btn:hover {
  2209. color: var(--active-color);
  2210. text-decoration: underline;
  2211. background: var(--bg-color);
  2212. box-shadow: 0px 0px 5px var(--fg-color);
  2213. }
  2214. .close {
  2215. text-align: right;
  2216. margin: 0;
  2217. }
  2218. .close input {
  2219. font-size: .8em;
  2220. }
  2221. input[type=submit] {
  2222. float: right;
  2223. }
  2224. dialog {
  2225. position: fixed;
  2226. top: 1em;
  2227. right: 1em;
  2228. bottom: 1em;
  2229. left: 1em;
  2230. box-shadow: 0px 0px 5px var(--fg-color);
  2231. background: var(--g1-color);
  2232. color: var(--fg-color);
  2233. border: none;
  2234. border-radius: .5em;
  2235. }
  2236. dialog form div {
  2237. clear: both;
  2238. margin: 2em 0;
  2239. text-align: center;
  2240. }
  2241. .upload {
  2242. margin: 1em 0;
  2243. }
  2244. #mdp div, #mdp textarea {
  2245. width: calc(100% - 1em);
  2246. padding: .5em;
  2247. font-size: 1em;
  2248. height: calc(100% - 1em);
  2249. text-align: left;
  2250. margin: 0;
  2251. }
  2252. #md {
  2253. overflow: hidden;
  2254. overflow-x: auto;
  2255. }
  2256. #mdp {
  2257. display: grid;
  2258. grid-template-columns: 1fr 1fr;
  2259. grid-gap: .2em;
  2260. background: var(--g1-color);
  2261. height: 82vh;
  2262. }
  2263. dialog.preview {
  2264. height: calc(100%);
  2265. width: calc(100%);
  2266. top: 0;
  2267. left: 0;
  2268. right: 0;
  2269. bottom: 0;
  2270. padding: 0;
  2271. border-radius: 0;
  2272. background: var(--g1-color);
  2273. overflow: hidden;
  2274. }
  2275. iframe, .md_preview {
  2276. overflow: auto;
  2277. position: absolute;
  2278. top: 0;
  2279. left: 0;
  2280. right: 0;
  2281. bottom: 0;
  2282. padding: 0;
  2283. margin: 0;
  2284. width: 100%;
  2285. height: 100%;
  2286. border: none;
  2287. }
  2288. iframe, iframe body, .md_preview {
  2289. background-color: #fff;
  2290. color: #000;
  2291. }
  2292. .preview form {
  2293. height: calc(100% - 2em);
  2294. display: flex;
  2295. align-items: center;
  2296. justify-content: center;
  2297. }
  2298. .preview form > div {
  2299. width: calc(100vw);
  2300. height: 100%;
  2301. position: relative;
  2302. margin: 0;
  2303. display: flex;
  2304. align-items: center;
  2305. justify-content: center;
  2306. }
  2307. .preview div video {
  2308. max-width: 100%;
  2309. max-height: 100%;
  2310. }
  2311. .md_preview {
  2312. width: calc(100vw - 2em);
  2313. height: calc(100vh - 2em);
  2314. padding: 1em;
  2315. text-align: left;
  2316. }
  2317. .preview .close {
  2318. height: 2em;
  2319. text-align: center;
  2320. font-size: 1em;
  2321. display: block;
  2322. width: 100%;
  2323. margin: 0;
  2324. padding: 0;
  2325. border-radius: 0;
  2326. background: var(--g2-color);
  2327. color: var(--fg-color);
  2328. box-shadow: 0px 0px 5px var(--g2-color);
  2329. }
  2330. .preview img {
  2331. max-width: 95%;
  2332. max-height: 95%;
  2333. }
  2334. input[name=rename], input[name=paste_name] {
  2335. width: 30em;
  2336. }
  2337. .bg {
  2338. align-items: center;
  2339. justify-content: center;
  2340. position: fixed;
  2341. top: 0;
  2342. left: 0;
  2343. right: 0;
  2344. bottom: 0;
  2345. margin: 0;
  2346. padding: 0;
  2347. width: 0;
  2348. height: 0;
  2349. border: none;
  2350. display: flex;
  2351. opacity: 0;
  2352. }
  2353. .loading .bg::after {
  2354. display: block;
  2355. content: " ";
  2356. width: 70px;
  2357. height: 70px;
  2358. border: 5px solid var(--g2-color);
  2359. border-radius: 50%;
  2360. border-top-color: var(--fg-color);
  2361. animation: spin 1s ease-in-out infinite;
  2362. filter: none;
  2363. }
  2364. .loading .bg::before {
  2365. display: block;
  2366. content: " ";
  2367. width: 70px;
  2368. height: 70px;
  2369. border: 20px solid var(--bg-color);
  2370. border-radius: 50%;
  2371. background: var(--bg-color);
  2372. position: absolute;
  2373. }
  2374. .loading .bg, .dragging .bg, .dialog .bg {
  2375. backdrop-filter: blur(5px);
  2376. background: rgba(0, 0, 0, 0.5);
  2377. opacity: 1;
  2378. width: 100%;
  2379. height: 100%;
  2380. }
  2381. dialog {
  2382. transition: all .3s;
  2383. }
  2384. @keyframes spin { to { transform: rotate(360deg); } }
  2385. @media screen and (max-width: 800px) {
  2386. .upload {
  2387. display: flex;
  2388. flex-direction: row;
  2389. justify-content: center;
  2390. flex-wrap: wrap;
  2391. }
  2392. body {
  2393. margin: 0;
  2394. font-size: 1em;
  2395. }
  2396. table {
  2397. margin: 2em 0;
  2398. width: 100%;
  2399. display: flex;
  2400. flex-direction: column;
  2401. }
  2402. table tr {
  2403. display: block;
  2404. border-top: 5px solid var(--bg-color);
  2405. padding: 0;
  2406. padding-left: 2em;
  2407. position: relative;
  2408. text-align: left;
  2409. min-height: 2.5em;
  2410. }
  2411. table td, table th {
  2412. border: none;
  2413. display: inline-block;
  2414. padding: .2em .5em;
  2415. }
  2416. table td.buttons {
  2417. display: block;
  2418. width: auto;
  2419. text-align: left;
  2420. }
  2421. td.buttons div {
  2422. display: inline-block;
  2423. }
  2424. table td.thumb {
  2425. padding: 0;
  2426. width: 2em;
  2427. position: absolute;
  2428. left: 0;
  2429. top: 0;
  2430. bottom: 0;
  2431. }
  2432. table th {
  2433. display: block;
  2434. }
  2435. .icon {
  2436. font-size: 12px;
  2437. height: 100%;
  2438. border-radius: 0;
  2439. }
  2440. .icon:not(.dir) b {
  2441. line-height: 3em;
  2442. display: block;
  2443. transform: translateX(-50%) translateY(-50%) rotate(-90deg);
  2444. font-size: 2em;
  2445. height: 3em;
  2446. position: absolute;
  2447. top: 50%;
  2448. left: 50%;
  2449. }
  2450. table th a {
  2451. font-size: 1.2em;
  2452. }
  2453. input[name=rename], input[name=paste_name] {
  2454. width: auto;
  2455. }
  2456. }
  2457. @media (prefers-color-scheme: dark) {
  2458. :root {
  2459. --bg-color: #000;
  2460. --fg-color: #fff;
  2461. --g1-color: #222;
  2462. --g2-color: #555;
  2463. --g3-color: #777;
  2464. --link-color: #99f;
  2465. --visited-color: #ccf;
  2466. --active-color: orange;
  2467. }
  2468. }
  2469. <?php } ?>