index.php 85 KB

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