index.php 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373
  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. # Uncomment the following 2 lignes to make things a bit faster for
  1472. # downloading files, AND you don\'t use PicoDAV users to manage access,
  1473. # but a regular .htpasswd file and config for your web server.
  1474. #RewriteCond %{REQUEST_FILENAME} !-f [OR]
  1475. #RewriteCond %{REQUEST_METHOD} !GET
  1476. RewriteRule ^.*$ index.php [END]
  1477. '));
  1478. }
  1479. if ($relative_uri == '.webdav/webdav.js' || $relative_uri == '.webdav/webdav.css') {
  1480. http_response_code(200);
  1481. if ($relative_uri == '.webdav/webdav.js') {
  1482. header('Content-Type: text/javascript', true);
  1483. }
  1484. else {
  1485. header('Content-Type: text/css', true);
  1486. }
  1487. $seconds_to_cache = 3600 * 24 * 5;
  1488. $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  1489. header("Expires: " . $ts);
  1490. header("Pragma: cache");
  1491. header("Cache-Control: max-age=" . $seconds_to_cache);
  1492. $fp = fopen(__FILE__, 'r');
  1493. if ($relative_uri == '.webdav/webdav.js') {
  1494. fseek($fp, 52648, SEEK_SET);
  1495. echo fread($fp, 27798);
  1496. }
  1497. else {
  1498. fseek($fp, 52648 + 27798, SEEK_SET);
  1499. echo fread($fp, 7004);
  1500. }
  1501. fclose($fp);
  1502. exit;
  1503. }
  1504. $config_file = $self_dir . '/.picodav.ini';
  1505. define('PicoDAV\INTERNAL_FILES', ['.picodav.ini', $self_dir, '.webdav/webdav.js', '.webdav/webdav.css']);
  1506. const DEFAULT_CONFIG = [
  1507. 'ANONYMOUS_READ' => true,
  1508. 'ANONYMOUS_WRITE' => false,
  1509. 'HTTP_LOG_FILE' => null,
  1510. ];
  1511. $config = [];
  1512. $storage = new Storage($self_dir);
  1513. if (file_exists($config_file)) {
  1514. $config = parse_ini_string(file_get_contents($config_file), true, INI_SCANNER_TYPED);
  1515. $users = array_filter($config, 'is_array');
  1516. $config = array_diff_key($config, $users);
  1517. $config = array_change_key_case($config, \CASE_UPPER);
  1518. $replace = [];
  1519. // Encrypt plaintext passwords
  1520. foreach ($users as $name => $properties) {
  1521. if (isset($properties['password']) && substr($properties['password'], 0, 1) != '$') {
  1522. $users[$name]['password'] = $replace[$name] = password_hash($properties['password'], null);
  1523. }
  1524. }
  1525. if (count($replace)) {
  1526. $lines = file($config_file);
  1527. $current = null;
  1528. foreach ($lines as &$line) {
  1529. if (preg_match('/^\s*\[(\w+)\]\s*$/', $line, $match)) {
  1530. $current = $match[1];
  1531. continue;
  1532. }
  1533. if ($current && isset($replace[$current]) && preg_match('/^\s*password\s*=/', $line)) {
  1534. $line = sprintf("password = %s\n", var_export($replace[$current], true));
  1535. }
  1536. }
  1537. unset($line, $current);
  1538. file_put_contents($config_file, implode('', $lines));
  1539. }
  1540. $storage->users = $users;
  1541. }
  1542. foreach (DEFAULT_CONFIG as $key => $value) {
  1543. if (array_key_exists($key, $config)) {
  1544. $value = $config[$key];
  1545. }
  1546. if (is_bool(DEFAULT_CONFIG[$key])) {
  1547. $value = boolval($value);
  1548. }
  1549. define('PicoDAV\\' . $key, $value);
  1550. }
  1551. $dav = new Server();
  1552. $dav->setStorage($storage);
  1553. $dav->setBaseURI($root);
  1554. if (!$dav->route($uri)) {
  1555. http_response_code(404);
  1556. die('Unknown URL, sorry.');
  1557. }
  1558. exit;
  1559. ?>
  1560. var css_url = document.currentScript.src.replace(/\/[^\/]+$/, '') + '/webdav.css';
  1561. const WebDAVNavigator = (url, options) => {
  1562. // Microdown
  1563. // https://github.com/commit-intl/micro-down
  1564. 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}}();
  1565. const PREVIEW_TYPES = /^image\/(png|webp|svg|jpeg|jpg|gif|png)|^application\/pdf|^text\/|^audio\/|^video\/|application\/x-empty/;
  1566. const _ = key => typeof lang_strings != 'undefined' && key in lang_strings ? lang_strings[key] : key;
  1567. const rename_button = `<input class="rename" type="button" value="${_('Rename')}" />`;
  1568. const delete_button = `<input class="delete" type="button" value="${_('Delete')}" />`;
  1569. const edit_button = `<input class="edit" type="button" value="${_('Edit')}" />`;
  1570. const mkdir_dialog = `<input type="text" name="mkdir" placeholder="${_('Directory name')}" />`;
  1571. const mkfile_dialog = `<input type="text" name="mkfile" placeholder="${_('File name')}" />`;
  1572. const rename_dialog = `<input type="text" name="rename" placeholder="${_('New file name')}" />`;
  1573. const paste_upload_dialog = `<h3>Upload this file?</h3><input type="text" name="paste_name" placeholder="${_('New file name')}" />`;
  1574. const edit_dialog = `<textarea name="edit" cols="70" rows="30"></textarea>`;
  1575. const markdown_dialog = `<div id="mdp"><textarea name="edit" cols="70" rows="30"></textarea><div id="md"></div></div>`;
  1576. const delete_dialog = `<h3>${_('Confirm delete?')}</h3>`;
  1577. const wopi_dialog = `<iframe id="wopi_frame" name="wopi_frame" allowfullscreen="true" allow="autoplay camera microphone display-capture"
  1578. sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation allow-popups-to-escape-sandbox allow-downloads allow-modals">
  1579. </iframe>`;
  1580. const dialog_tpl = `<dialog open><p class="close"><input type="button" value="&#x2716; ${_('Close')}" class="close" /></p><form><div>%s</div>%b</form></dialog>`;
  1581. const html_tpl = `<!DOCTYPE html><html>
  1582. <head><title>Files</title><link rel="stylesheet" type="text/css" href="${css_url}" /></head>
  1583. <body><main></main><div class="bg"></div></body></html>`;
  1584. const body_tpl = `<h1>%title%</h1>
  1585. <div class="upload">
  1586. <select class="sortorder btn">
  1587. <option value="name">${_('Sort by name')}</option>
  1588. <option value="date">${_('Sort by date')}</option>
  1589. <option value="size">${_('Sort by size')}</option>
  1590. </select>
  1591. <input type="button" class="download_all" value="${_('Download all files')}" />
  1592. </div>
  1593. <table>%table%</table>`;
  1594. const create_buttons = `<input class="mkdir" type="button" value="${_('New directory')}" />
  1595. <input type="file" style="display: none;" />
  1596. <input class="mkfile" type="button" value="${_('New text file')}" />
  1597. <input class="uploadfile" type="button" value="${_('Upload file')}" />`;
  1598. 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>`;
  1599. 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>`;
  1600. const propfind_tpl = '<'+ `?xml version="1.0" encoding="UTF-8"?>
  1601. <D:propfind xmlns:D="DAV:" xmlns:oc="http://owncloud.org/ns">
  1602. <D:prop>
  1603. <D:getlastmodified/><D:getcontenttype/><D:getcontentlength/><D:resourcetype/><D:displayname/><oc:permissions/>
  1604. </D:prop>
  1605. </D:propfind>`;
  1606. const wopi_propfind_tpl = '<' + `?xml version="1.0" encoding="UTF-8"?>
  1607. <D:propfind xmlns:D="DAV:" xmlns:W="https://interoperability.blob.core.windows.net/files/MS-WOPI/">
  1608. <D:prop>
  1609. <W:file-url/><W:token/><W:token-ttl/>
  1610. </D:prop>
  1611. </D:propfind>`;
  1612. const html = (unsafe) => {
  1613. return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
  1614. };
  1615. const reqXML = (method, url, body, headers) => {
  1616. return req(method, url, body, headers).then((r) => {
  1617. if (!r.ok) {
  1618. throw new Error(r.status + ' ' + r.statusText);
  1619. }
  1620. return r.text();
  1621. }).then(str => new window.DOMParser().parseFromString(str, "text/xml"));
  1622. };
  1623. const reqAndReload = (method, url, body, headers) => {
  1624. animateLoading();
  1625. req(method, url, body, headers).then(r => {
  1626. stopLoading();
  1627. if (!r.ok) {
  1628. return r.text().then(t => {
  1629. var message;
  1630. if (a = t.match(/<((?:\w+:)?message)>(.*)<\/\1>/)) {
  1631. message = "\n" + a[2];
  1632. }
  1633. throw new Error(r.status + ' ' + r.statusText + message); });
  1634. }
  1635. reloadListing();
  1636. }).catch(e => {
  1637. console.error(e);
  1638. alert(e);
  1639. });
  1640. return false;
  1641. };
  1642. const req = (method, url, body, headers) => {
  1643. if (!headers) {
  1644. headers = {};
  1645. }
  1646. if (auth_header) {
  1647. headers.Authorization = auth_header;
  1648. }
  1649. return fetch(url, {method, body, headers});
  1650. };
  1651. const xhr = (method, url, progress_callback) => {
  1652. var xhr = new XMLHttpRequest();
  1653. current_xhr = xhr;
  1654. xhr.responseType = 'blob';
  1655. var p = new Promise((resolve, reject) => {
  1656. xhr.open(method, url);
  1657. xhr.onload = function () {
  1658. if (this.status >= 200 && this.status < 300) {
  1659. resolve(xhr.response);
  1660. } else {
  1661. reject({
  1662. status: this.status,
  1663. statusText: xhr.statusText
  1664. });
  1665. }
  1666. };
  1667. xhr.onerror = function () {
  1668. reject({
  1669. status: this.status,
  1670. statusText: xhr.statusText
  1671. });
  1672. };
  1673. xhr.onprogress = progress_callback;
  1674. xhr.send();
  1675. });
  1676. return p;
  1677. };
  1678. const get_url = async (url) => {
  1679. var progress = (e) => {
  1680. var p = $('progress');
  1681. if (!p || e.loaded <= 0) return;
  1682. p.value = e.loaded;
  1683. $('.progress_bytes').innerHTML = formatBytes(e.loaded);
  1684. };
  1685. if (temp_object_url) {
  1686. window.URL.revokeObjectURL(temp_object_url);
  1687. }
  1688. return await xhr('GET', url, progress).then(blob => {
  1689. temp_object_url = window.URL.createObjectURL(blob);
  1690. return temp_object_url;
  1691. });
  1692. };
  1693. const wopi_init = async () => {
  1694. if (!wopi_discovery_url) {
  1695. return;
  1696. }
  1697. var d = await reqXML('GET', wopi_discovery_url);
  1698. d.querySelectorAll('app').forEach(app => {
  1699. var mime = (a = app.getAttribute('name').match(/^.*\/.*$/)) ? a[0] : null;
  1700. wopi_mimes[mime] = {};
  1701. app.querySelectorAll('action').forEach(action => {
  1702. var ext = action.getAttribute('ext').toUpperCase();
  1703. var url = action.getAttribute('urlsrc').replace(/<[^>]*&>/g, '');
  1704. var name = action.getAttribute('name');
  1705. if (mime) {
  1706. wopi_mimes[mime][name] = url;
  1707. }
  1708. else {
  1709. if (!wopi_extensions.hasOwnProperty(ext)) {
  1710. wopi_extensions[ext] = {};
  1711. }
  1712. wopi_extensions[ext][name] = url;
  1713. }
  1714. });
  1715. });
  1716. reloadListing();
  1717. };
  1718. const wopi_getEditURL = (name, mime) => {
  1719. var file_ext = name.replace(/^.*\.(\w+)$/, '$1').toUpperCase();
  1720. if (wopi_mimes.hasOwnProperty(mime) && wopi_mimes[mime].hasOwnProperty('edit')) {
  1721. return wopi_mimes[mime].edit;
  1722. }
  1723. else if (wopi_extensions.hasOwnProperty(file_ext) && wopi_extensions[file_ext].hasOwnProperty('edit')) {
  1724. return wopi_extensions[file_ext].edit;
  1725. }
  1726. return null;
  1727. };
  1728. const wopi_getViewURL = (name, mime) => {
  1729. var file_ext = name.replace(/^.*\.(\w+)$/, '$1').toUpperCase();
  1730. if (wopi_mimes.hasOwnProperty(mime) && wopi_mimes[mime].hasOwnProperty('view')) {
  1731. return wopi_mimes[mime].view;
  1732. }
  1733. else if (wopi_extensions.hasOwnProperty(file_ext) && wopi_extensions[file_ext].hasOwnProperty('view')) {
  1734. return wopi_extensions[file_ext].view;
  1735. }
  1736. return wopi_getEditURL(name, mime);
  1737. };
  1738. const wopi_open = async (document_url, wopi_url) => {
  1739. var properties = await reqXML('PROPFIND', document_url, wopi_propfind_tpl, {'Depth': '0'});
  1740. var src = (a = properties.querySelector('file-url')) ? a.textContent : null;
  1741. var token = (a = properties.querySelector('token')) ? a.textContent : null;
  1742. var token_ttl = (a = properties.querySelector('token-ttl')) ? a.textContent : +(new Date(Date.now() + 3600 * 1000));
  1743. if (!src || !token) {
  1744. alert('Cannot open document: WebDAV server did not return WOPI properties');
  1745. }
  1746. wopi_url += '&WOPISrc=' + encodeURIComponent(src);
  1747. openDialog(wopi_dialog, false);
  1748. $('dialog').className = 'preview';
  1749. var f = $('dialog form');
  1750. f.target = 'wopi_frame';
  1751. f.action = wopi_url;
  1752. f.method = 'post';
  1753. f.insertAdjacentHTML('beforeend', `<input name="access_token" value="${token}" type="hidden" /><input name="access_token_ttl" value="${token_ttl}" type="hidden" />`);
  1754. f.submit();
  1755. };
  1756. const template = (tpl, params) => {
  1757. return tpl.replace(/%(\w+)%/g, (a, b) => {
  1758. return params[b];
  1759. });
  1760. };
  1761. const openDialog = (html, ok_btn = true) => {
  1762. var tpl = dialog_tpl.replace(/%b/, ok_btn ? `<p><input type="submit" value="${_('OK')}" /></p>` : '');
  1763. $('body').classList.add('dialog');
  1764. $('body').insertAdjacentHTML('beforeend', tpl.replace(/%s/, html));
  1765. $('.close input').onclick = closeDialog;
  1766. evt = window.addEventListener('keyup', (e) => {
  1767. if (e.key != 'Escape') return;
  1768. closeDialog();
  1769. return false;
  1770. });
  1771. if (a = $('dialog form input, dialog form textarea')) a.focus();
  1772. };
  1773. const closeDialog = (e) => {
  1774. if (!$('body').classList.contains('dialog')) {
  1775. return;
  1776. }
  1777. if (current_xhr) {
  1778. current_xhr.abort();
  1779. current_xhr = null;
  1780. }
  1781. window.onbeforeunload = null;
  1782. $('body').classList.remove('dialog');
  1783. if (!$('dialog')) return;
  1784. $('dialog').remove();
  1785. window.removeEventListener('keyup', evt);
  1786. evt = null;
  1787. };
  1788. const download = async (name, size, url) => {
  1789. window.onbeforeunload = () => {
  1790. if (current_xhr) {
  1791. current_xhr.abort();
  1792. }
  1793. return true;
  1794. };
  1795. openDialog(`<p class="spinner"><span></span></p>
  1796. <h3>${html(name)}</h3>
  1797. <progress max="${size}"></progress>
  1798. <p><span class="progress_bytes"></span> / ${formatBytes(size)}</p>`, false);
  1799. await get_url(url);
  1800. const a = document.createElement('a');
  1801. a.style.display = 'none';
  1802. a.href = temp_object_url;
  1803. a.download = name;
  1804. document.body.appendChild(a);
  1805. a.click();
  1806. window.URL.revokeObjectURL(temp_object_url);
  1807. a.remove();
  1808. closeDialog();
  1809. window.onbeforeunload = null;
  1810. };
  1811. const download_all = async () => {
  1812. for (var i = 0; i < items.length; i++) {
  1813. var item = items[i];
  1814. if (item.is_dir) {
  1815. continue;
  1816. }
  1817. await download(item.name, item.size, item.uri)
  1818. }
  1819. };
  1820. const preview = (type, url) => {
  1821. if (type.match(/^image\//)) {
  1822. openDialog(`<img src="${url}" />`, false);
  1823. }
  1824. else if (type.match(/^audio\//)) {
  1825. openDialog(`<audio controls="true" autoplay="true" src="${url}" />`, false);
  1826. }
  1827. else if (type.match(/^video\//)) {
  1828. openDialog(`<video controls="true" autoplay="true" src="${url}" />`, false);
  1829. }
  1830. else {
  1831. openDialog(`<iframe src="${url}" />`, false);
  1832. }
  1833. $('dialog').className = 'preview';
  1834. };
  1835. const $ = (a) => document.querySelector(a);
  1836. const formatBytes = (bytes) => {
  1837. const unit = _('B');
  1838. if (bytes >= 1024*1024*1024) {
  1839. return Math.round(bytes / (1024*1024*1024)) + ' G' + unit;
  1840. }
  1841. else if (bytes >= 1024*1024) {
  1842. return Math.round(bytes / (1024*1024)) + ' M' + unit;
  1843. }
  1844. else if (bytes >= 1024) {
  1845. return Math.round(bytes / 1024) + ' K' + unit;
  1846. }
  1847. else {
  1848. return bytes + ' ' + unit;
  1849. }
  1850. };
  1851. const formatDate = (date) => {
  1852. var now = new Date;
  1853. var nb_hours = (+(now) - +(date)) / 3600 / 1000;
  1854. if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() == now.getDate()) {
  1855. if (nb_hours <= 1) {
  1856. return _('%d minutes ago').replace(/%d/, Math.round(nb_hours * 60));
  1857. }
  1858. else {
  1859. return _('%d hours ago').replace(/%d/, Math.round(nb_hours));
  1860. }
  1861. }
  1862. else if (nb_hours <= 24) {
  1863. return _('Yesterday, %s').replace(/%s/, date.toLocaleTimeString());
  1864. }
  1865. return date.toLocaleString();
  1866. };
  1867. const openListing = (uri, push) => {
  1868. closeDialog();
  1869. reqXML('PROPFIND', uri, propfind_tpl, {'Depth': 1}).then((xml) => {
  1870. buildListing(uri, xml)
  1871. current_url = uri;
  1872. changeURL(uri, push);
  1873. }).catch((e) => {
  1874. console.error(e);
  1875. alert(e);
  1876. });
  1877. };
  1878. const reloadListing = () => {
  1879. stopLoading();
  1880. openListing(current_url, false);
  1881. };
  1882. const normalizeURL = (url) => {
  1883. if (!url.match(/^https?:\/\//)) {
  1884. url = base_url.replace(/^(https?:\/\/[^\/]+\/).*$/, '$1') + url.replace(/^\/+/, '');
  1885. }
  1886. return url;
  1887. };
  1888. const changeURL = (uri, push) => {
  1889. try {
  1890. if (push) {
  1891. history.pushState(1, null, uri);
  1892. }
  1893. else {
  1894. history.replaceState(1, null, uri);
  1895. }
  1896. if (popstate_evt) return;
  1897. popstate_evt = window.addEventListener('popstate', (e) => {
  1898. var url = location.pathname;
  1899. openListing(url, false);
  1900. });
  1901. }
  1902. catch (e) {
  1903. // If using a HTML page on another origin
  1904. location.hash = uri;
  1905. }
  1906. };
  1907. const animateLoading = () => {
  1908. document.body.classList.add('loading');
  1909. };
  1910. const stopLoading = () => {
  1911. document.body.classList.remove('loading');
  1912. };
  1913. const buildListing = (uri, xml) => {
  1914. uri = normalizeURL(uri);
  1915. items = [[], []];
  1916. var title = null;
  1917. var root_permissions = null;
  1918. xml.querySelectorAll('response').forEach((node) => {
  1919. var item_uri = normalizeURL(node.querySelector('href').textContent);
  1920. var props = null;
  1921. node.querySelectorAll('propstat').forEach((propstat) => {
  1922. if (propstat.querySelector('status').textContent.match(/200/)) {
  1923. props = propstat;
  1924. }
  1925. });
  1926. // This item didn't return any properties, everything is 404?
  1927. if (!props) {
  1928. console.error('Cannot find properties for: ' + item_uri);
  1929. return;
  1930. }
  1931. var name = item_uri.replace(/\/$/, '').split('/').pop();
  1932. name = decodeURIComponent(name);
  1933. var permissions = (prop = node.querySelector('permissions')) ? prop.textContent : null;
  1934. if (item_uri == uri) {
  1935. title = name;
  1936. root_permissions = permissions;
  1937. return;
  1938. }
  1939. var is_dir = node.querySelector('resourcetype collection') ? true : false;
  1940. var index = sort_order == 'name' && is_dir ? 0 : 1;
  1941. items[index].push({
  1942. 'uri': item_uri,
  1943. 'name': name,
  1944. 'size': !is_dir && (prop = node.querySelector('getcontentlength')) ? parseInt(prop.textContent, 10) : null,
  1945. 'mime': !is_dir && (prop = node.querySelector('getcontenttype')) ? prop.textContent : null,
  1946. 'modified': (prop = node.querySelector('getlastmodified')) ? new Date(prop.textContent) : null,
  1947. 'is_dir': is_dir,
  1948. 'permissions': permissions,
  1949. });
  1950. });
  1951. if (sort_order == 'name') {
  1952. items[0].sort((a, b) => a.name.localeCompare(b.name));
  1953. }
  1954. items[1].sort((a, b) => {
  1955. if (sort_order == 'date') {
  1956. return b.modified - a.modified;
  1957. }
  1958. else if (sort_order == 'size') {
  1959. return b.size - a.size;
  1960. }
  1961. else {
  1962. return a.name.localeCompare(b.name);
  1963. }
  1964. });
  1965. if (sort_order == 'name') {
  1966. // Sort with directories first
  1967. items = items[0].concat(items[1]);
  1968. }
  1969. else {
  1970. items = items[1];
  1971. }
  1972. var table = '';
  1973. var parent = uri.replace(/\/+$/, '').split('/').slice(0, -1).join('/') + '/';
  1974. if (parent.length >= base_url.length) {
  1975. table += template(dir_row_tpl, {'name': _('Back'), 'uri': parent, 'icon': '&#x21B2;'});
  1976. }
  1977. else {
  1978. title = 'My files';
  1979. }
  1980. items.forEach(item => {
  1981. // Don't include files we cannot read
  1982. if (item.permissions !== null && item.permissions.indexOf('G') == -1) {
  1983. console.error('OC permissions deny read access to this file: ' + item.name, 'Permissions: ', item.permissions);
  1984. return;
  1985. }
  1986. var row = item.is_dir ? dir_row_tpl : file_row_tpl;
  1987. item.size_bytes = item.size !== null ? formatBytes(item.size).replace(/ /g, '&nbsp;') : null;
  1988. item.icon = item.is_dir ? '&#x1F4C1;' : (item.uri.indexOf('.') > 0 ? item.uri.replace(/^.*\.(\w+)$/, '$1').toUpperCase() : '');
  1989. item.modified = item.modified !== null ? formatDate(item.modified) : null;
  1990. item.name = html(item.name);
  1991. table += template(row, item);
  1992. });
  1993. document.title = title;
  1994. document.querySelector('main').innerHTML = template(body_tpl, {'title': html(document.title), 'base_url': base_url, 'table': table});
  1995. var select = $('.sortorder');
  1996. select.value = sort_order;
  1997. select.onchange = () => {
  1998. sort_order = select.value;
  1999. window.localStorage.setItem('sort_order', sort_order);
  2000. reloadListing();
  2001. };
  2002. if (!items.length) {
  2003. $('.download_all').disabled = true;
  2004. }
  2005. else {
  2006. $('.download_all').onclick = download_all;
  2007. }
  2008. if (!root_permissions || root_permissions.indexOf('CK') != -1) {
  2009. $('.upload').insertAdjacentHTML('afterbegin', create_buttons);
  2010. $('.mkdir').onclick = () => {
  2011. openDialog(mkdir_dialog);
  2012. document.forms[0].onsubmit = () => {
  2013. var name = $('input[name=mkdir]').value;
  2014. if (!name) return false;
  2015. name = encodeURIComponent(name);
  2016. req('MKCOL', current_url + name).then(() => openListing(current_url + name + '/'));
  2017. return false;
  2018. };
  2019. };
  2020. $('.mkfile').onclick = () => {
  2021. openDialog(mkfile_dialog);
  2022. var t = $('input[name=mkfile]');
  2023. t.value = '.md';
  2024. t.focus();
  2025. t.selectionStart = t.selectionEnd = 0;
  2026. document.forms[0].onsubmit = () => {
  2027. var name = t.value;
  2028. if (!name) return false;
  2029. name = encodeURIComponent(name);
  2030. return reqAndReload('PUT', current_url + name, '');
  2031. };
  2032. };
  2033. var fi = $('input[type=file]');
  2034. $('.uploadfile').onclick = () => fi.click();
  2035. fi.onchange = () => {
  2036. if (!fi.files.length) return;
  2037. var body = new Blob(fi.files);
  2038. var name = fi.files[0].name;
  2039. name = encodeURIComponent(name);
  2040. return reqAndReload('PUT', current_url + name, body);
  2041. };
  2042. }
  2043. Array.from($('table').rows).forEach((tr) => {
  2044. var $$ = (a) => tr.querySelector(a);
  2045. var file_url = $$('a').href;
  2046. var file_name = $$('a').innerText;
  2047. var dir = $$('[colspan]');
  2048. var mime = !dir ? tr.getAttribute('data-mime') : 'dir';
  2049. var buttons = $$('td.buttons div');
  2050. var permissions = tr.getAttribute('data-permissions');
  2051. var size = tr.getAttribute('data-size');
  2052. if (permissions == 'null') {
  2053. permissions = null;
  2054. }
  2055. if (dir) {
  2056. $$('a').onclick = () => {
  2057. openListing(file_url, true);
  2058. return false;
  2059. };
  2060. }
  2061. // For back link
  2062. if (dir && $$('a').getAttribute('href').length < uri.length) {
  2063. dir.setAttribute('colspan', 4);
  2064. tr.querySelector('td:last-child').remove();
  2065. tr.querySelector('td:last-child').remove();
  2066. return;
  2067. }
  2068. // This is to get around CORS when not on the same domain
  2069. if (user && password && (a = tr.querySelector('a[download]'))) {
  2070. a.onclick = () => {
  2071. download(file_name, size, url);
  2072. return false;
  2073. };
  2074. }
  2075. // Add rename/delete buttons
  2076. if (!permissions || permissions.indexOf('NV') != -1) {
  2077. buttons.insertAdjacentHTML('afterbegin', rename_button);
  2078. $$('.rename').onclick = () => {
  2079. openDialog(rename_dialog);
  2080. let t = $('input[name=rename]');
  2081. t.value = file_name;
  2082. t.focus();
  2083. t.selectionStart = 0;
  2084. t.selectionEnd = file_name.lastIndexOf('.');
  2085. document.forms[0].onsubmit = () => {
  2086. var name = t.value;
  2087. if (!name) return false;
  2088. name = encodeURIComponent(name);
  2089. name = name.replace(/%2F/, '/');
  2090. var dest = current_url + name;
  2091. dest = normalizeURL(dest);
  2092. return reqAndReload('MOVE', file_url, '', {'Destination': dest});
  2093. };
  2094. };
  2095. }
  2096. if (!permissions || permissions.indexOf('D') != -1) {
  2097. buttons.insertAdjacentHTML('afterbegin', delete_button);
  2098. $$('.delete').onclick = (e) => {
  2099. openDialog(delete_dialog);
  2100. document.forms[0].onsubmit = () => {
  2101. return reqAndReload('DELETE', file_url);
  2102. };
  2103. };
  2104. }
  2105. var view_url, edit_url;
  2106. // Don't preview PDF in mobile
  2107. if (mime.match(PREVIEW_TYPES)
  2108. && !(mime == 'application/pdf' && window.navigator.userAgent.match(/Mobi|Tablet|Android|iPad|iPhone/))) {
  2109. $$('a').onclick = () => {
  2110. if (file_url.match(/\.md$/)) {
  2111. openDialog('<div class="md_preview"></div>', false);
  2112. $('dialog').className = 'preview';
  2113. req('GET', file_url).then(r => r.text()).then(t => {
  2114. $('.md_preview').innerHTML = microdown.parse(html(t));
  2115. });
  2116. return false;
  2117. }
  2118. if (user && password) {
  2119. (async () => { preview(mime, await get_url(file_url)); })();
  2120. }
  2121. else {
  2122. preview(mime, file_url);
  2123. }
  2124. return false;
  2125. };
  2126. }
  2127. else if (view_url = wopi_getViewURL(file_url, mime)) {
  2128. $$('.icon').classList.add('document');
  2129. $$('a').onclick = () => { wopi_open(file_url, view_url); return false; };
  2130. }
  2131. else if (user && password && !dir) {
  2132. $$('a').onclick = () => { download(file_name, size, file_url); return false; };
  2133. }
  2134. else {
  2135. $$('a').download = file_name;
  2136. }
  2137. if (!permissions || permissions.indexOf('W') != -1) {
  2138. if (mime.match(/^text\/|application\/x-empty/)) {
  2139. buttons.insertAdjacentHTML('beforeend', edit_button);
  2140. $$('.edit').onclick = (e) => {
  2141. req('GET', file_url).then((r) => r.text().then((t) => {
  2142. let md = file_url.match(/\.md$/);
  2143. openDialog(md ? markdown_dialog : edit_dialog);
  2144. var txt = $('textarea[name=edit]');
  2145. txt.value = t;
  2146. // Markdown editor
  2147. if (md) {
  2148. let pre = $('#md');
  2149. txt.oninput = () => {
  2150. pre.innerHTML = microdown.parse(html(txt.value));
  2151. };
  2152. txt.oninput();
  2153. // Sync scroll, not perfect but better than nothing
  2154. txt.onscroll = (e) => {
  2155. var p = e.target.scrollTop / (e.target.scrollHeight - e.target.offsetHeight);
  2156. var target = e.target == pre ? txt : pre;
  2157. target.scrollTop = p * (target.scrollHeight - target.offsetHeight);
  2158. e.preventDefault();
  2159. return false;
  2160. };
  2161. }
  2162. document.forms[0].onsubmit = () => {
  2163. var content = txt.value;
  2164. return reqAndReload('PUT', file_url, content);
  2165. };
  2166. }));
  2167. };
  2168. }
  2169. else if (edit_url = wopi_getEditURL(file_url, mime)) {
  2170. buttons.insertAdjacentHTML('beforeend', edit_button);
  2171. $$('.icon').classList.add('document');
  2172. $$('.edit').onclick = () => { wopi_open(file_url, edit_url); return false; };
  2173. }
  2174. }
  2175. });
  2176. };
  2177. var items = [[], []];
  2178. var current_xhr = null;
  2179. var current_url = url;
  2180. var base_url = url;
  2181. const user = options.user || null;
  2182. const password = options.password || null;
  2183. var auth_header = (user && password) ? 'Basic ' + btoa(user + ':' + password) : null;
  2184. if (location.pathname.indexOf(base_url) === 0) {
  2185. current_url = location.pathname;
  2186. }
  2187. if (!base_url.match(/^https?:/)) {
  2188. base_url = location.href.replace(/^(https?:\/\/[^\/]+\/).*$/, '$1') + base_url.replace(/^\/+/, '');
  2189. }
  2190. var evt, paste_upload, popstate_evt, temp_object_url;
  2191. var sort_order = window.localStorage.getItem('sort_order') || 'name';
  2192. var wopi_mimes = {}, wopi_extensions = {};
  2193. const wopi_discovery_url = options.wopi_discovery_url || null;
  2194. document.querySelector('html').innerHTML = html_tpl;
  2195. if (wopi_discovery_url) {
  2196. // Wait for WOPI discovery before creating the list
  2197. wopi_init();
  2198. }
  2199. else {
  2200. reloadListing();
  2201. }
  2202. window.addEventListener('paste', (e) => {
  2203. let items = e.clipboardData.items;
  2204. const IMAGE_MIME_REGEX = /^image\/(p?jpeg|gif|png)$/i;
  2205. for (var i = 0; i < items.length; i++) {
  2206. if (items[i].kind === 'file' || IMAGE_MIME_REGEX.test(items[i].type)) {
  2207. e.preventDefault();
  2208. let f = items[i].getAsFile();
  2209. let name = f.name == 'image.png' ? f.name.replace(/\./, '-' + (+(new Date)) + '.') : f.name;
  2210. paste_upload = f;
  2211. openDialog(paste_upload_dialog);
  2212. let t = $('input[name=paste_name]');
  2213. t.value = name;
  2214. t.focus();
  2215. t.selectionStart = 0;
  2216. t.selectionEnd = name.lastIndexOf('.');
  2217. document.forms[0].onsubmit = () => {
  2218. name = encodeURIComponent(t.value);
  2219. return reqAndReload('PUT', current_url + name, paste_upload);
  2220. };
  2221. return;
  2222. }
  2223. }
  2224. });
  2225. var dragcounter = 0;
  2226. window.addEventListener('dragover', (e) => {
  2227. e.preventDefault();
  2228. e.stopPropagation();
  2229. });
  2230. window.addEventListener('dragenter', (e) => {
  2231. e.preventDefault();
  2232. e.stopPropagation();
  2233. if (!dragcounter) {
  2234. document.body.classList.add('dragging');
  2235. }
  2236. dragcounter++;
  2237. });
  2238. window.addEventListener('dragleave', (e) => {
  2239. e.preventDefault();
  2240. e.stopPropagation();
  2241. dragcounter--;
  2242. if (!dragcounter) {
  2243. document.body.classList.remove('dragging');
  2244. }
  2245. });
  2246. window.addEventListener('drop', (e) => {
  2247. e.preventDefault();
  2248. e.stopPropagation();
  2249. document.body.classList.remove('dragging');
  2250. dragcounter = 0;
  2251. const files = [...e.dataTransfer.items].map(item => item.getAsFile());
  2252. if (!files.length) return;
  2253. animateLoading();
  2254. (async () => {
  2255. for (var i = 0; i < files.length; i++) {
  2256. var f = files[i]
  2257. await req('PUT', current_url + encodeURIComponent(f.name), f);
  2258. }
  2259. window.setTimeout(() => {
  2260. stopLoading();
  2261. reloadListing();
  2262. }, 500);
  2263. })();
  2264. });
  2265. };
  2266. if (url = document.querySelector('html').getAttribute('data-webdav-url')) {
  2267. WebDAVNavigator(url, {
  2268. 'wopi_discovery_url': document.querySelector('html').getAttribute('data-wopi-discovery-url'),
  2269. });
  2270. }
  2271. :root {
  2272. --bg-color: #fff;
  2273. --fg-color: #000;
  2274. --g1-color: #eee;
  2275. --g2-color: #ccc;
  2276. --g3-color: #999;
  2277. --link-color: blue;
  2278. --visited-color: purple;
  2279. --active-color: darkred;
  2280. }
  2281. body {
  2282. text-align: center;
  2283. font-size: 1.1em;
  2284. font-family: Arial, Helvetica, sans-serif;
  2285. background: var(--bg-color);
  2286. color: var(--fg-color);
  2287. }
  2288. a:link {
  2289. color: var(--link-color);
  2290. }
  2291. a:visited {
  2292. color: var(--visited-color);
  2293. }
  2294. a:hover {
  2295. color: var(--active-color);
  2296. }
  2297. table {
  2298. margin: 2em auto;
  2299. border-collapse: collapse;
  2300. width: 90%;
  2301. }
  2302. th, td {
  2303. padding: .5em;
  2304. text-align: left;
  2305. border: 2px solid var(--g2-color);
  2306. }
  2307. th {
  2308. word-break: break-all;
  2309. }
  2310. td.thumb {
  2311. width: 5%;
  2312. }
  2313. td.buttons {
  2314. text-align: right;
  2315. width: 20em;
  2316. }
  2317. td.buttons div {
  2318. display: flex;
  2319. flex-direction: row-reverse;
  2320. }
  2321. table tr:nth-child(even) {
  2322. background: var(--g1-color);
  2323. }
  2324. .icon {
  2325. width: 2.6em;
  2326. height: 2.6em;
  2327. display: block;
  2328. border-radius: .2em;
  2329. background:var(--g3-color);
  2330. overflow: hidden;
  2331. color: var(--bg-color);
  2332. text-align: center;
  2333. }
  2334. .icon b {
  2335. font-weight: normal;
  2336. display: inline-block;
  2337. transform: rotate(-30deg);
  2338. line-height: 2.6rem;
  2339. }
  2340. .icon.JPEG, .icon.PNG, .icon.JPG, .icon.GIF, .icon.SVG, .icon.WEBP {
  2341. background: #966;
  2342. }
  2343. .icon.TXT, .icon.MD {
  2344. background: var(--fg-color);
  2345. }
  2346. .icon.MP4, .icon.MKV, .icon.MP3, .icon.M4A, .icon.WAV, .icon.FLAC, .icon.OGG, .icon.OGV, .icon.AAC, .icon.WEBM {
  2347. background: #669;
  2348. }
  2349. .icon.document {
  2350. background: #696;
  2351. }
  2352. .icon.PDF {
  2353. background: #969;
  2354. }
  2355. .icon.dir {
  2356. background: var(--g2-color);
  2357. color: var(--fg-color);
  2358. }
  2359. .icon.dir b {
  2360. font-size: 2em;
  2361. transform: none;
  2362. }
  2363. .size {
  2364. text-align: right;
  2365. }
  2366. input[type=button], input[type=submit], .btn {
  2367. font-size: 1.2em;
  2368. padding: .3em .5em;
  2369. margin: .2em .3em;
  2370. border: none;
  2371. background: var(--g2-color);
  2372. border-radius: .2em;
  2373. cursor: pointer;
  2374. text-decoration: none;
  2375. color: var(--fg-color) !important;
  2376. font-family: inherit;
  2377. }
  2378. td input[type=button], td input[type=submit], td .btn {
  2379. font-size: 1em;
  2380. }
  2381. input[type=text], textarea {
  2382. font-size: 1.2em;
  2383. padding: .3em .5em;
  2384. border: none;
  2385. background: var(--bg-color);
  2386. border-radius: .2em;
  2387. width: calc(100% - 1em);
  2388. color: var(--fg-color);
  2389. }
  2390. input:focus, textarea:focus {
  2391. box-shadow: 0px 0px 5px var(--active-color);
  2392. outline: 1px solid var(--active-color);
  2393. }
  2394. input[type=button]:hover, input[type=submit]:hover, .btn:hover {
  2395. color: var(--active-color);
  2396. text-decoration: underline;
  2397. background: var(--bg-color);
  2398. box-shadow: 0px 0px 5px var(--fg-color);
  2399. }
  2400. .close {
  2401. text-align: right;
  2402. margin: 0;
  2403. }
  2404. .close input {
  2405. font-size: .8em;
  2406. }
  2407. input[type=submit] {
  2408. float: right;
  2409. }
  2410. dialog {
  2411. position: fixed;
  2412. top: 1em;
  2413. right: 1em;
  2414. bottom: 1em;
  2415. left: 1em;
  2416. box-shadow: 0px 0px 5px var(--fg-color);
  2417. background: var(--g1-color);
  2418. color: var(--fg-color);
  2419. border: none;
  2420. border-radius: .5em;
  2421. }
  2422. dialog form div {
  2423. clear: both;
  2424. margin: 2em 0;
  2425. text-align: center;
  2426. }
  2427. .upload {
  2428. margin: 1em 0;
  2429. }
  2430. #mdp div, #mdp textarea {
  2431. width: calc(100% - 1em);
  2432. padding: .5em;
  2433. font-size: 1em;
  2434. height: calc(100% - 1em);
  2435. text-align: left;
  2436. margin: 0;
  2437. }
  2438. #md {
  2439. overflow: hidden;
  2440. overflow-x: auto;
  2441. }
  2442. #mdp {
  2443. display: grid;
  2444. grid-template-columns: 1fr 1fr;
  2445. grid-gap: .2em;
  2446. background: var(--g1-color);
  2447. height: 82vh;
  2448. }
  2449. dialog.preview {
  2450. height: calc(100%);
  2451. width: calc(100%);
  2452. top: 0;
  2453. left: 0;
  2454. right: 0;
  2455. bottom: 0;
  2456. padding: 0;
  2457. border-radius: 0;
  2458. background: var(--g1-color);
  2459. overflow: hidden;
  2460. }
  2461. iframe, .md_preview {
  2462. overflow: auto;
  2463. position: absolute;
  2464. top: 0;
  2465. left: 0;
  2466. right: 0;
  2467. bottom: 0;
  2468. padding: 0;
  2469. margin: 0;
  2470. width: 100%;
  2471. height: 100%;
  2472. border: none;
  2473. }
  2474. iframe, iframe body, .md_preview {
  2475. background-color: #fff;
  2476. color: #000;
  2477. }
  2478. .preview form {
  2479. height: calc(100% - 2em);
  2480. display: flex;
  2481. align-items: center;
  2482. justify-content: center;
  2483. }
  2484. .preview form > div {
  2485. width: calc(100vw);
  2486. height: 100%;
  2487. position: relative;
  2488. margin: 0;
  2489. display: flex;
  2490. align-items: center;
  2491. justify-content: center;
  2492. }
  2493. .preview div video {
  2494. max-width: 100%;
  2495. max-height: 100%;
  2496. }
  2497. .md_preview {
  2498. width: calc(100vw - 2em);
  2499. height: calc(100vh - 2em);
  2500. padding: 1em;
  2501. text-align: left;
  2502. }
  2503. .preview .close {
  2504. height: 2em;
  2505. text-align: center;
  2506. font-size: 1em;
  2507. display: block;
  2508. width: 100%;
  2509. margin: 0;
  2510. padding: 0;
  2511. border-radius: 0;
  2512. background: var(--g2-color);
  2513. color: var(--fg-color);
  2514. box-shadow: 0px 0px 5px var(--g2-color);
  2515. }
  2516. .preview img {
  2517. max-width: 95%;
  2518. max-height: 95%;
  2519. }
  2520. input[name=rename], input[name=paste_name] {
  2521. width: 30em;
  2522. }
  2523. .bg {
  2524. align-items: center;
  2525. justify-content: center;
  2526. position: fixed;
  2527. top: 0;
  2528. left: 0;
  2529. right: 0;
  2530. bottom: 0;
  2531. margin: 0;
  2532. padding: 0;
  2533. width: 0;
  2534. height: 0;
  2535. border: none;
  2536. align-items: center;
  2537. justify-content: center;
  2538. opacity: 0;
  2539. display: flex;
  2540. }
  2541. .loading .bg::after, .spinner span::after {
  2542. display: block;
  2543. content: " ";
  2544. width: 70px;
  2545. height: 70px;
  2546. border: 5px solid var(--g2-color);
  2547. border-radius: 50%;
  2548. border-top-color: var(--fg-color);
  2549. animation: spin 1s ease-in-out infinite;
  2550. filter: none;
  2551. }
  2552. .loading .bg::before {
  2553. display: block;
  2554. content: " ";
  2555. width: 70px;
  2556. height: 70px;
  2557. border: 20px solid var(--bg-color);
  2558. border-radius: 50%;
  2559. background: var(--bg-color);
  2560. position: absolute;
  2561. }
  2562. .spinner {
  2563. align-items: center;
  2564. justify-content: center;
  2565. display: flex;
  2566. }
  2567. .spinner span::after {
  2568. width: 30px;
  2569. height: 30px;
  2570. }
  2571. .loading .bg, .dragging .bg, .dialog .bg {
  2572. backdrop-filter: blur(5px);
  2573. background: rgba(0, 0, 0, 0.5);
  2574. opacity: 1;
  2575. width: 100%;
  2576. height: 100%;
  2577. }
  2578. dialog {
  2579. transition: all .3s;
  2580. }
  2581. progress {
  2582. height: 2em;
  2583. width: 90%;
  2584. }
  2585. @keyframes spin { to { transform: rotate(360deg); } }
  2586. @media screen and (max-width: 800px) {
  2587. .upload {
  2588. display: flex;
  2589. flex-direction: row;
  2590. justify-content: center;
  2591. flex-wrap: wrap;
  2592. }
  2593. body {
  2594. margin: 0;
  2595. font-size: 1em;
  2596. }
  2597. table {
  2598. margin: 2em 0;
  2599. width: 100%;
  2600. display: flex;
  2601. flex-direction: column;
  2602. }
  2603. table tr {
  2604. display: block;
  2605. border-top: 5px solid var(--bg-color);
  2606. padding: 0;
  2607. padding-left: 2em;
  2608. position: relative;
  2609. text-align: left;
  2610. min-height: 2.5em;
  2611. }
  2612. table td, table th {
  2613. border: none;
  2614. display: inline-block;
  2615. padding: .2em .5em;
  2616. }
  2617. table td.buttons {
  2618. display: block;
  2619. width: auto;
  2620. text-align: left;
  2621. }
  2622. td.buttons div {
  2623. display: inline-block;
  2624. }
  2625. table td.thumb {
  2626. padding: 0;
  2627. width: 2em;
  2628. position: absolute;
  2629. left: 0;
  2630. top: 0;
  2631. bottom: 0;
  2632. }
  2633. table th {
  2634. display: block;
  2635. }
  2636. .icon {
  2637. font-size: 12px;
  2638. height: 100%;
  2639. border-radius: 0;
  2640. }
  2641. .icon:not(.dir) b {
  2642. line-height: 3em;
  2643. display: block;
  2644. transform: translateX(-50%) translateY(-50%) rotate(-90deg);
  2645. font-size: 2em;
  2646. height: 3em;
  2647. position: absolute;
  2648. top: 50%;
  2649. left: 50%;
  2650. }
  2651. table th a {
  2652. font-size: 1.2em;
  2653. }
  2654. input[name=rename], input[name=paste_name] {
  2655. width: auto;
  2656. }
  2657. }
  2658. @media (prefers-color-scheme: dark) {
  2659. :root {
  2660. --bg-color: #000;
  2661. --fg-color: #fff;
  2662. --g1-color: #222;
  2663. --g2-color: #555;
  2664. --g3-color: #777;
  2665. --link-color: #99f;
  2666. --visited-color: #ccf;
  2667. --active-color: orange;
  2668. }
  2669. }
  2670. <?php } ?>