index.php 85 KB

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