index.php 84 KB

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