index.php 83 KB

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