index.php 88 KB

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