index.php 82 KB

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