Server.php 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987
  1. <?php
  2. //
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2003 The PHP Group |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.02 of the PHP license, |
  9. // | that is bundled with this package in the file LICENSE, and is |
  10. // | available at through the world-wide-web at |
  11. // | http://www.php.net/license/2_02.txt. |
  12. // | If you did not receive a copy of the PHP license and are unable to |
  13. // | obtain it through the world-wide-web, please send a note to |
  14. // | [email protected] so we can mail you a copy immediately. |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Hartmut Holzgraefe <[email protected]> |
  17. // | Christian Stocker <[email protected]> |
  18. // +----------------------------------------------------------------------+
  19. //
  20. // $Id: Server.php,v 1.46 2006/03/03 21:43:09 hholzgra Exp $
  21. //
  22. require_once "HTTP/WebDAV/Tools/_parse_propfind.php";
  23. require_once "HTTP/WebDAV/Tools/_parse_proppatch.php";
  24. require_once "HTTP/WebDAV/Tools/_parse_lockinfo.php";
  25. /**
  26. * Virtual base class for implementing WebDAV servers
  27. *
  28. * WebDAV server base class, needs to be extended to do useful work
  29. *
  30. * @package HTTP_WebDAV_Server
  31. * @author Hartmut Holzgraefe <[email protected]>
  32. * @version 0.99.1dev
  33. */
  34. class HTTP_WebDAV_Server
  35. {
  36. // {{{ Member Variables
  37. /**
  38. * complete URI for this request
  39. *
  40. * @var string
  41. */
  42. var $uri;
  43. /**
  44. * base URI for this request
  45. *
  46. * @var string
  47. */
  48. var $base_uri;
  49. /**
  50. * URI path for this request
  51. *
  52. * @var string
  53. */
  54. var $path;
  55. /**
  56. * Realm string to be used in authentification popups
  57. *
  58. * @var string
  59. */
  60. var $http_auth_realm = "PHP WebDAV";
  61. /**
  62. * String to be used in "X-Dav-Powered-By" header
  63. *
  64. * @var string
  65. */
  66. var $dav_powered_by = "";
  67. /**
  68. * Remember parsed If: (RFC2518/9.4) header conditions
  69. *
  70. * @var array
  71. */
  72. var $_if_header_uris = array();
  73. /**
  74. * HTTP response status/message
  75. *
  76. * @var string
  77. */
  78. var $_http_status = "200 OK";
  79. /**
  80. * encoding of property values passed in
  81. *
  82. * @var string
  83. */
  84. var $_prop_encoding = "utf-8";
  85. // }}}
  86. // {{{ Constructor
  87. /**
  88. * Constructor
  89. *
  90. * @param void
  91. */
  92. function HTTP_WebDAV_Server()
  93. {
  94. // PHP messages destroy XML output -> switch them off
  95. ini_set("display_errors", 0);
  96. }
  97. // }}}
  98. // {{{ ServeRequest()
  99. /**
  100. * Serve WebDAV HTTP request
  101. *
  102. * dispatch WebDAV HTTP request to the apropriate method handler
  103. *
  104. * @param void
  105. * @return void
  106. */
  107. function ServeRequest()
  108. {
  109. // prevent warning in litmus check 'delete_fragment'
  110. if (strstr($_SERVER["REQUEST_URI"], '#')) {
  111. $this->http_status("400 Bad Request");
  112. return;
  113. }
  114. // default uri is the complete request uri
  115. $uri = (@$_SERVER["HTTPS"] === "on" ? "https:" : "http:");
  116. $uri.= "//$_SERVER[HTTP_HOST]$_SERVER[SCRIPT_NAME]";
  117. $path_info = empty($_SERVER["PATH_INFO"]) ? "/" : $_SERVER["PATH_INFO"];
  118. $this->base_uri = $uri;
  119. $this->uri = $uri . $path_info;
  120. // set path
  121. $this->path = $this->_urldecode($path_info);
  122. if (!strlen($this->path)) {
  123. if ($_SERVER["REQUEST_METHOD"] == "GET") {
  124. // redirect clients that try to GET a collection
  125. // WebDAV clients should never try this while
  126. // regular HTTP clients might ...
  127. header("Location: ".$this->base_uri."/");
  128. return;
  129. } else {
  130. // if a WebDAV client didn't give a path we just assume '/'
  131. $this->path = "/";
  132. }
  133. }
  134. if(ini_get("magic_quotes_gpc")) {
  135. $this->path = stripslashes($this->path);
  136. }
  137. // identify ourselves
  138. if (empty($this->dav_powered_by)) {
  139. header("X-Dav-Powered-By: PHP class: ".get_class($this));
  140. } else {
  141. header("X-Dav-Powered-By: ".$this->dav_powered_by );
  142. }
  143. // check authentication
  144. // for the motivation for not checking OPTIONS requests on / see
  145. // http://pear.php.net/bugs/bug.php?id=5363
  146. if ( ( !(($_SERVER['REQUEST_METHOD'] == 'OPTIONS') && ($this->path == "/")))
  147. && (!$this->_check_auth())) {
  148. // RFC2518 says we must use Digest instead of Basic
  149. // but Microsoft Clients do not support Digest
  150. // and we don't support NTLM and Kerberos
  151. // so we are stuck with Basic here
  152. header('WWW-Authenticate: Basic realm="'.($this->http_auth_realm).'"');
  153. // Windows seems to require this being the last header sent
  154. // (changed according to PECL bug #3138)
  155. $this->http_status('401 Unauthorized');
  156. return;
  157. }
  158. // check
  159. if(! $this->_check_if_header_conditions()) {
  160. return;
  161. }
  162. // detect requested method names
  163. $method = strtolower($_SERVER["REQUEST_METHOD"]);
  164. $wrapper = "http_".$method;
  165. // activate HEAD emulation by GET if no HEAD method found
  166. if ($method == "head" && !method_exists($this, "head")) {
  167. $method = "get";
  168. }
  169. if (method_exists($this, $wrapper) && ($method == "options" || method_exists($this, $method))) {
  170. $this->$wrapper(); // call method by name
  171. } else { // method not found/implemented
  172. if ($_SERVER["REQUEST_METHOD"] == "LOCK") {
  173. $this->http_status("412 Precondition failed");
  174. } else {
  175. $this->http_status("405 Method not allowed");
  176. header("Allow: ".join(", ", $this->_allow())); // tell client what's allowed
  177. }
  178. }
  179. }
  180. // }}}
  181. // {{{ abstract WebDAV methods
  182. // {{{ GET()
  183. /**
  184. * GET implementation
  185. *
  186. * overload this method to retrieve resources from your server
  187. * <br>
  188. *
  189. *
  190. * @abstract
  191. * @param array &$params Array of input and output parameters
  192. * <br><b>input</b><ul>
  193. * <li> path -
  194. * </ul>
  195. * <br><b>output</b><ul>
  196. * <li> size -
  197. * </ul>
  198. * @returns int HTTP-Statuscode
  199. */
  200. /* abstract
  201. function GET(&$params)
  202. {
  203. // dummy entry for PHPDoc
  204. }
  205. */
  206. // }}}
  207. // {{{ PUT()
  208. /**
  209. * PUT implementation
  210. *
  211. * PUT implementation
  212. *
  213. * @abstract
  214. * @param array &$params
  215. * @returns int HTTP-Statuscode
  216. */
  217. /* abstract
  218. function PUT()
  219. {
  220. // dummy entry for PHPDoc
  221. }
  222. */
  223. // }}}
  224. // {{{ COPY()
  225. /**
  226. * COPY implementation
  227. *
  228. * COPY implementation
  229. *
  230. * @abstract
  231. * @param array &$params
  232. * @returns int HTTP-Statuscode
  233. */
  234. /* abstract
  235. function COPY()
  236. {
  237. // dummy entry for PHPDoc
  238. }
  239. */
  240. // }}}
  241. // {{{ MOVE()
  242. /**
  243. * MOVE implementation
  244. *
  245. * MOVE implementation
  246. *
  247. * @abstract
  248. * @param array &$params
  249. * @returns int HTTP-Statuscode
  250. */
  251. /* abstract
  252. function MOVE()
  253. {
  254. // dummy entry for PHPDoc
  255. }
  256. */
  257. // }}}
  258. // {{{ DELETE()
  259. /**
  260. * DELETE implementation
  261. *
  262. * DELETE implementation
  263. *
  264. * @abstract
  265. * @param array &$params
  266. * @returns int HTTP-Statuscode
  267. */
  268. /* abstract
  269. function DELETE()
  270. {
  271. // dummy entry for PHPDoc
  272. }
  273. */
  274. // }}}
  275. // {{{ PROPFIND()
  276. /**
  277. * PROPFIND implementation
  278. *
  279. * PROPFIND implementation
  280. *
  281. * @abstract
  282. * @param array &$params
  283. * @returns int HTTP-Statuscode
  284. */
  285. /* abstract
  286. function PROPFIND()
  287. {
  288. // dummy entry for PHPDoc
  289. }
  290. */
  291. // }}}
  292. // {{{ PROPPATCH()
  293. /**
  294. * PROPPATCH implementation
  295. *
  296. * PROPPATCH implementation
  297. *
  298. * @abstract
  299. * @param array &$params
  300. * @returns int HTTP-Statuscode
  301. */
  302. /* abstract
  303. function PROPPATCH()
  304. {
  305. // dummy entry for PHPDoc
  306. }
  307. */
  308. // }}}
  309. // {{{ LOCK()
  310. /**
  311. * LOCK implementation
  312. *
  313. * LOCK implementation
  314. *
  315. * @abstract
  316. * @param array &$params
  317. * @returns int HTTP-Statuscode
  318. */
  319. /* abstract
  320. function LOCK()
  321. {
  322. // dummy entry for PHPDoc
  323. }
  324. */
  325. // }}}
  326. // {{{ UNLOCK()
  327. /**
  328. * UNLOCK implementation
  329. *
  330. * UNLOCK implementation
  331. *
  332. * @abstract
  333. * @param array &$params
  334. * @returns int HTTP-Statuscode
  335. */
  336. /* abstract
  337. function UNLOCK()
  338. {
  339. // dummy entry for PHPDoc
  340. }
  341. */
  342. // }}}
  343. // }}}
  344. // {{{ other abstract methods
  345. // {{{ check_auth()
  346. /**
  347. * check authentication
  348. *
  349. * overload this method to retrieve and confirm authentication information
  350. *
  351. * @abstract
  352. * @param string type Authentication type, e.g. "basic" or "digest"
  353. * @param string username Transmitted username
  354. * @param string passwort Transmitted password
  355. * @returns bool Authentication status
  356. */
  357. /* abstract
  358. function checkAuth($type, $username, $password)
  359. {
  360. // dummy entry for PHPDoc
  361. }
  362. */
  363. // }}}
  364. // {{{ checklock()
  365. /**
  366. * check lock status for a resource
  367. *
  368. * overload this method to return shared and exclusive locks
  369. * active for this resource
  370. *
  371. * @abstract
  372. * @param string resource Resource path to check
  373. * @returns array An array of lock entries each consisting
  374. * of 'type' ('shared'/'exclusive'), 'token' and 'timeout'
  375. */
  376. /* abstract
  377. function checklock($resource)
  378. {
  379. // dummy entry for PHPDoc
  380. }
  381. */
  382. // }}}
  383. // }}}
  384. // {{{ WebDAV HTTP method wrappers
  385. // {{{ http_OPTIONS()
  386. /**
  387. * OPTIONS method handler
  388. *
  389. * The OPTIONS method handler creates a valid OPTIONS reply
  390. * including Dav: and Allowed: heaers
  391. * based on the implemented methods found in the actual instance
  392. *
  393. * @param void
  394. * @return void
  395. */
  396. function http_OPTIONS()
  397. {
  398. // Microsoft clients default to the Frontpage protocol
  399. // unless we tell them to use WebDAV
  400. header("MS-Author-Via: DAV");
  401. // get allowed methods
  402. $allow = $this->_allow();
  403. // dav header
  404. $dav = array(1); // assume we are always dav class 1 compliant
  405. if (isset($allow['LOCK'])) {
  406. $dav[] = 2; // dav class 2 requires that locking is supported
  407. }
  408. // tell clients what we found
  409. $this->http_status("200 OK");
  410. header("DAV: " .join("," , $dav));
  411. header("Allow: ".join(", ", $allow));
  412. header("Content-length: 0");
  413. }
  414. // }}}
  415. // {{{ http_PROPFIND()
  416. /**
  417. * PROPFIND method handler
  418. *
  419. * @param void
  420. * @return void
  421. */
  422. function http_PROPFIND()
  423. {
  424. $options = Array();
  425. $options["path"] = $this->path;
  426. // search depth from header (default is "infinity)
  427. if (isset($_SERVER['HTTP_DEPTH'])) {
  428. $options["depth"] = $_SERVER["HTTP_DEPTH"];
  429. } else {
  430. $options["depth"] = "infinity";
  431. }
  432. // analyze request payload
  433. $propinfo = new _parse_propfind("php://input");
  434. if (!$propinfo->success) {
  435. $this->http_status("400 Error");
  436. return;
  437. }
  438. $options['props'] = $propinfo->props;
  439. // call user handler
  440. if (!$this->PROPFIND($options, $files)) {
  441. $this->http_status("404 Not Found");
  442. return;
  443. }
  444. // collect namespaces here
  445. $ns_hash = array();
  446. // Microsoft Clients need this special namespace for date and time values
  447. $ns_defs = "xmlns:ns0=\"urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/\"";
  448. // now we loop over all returned file entries
  449. foreach($files["files"] as $filekey => $file) {
  450. // nothing to do if no properties were returend for a file
  451. if (!isset($file["props"]) || !is_array($file["props"])) {
  452. continue;
  453. }
  454. // now loop over all returned properties
  455. foreach($file["props"] as $key => $prop) {
  456. // as a convenience feature we do not require that user handlers
  457. // restrict returned properties to the requested ones
  458. // here we strip all unrequested entries out of the response
  459. switch($options['props']) {
  460. case "all":
  461. // nothing to remove
  462. break;
  463. case "names":
  464. // only the names of all existing properties were requested
  465. // so we remove all values
  466. unset($files["files"][$filekey]["props"][$key]["val"]);
  467. break;
  468. default:
  469. $found = false;
  470. // search property name in requested properties
  471. foreach((array)$options["props"] as $reqprop) {
  472. if ( $reqprop["name"] == $prop["name"]
  473. && @$reqprop["xmlns"] == $prop["ns"]) {
  474. $found = true;
  475. break;
  476. }
  477. }
  478. // unset property and continue with next one if not found/requested
  479. if (!$found) {
  480. $files["files"][$filekey]["props"][$key]="";
  481. continue(2);
  482. }
  483. break;
  484. }
  485. // namespace handling
  486. if (empty($prop["ns"])) continue; // no namespace
  487. $ns = $prop["ns"];
  488. if ($ns == "DAV:") continue; // default namespace
  489. if (isset($ns_hash[$ns])) continue; // already known
  490. // register namespace
  491. $ns_name = "ns".(count($ns_hash) + 1);
  492. $ns_hash[$ns] = $ns_name;
  493. $ns_defs .= " xmlns:$ns_name=\"$ns\"";
  494. }
  495. // we also need to add empty entries for properties that were requested
  496. // but for which no values where returned by the user handler
  497. if (is_array($options['props'])) {
  498. foreach($options["props"] as $reqprop) {
  499. if($reqprop['name']=="") continue; // skip empty entries
  500. $found = false;
  501. // check if property exists in result
  502. foreach($file["props"] as $prop) {
  503. if ( $reqprop["name"] == $prop["name"]
  504. && @$reqprop["xmlns"] == $prop["ns"]) {
  505. $found = true;
  506. break;
  507. }
  508. }
  509. if (!$found) {
  510. if($reqprop["xmlns"]==="DAV:" && $reqprop["name"]==="lockdiscovery") {
  511. // lockdiscovery is handled by the base class
  512. $files["files"][$filekey]["props"][]
  513. = $this->mkprop("DAV:",
  514. "lockdiscovery" ,
  515. $this->lockdiscovery($files["files"][$filekey]['path']));
  516. } else {
  517. // add empty value for this property
  518. $files["files"][$filekey]["noprops"][] =
  519. $this->mkprop($reqprop["xmlns"], $reqprop["name"], "");
  520. // register property namespace if not known yet
  521. if ($reqprop["xmlns"] != "DAV:" && !isset($ns_hash[$reqprop["xmlns"]])) {
  522. $ns_name = "ns".(count($ns_hash) + 1);
  523. $ns_hash[$reqprop["xmlns"]] = $ns_name;
  524. $ns_defs .= " xmlns:$ns_name=\"$reqprop[xmlns]\"";
  525. }
  526. }
  527. }
  528. }
  529. }
  530. }
  531. // now we generate the reply header ...
  532. $this->http_status("207 Multi-Status");
  533. header('Content-Type: text/xml; charset="utf-8"');
  534. // ... and payload
  535. echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  536. echo "<D:multistatus xmlns:D=\"DAV:\">\n";
  537. foreach($files["files"] as $file) {
  538. // ignore empty or incomplete entries
  539. if(!is_array($file) || empty($file) || !isset($file["path"])) continue;
  540. $path = $file['path'];
  541. if(!is_string($path) || $path==="") continue;
  542. echo " <D:response $ns_defs>\n";
  543. /* TODO right now the user implementation has to make sure
  544. collections end in a slash, this should be done in here
  545. by checking the resource attribute */
  546. $href = $this->_mergePathes($_SERVER['SCRIPT_NAME'], $path);
  547. echo " <D:href>$href</D:href>\n";
  548. // report all found properties and their values (if any)
  549. if (isset($file["props"]) && is_array($file["props"])) {
  550. echo " <D:propstat>\n";
  551. echo " <D:prop>\n";
  552. foreach($file["props"] as $key => $prop) {
  553. if (!is_array($prop)) continue;
  554. if (!isset($prop["name"])) continue;
  555. if (!isset($prop["val"]) || $prop["val"] === "" || $prop["val"] === false) {
  556. // empty properties (cannot use empty() for check as "0" is a legal value here)
  557. if($prop["ns"]=="DAV:") {
  558. echo " <D:$prop[name]/>\n";
  559. } else if(!empty($prop["ns"])) {
  560. echo " <".$ns_hash[$prop["ns"]].":$prop[name]/>\n";
  561. } else {
  562. echo " <$prop[name] xmlns=\"\"/>";
  563. }
  564. } else if ($prop["ns"] == "DAV:") {
  565. // some WebDAV properties need special treatment
  566. switch ($prop["name"]) {
  567. case "creationdate":
  568. echo " <D:creationdate ns0:dt=\"dateTime.tz\">"
  569. . gmdate("Y-m-d\\TH:i:s\\Z",$prop['val'])
  570. . "</D:creationdate>\n";
  571. break;
  572. case "getlastmodified":
  573. echo " <D:getlastmodified ns0:dt=\"dateTime.rfc1123\">"
  574. . gmdate("D, d M Y H:i:s ", $prop['val'])
  575. . "GMT</D:getlastmodified>\n";
  576. break;
  577. case "resourcetype":
  578. echo " <D:resourcetype><D:$prop[val]/></D:resourcetype>\n";
  579. break;
  580. case "supportedlock":
  581. echo " <D:supportedlock>$prop[val]</D:supportedlock>\n";
  582. break;
  583. case "lockdiscovery":
  584. echo " <D:lockdiscovery>\n";
  585. echo $prop["val"];
  586. echo " </D:lockdiscovery>\n";
  587. break;
  588. default:
  589. echo " <D:$prop[name]>"
  590. . $this->_prop_encode(htmlspecialchars($prop['val']))
  591. . "</D:$prop[name]>\n";
  592. break;
  593. }
  594. } else {
  595. // properties from namespaces != "DAV:" or without any namespace
  596. if ($prop["ns"]) {
  597. echo " <" . $ns_hash[$prop["ns"]] . ":$prop[name]>"
  598. . $this->_prop_encode(htmlspecialchars($prop['val']))
  599. . "</" . $ns_hash[$prop["ns"]] . ":$prop[name]>\n";
  600. } else {
  601. echo " <$prop[name] xmlns=\"\">"
  602. . $this->_prop_encode(htmlspecialchars($prop['val']))
  603. . "</$prop[name]>\n";
  604. }
  605. }
  606. }
  607. echo " </D:prop>\n";
  608. echo " <D:status>HTTP/1.1 200 OK</D:status>\n";
  609. echo " </D:propstat>\n";
  610. }
  611. // now report all properties requested but not found
  612. if (isset($file["noprops"])) {
  613. echo " <D:propstat>\n";
  614. echo " <D:prop>\n";
  615. foreach($file["noprops"] as $key => $prop) {
  616. if ($prop["ns"] == "DAV:") {
  617. echo " <D:$prop[name]/>\n";
  618. } else if ($prop["ns"] == "") {
  619. echo " <$prop[name] xmlns=\"\"/>\n";
  620. } else {
  621. echo " <" . $ns_hash[$prop["ns"]] . ":$prop[name]/>\n";
  622. }
  623. }
  624. echo " </D:prop>\n";
  625. echo " <D:status>HTTP/1.1 404 Not Found</D:status>\n";
  626. echo " </D:propstat>\n";
  627. }
  628. echo " </D:response>\n";
  629. }
  630. echo "</D:multistatus>\n";
  631. }
  632. // }}}
  633. // {{{ http_PROPPATCH()
  634. /**
  635. * PROPPATCH method handler
  636. *
  637. * @param void
  638. * @return void
  639. */
  640. function http_PROPPATCH()
  641. {
  642. if($this->_check_lock_status($this->path)) {
  643. $options = Array();
  644. $options["path"] = $this->path;
  645. $propinfo = new _parse_proppatch("php://input");
  646. if (!$propinfo->success) {
  647. $this->http_status("400 Error");
  648. return;
  649. }
  650. $options['props'] = $propinfo->props;
  651. $responsedescr = $this->PROPPATCH($options);
  652. $this->http_status("207 Multi-Status");
  653. header('Content-Type: text/xml; charset="utf-8"');
  654. echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  655. echo "<D:multistatus xmlns:D=\"DAV:\">\n";
  656. echo " <D:response>\n";
  657. echo " <D:href>".$this->_urlencode($this->_mergePathes($_SERVER["SCRIPT_NAME"], $this->path))."</D:href>\n";
  658. foreach($options["props"] as $prop) {
  659. echo " <D:propstat>\n";
  660. echo " <D:prop><$prop[name] xmlns=\"$prop[ns]\"/></D:prop>\n";
  661. echo " <D:status>HTTP/1.1 $prop[status]</D:status>\n";
  662. echo " </D:propstat>\n";
  663. }
  664. if ($responsedescr) {
  665. echo " <D:responsedescription>".
  666. $this->_prop_encode(htmlspecialchars($responsedescr)).
  667. "</D:responsedescription>\n";
  668. }
  669. echo " </D:response>\n";
  670. echo "</D:multistatus>\n";
  671. } else {
  672. $this->http_status("423 Locked");
  673. }
  674. }
  675. // }}}
  676. // {{{ http_MKCOL()
  677. /**
  678. * MKCOL method handler
  679. *
  680. * @param void
  681. * @return void
  682. */
  683. function http_MKCOL()
  684. {
  685. $options = Array();
  686. $options["path"] = $this->path;
  687. $stat = $this->MKCOL($options);
  688. $this->http_status($stat);
  689. }
  690. // }}}
  691. // {{{ http_GET()
  692. /**
  693. * GET method handler
  694. *
  695. * @param void
  696. * @returns void
  697. */
  698. function http_GET()
  699. {
  700. // TODO check for invalid stream
  701. $options = Array();
  702. $options["path"] = $this->path;
  703. $this->_get_ranges($options);
  704. if (true === ($status = $this->GET($options))) {
  705. if (!headers_sent()) {
  706. $status = "200 OK";
  707. if (!isset($options['mimetype'])) {
  708. $options['mimetype'] = "application/octet-stream";
  709. }
  710. header("Content-type: $options[mimetype]");
  711. if (isset($options['mtime'])) {
  712. header("Last-modified:".gmdate("D, d M Y H:i:s ", $options['mtime'])."GMT");
  713. }
  714. if (isset($options['stream'])) {
  715. // GET handler returned a stream
  716. if (!empty($options['ranges']) && (0===fseek($options['stream'], 0, SEEK_SET))) {
  717. // partial request and stream is seekable
  718. if (count($options['ranges']) === 1) {
  719. $range = $options['ranges'][0];
  720. if (isset($range['start'])) {
  721. fseek($options['stream'], $range['start'], SEEK_SET);
  722. if (feof($options['stream'])) {
  723. $this->http_status("416 Requested range not satisfiable");
  724. return;
  725. }
  726. if (isset($range['end'])) {
  727. $size = $range['end']-$range['start']+1;
  728. $this->http_status("206 partial");
  729. header("Content-length: $size");
  730. header("Content-range: $range[start]-$range[end]/"
  731. . (isset($options['size']) ? $options['size'] : "*"));
  732. while ($size && !feof($options['stream'])) {
  733. $buffer = fread($options['stream'], 4096);
  734. $size -= strlen($buffer);
  735. echo $buffer;
  736. }
  737. } else {
  738. $this->http_status("206 partial");
  739. if (isset($options['size'])) {
  740. header("Content-length: ".($options['size'] - $range['start']));
  741. header("Content-range: $start-$end/"
  742. . (isset($options['size']) ? $options['size'] : "*"));
  743. }
  744. fpassthru($options['stream']);
  745. }
  746. } else {
  747. header("Content-length: ".$range['last']);
  748. fseek($options['stream'], -$range['last'], SEEK_END);
  749. fpassthru($options['stream']);
  750. }
  751. } else {
  752. $this->_multipart_byterange_header(); // init multipart
  753. foreach ($options['ranges'] as $range) {
  754. // TODO what if size unknown? 500?
  755. if (isset($range['start'])) {
  756. $from = $range['start'];
  757. $to = !empty($range['end']) ? $range['end'] : $options['size']-1;
  758. } else {
  759. $from = $options['size'] - $range['last']-1;
  760. $to = $options['size'] -1;
  761. }
  762. $total = isset($options['size']) ? $options['size'] : "*";
  763. $size = $to - $from + 1;
  764. $this->_multipart_byterange_header($options['mimetype'], $from, $to, $total);
  765. fseek($options['stream'], $start, SEEK_SET);
  766. while ($size && !feof($options['stream'])) {
  767. $buffer = fread($options['stream'], 4096);
  768. $size -= strlen($buffer);
  769. echo $buffer;
  770. }
  771. }
  772. $this->_multipart_byterange_header(); // end multipart
  773. }
  774. } else {
  775. // normal request or stream isn't seekable, return full content
  776. if (isset($options['size'])) {
  777. header("Content-length: ".$options['size']);
  778. }
  779. fpassthru($options['stream']);
  780. return; // no more headers
  781. }
  782. } elseif (isset($options['data'])) {
  783. if (is_array($options['data'])) {
  784. // reply to partial request
  785. } else {
  786. header("Content-length: ".strlen($options['data']));
  787. echo $options['data'];
  788. }
  789. }
  790. }
  791. }
  792. if (!headers_sent()) {
  793. if (false === $status) {
  794. $this->http_status("404 not found");
  795. } else {
  796. // TODO: check setting of headers in various code pathes above
  797. $this->http_status("$status");
  798. }
  799. }
  800. }
  801. /**
  802. * parse HTTP Range: header
  803. *
  804. * @param array options array to store result in
  805. * @return void
  806. */
  807. function _get_ranges(&$options)
  808. {
  809. // process Range: header if present
  810. if (isset($_SERVER['HTTP_RANGE'])) {
  811. // we only support standard "bytes" range specifications for now
  812. if (preg_match('/bytes\s*=\s*(.+)/', $_SERVER['HTTP_RANGE'], $matches)) {
  813. $options["ranges"] = array();
  814. // ranges are comma separated
  815. foreach (explode(",", $matches[1]) as $range) {
  816. // ranges are either from-to pairs or just end positions
  817. list($start, $end) = explode("-", $range);
  818. $options["ranges"][] = ($start==="")
  819. ? array("last"=>$end)
  820. : array("start"=>$start, "end"=>$end);
  821. }
  822. }
  823. }
  824. }
  825. /**
  826. * generate separator headers for multipart response
  827. *
  828. * first and last call happen without parameters to generate
  829. * the initial header and closing sequence, all calls inbetween
  830. * require content mimetype, start and end byte position and
  831. * optionaly the total byte length of the requested resource
  832. *
  833. * @param string mimetype
  834. * @param int start byte position
  835. * @param int end byte position
  836. * @param int total resource byte size
  837. */
  838. function _multipart_byterange_header($mimetype = false, $from = false, $to=false, $total=false)
  839. {
  840. if ($mimetype === false) {
  841. if (!isset($this->multipart_separator)) {
  842. // initial
  843. // a little naive, this sequence *might* be part of the content
  844. // but it's really not likely and rather expensive to check
  845. $this->multipart_separator = "SEPARATOR_".md5(microtime());
  846. // generate HTTP header
  847. header("Content-type: multipart/byteranges; boundary=".$this->multipart_separator);
  848. } else {
  849. // final
  850. // generate closing multipart sequence
  851. echo "\n--{$this->multipart_separator}--";
  852. }
  853. } else {
  854. // generate separator and header for next part
  855. echo "\n--{$this->multipart_separator}\n";
  856. echo "Content-type: $mimetype\n";
  857. echo "Content-range: $from-$to/". ($total === false ? "*" : $total);
  858. echo "\n\n";
  859. }
  860. }
  861. // }}}
  862. // {{{ http_HEAD()
  863. /**
  864. * HEAD method handler
  865. *
  866. * @param void
  867. * @return void
  868. */
  869. function http_HEAD()
  870. {
  871. $status = false;
  872. $options = Array();
  873. $options["path"] = $this->path;
  874. if (method_exists($this, "HEAD")) {
  875. $status = $this->head($options);
  876. } else if (method_exists($this, "GET")) {
  877. ob_start();
  878. $status = $this->GET($options);
  879. if (!isset($options['size'])) {
  880. $options['size'] = ob_get_length();
  881. }
  882. ob_end_clean();
  883. }
  884. if (isset($options['size'])) {
  885. header("Content-length: ".$options['size']);
  886. }
  887. if($status===true) $status = "200 OK";
  888. if($status===false) $status = "404 Not found";
  889. $this->http_status($status);
  890. }
  891. // }}}
  892. // {{{ http_PUT()
  893. /**
  894. * PUT method handler
  895. *
  896. * @param void
  897. * @return void
  898. */
  899. function http_PUT()
  900. {
  901. if ($this->_check_lock_status($this->path)) {
  902. $options = Array();
  903. $options["path"] = $this->path;
  904. $options["content_length"] = $_SERVER["CONTENT_LENGTH"];
  905. // get the Content-type
  906. if (isset($_SERVER["CONTENT_TYPE"])) {
  907. // for now we do not support any sort of multipart requests
  908. if (!strncmp($_SERVER["CONTENT_TYPE"], "multipart/", 10)) {
  909. $this->http_status("501 not implemented");
  910. echo "The service does not support mulipart PUT requests";
  911. return;
  912. }
  913. $options["content_type"] = $_SERVER["CONTENT_TYPE"];
  914. } else {
  915. // default content type if none given
  916. $options["content_type"] = "application/octet-stream";
  917. }
  918. /* RFC 2616 2.6 says: "The recipient of the entity MUST NOT
  919. ignore any Content-* (e.g. Content-Range) headers that it
  920. does not understand or implement and MUST return a 501
  921. (Not Implemented) response in such cases."
  922. */
  923. foreach ($_SERVER as $key => $val) {
  924. if (strncmp($key, "HTTP_CONTENT", 11)) continue;
  925. switch ($key) {
  926. case 'HTTP_CONTENT_ENCODING': // RFC 2616 14.11
  927. // TODO support this if ext/zlib filters are available
  928. $this->http_status("501 not implemented");
  929. echo "The service does not support '$val' content encoding";
  930. return;
  931. case 'HTTP_CONTENT_LANGUAGE': // RFC 2616 14.12
  932. // we assume it is not critical if this one is ignored
  933. // in the actual PUT implementation ...
  934. $options["content_language"] = $value;
  935. break;
  936. case 'HTTP_CONTENT_LOCATION': // RFC 2616 14.14
  937. /* The meaning of the Content-Location header in PUT
  938. or POST requests is undefined; servers are free
  939. to ignore it in those cases. */
  940. break;
  941. case 'HTTP_CONTENT_RANGE': // RFC 2616 14.16
  942. // single byte range requests are supported
  943. // the header format is also specified in RFC 2616 14.16
  944. // TODO we have to ensure that implementations support this or send 501 instead
  945. if (!preg_match('@bytes\s+(\d+)-(\d+)/((\d+)|\*)@', $val, $matches)) {
  946. $this->http_status("400 bad request");
  947. echo "The service does only support single byte ranges";
  948. return;
  949. }
  950. $range = array("start"=>$matches[1], "end"=>$matches[2]);
  951. if (is_numeric($matches[3])) {
  952. $range["total_length"] = $matches[3];
  953. }
  954. $option["ranges"][] = $range;
  955. // TODO make sure the implementation supports partial PUT
  956. // this has to be done in advance to avoid data being overwritten
  957. // on implementations that do not support this ...
  958. break;
  959. case 'HTTP_CONTENT_MD5': // RFC 2616 14.15
  960. // TODO: maybe we can just pretend here?
  961. $this->http_status("501 not implemented");
  962. echo "The service does not support content MD5 checksum verification";
  963. return;
  964. default:
  965. // any other unknown Content-* headers
  966. $this->http_status("501 not implemented");
  967. echo "The service does not support '$key'";
  968. return;
  969. }
  970. }
  971. $options["stream"] = fopen("php://input", "r");
  972. $stat = $this->PUT($options);
  973. if ($stat === false) {
  974. $stat = "403 Forbidden";
  975. } else if (is_resource($stat) && get_resource_type($stat) == "stream") {
  976. $stream = $stat;
  977. $stat = $options["new"] ? "201 Created" : "204 No Content";
  978. if (!empty($options["ranges"])) {
  979. // TODO multipart support is missing (see also above)
  980. if (0 == fseek($stream, $range[0]["start"], SEEK_SET)) {
  981. $length = $range[0]["end"]-$range[0]["start"]+1;
  982. if (!fwrite($stream, fread($options["stream"], $length))) {
  983. $stat = "403 Forbidden";
  984. }
  985. } else {
  986. $stat = "403 Forbidden";
  987. }
  988. } else {
  989. while (!feof($options["stream"])) {
  990. if (false === fwrite($stream, fread($options["stream"], 4096))) {
  991. $stat = "403 Forbidden";
  992. break;
  993. }
  994. }
  995. }
  996. fclose($stream);
  997. }
  998. $this->http_status($stat);
  999. } else {
  1000. $this->http_status("423 Locked");
  1001. }
  1002. }
  1003. // }}}
  1004. // {{{ http_DELETE()
  1005. /**
  1006. * DELETE method handler
  1007. *
  1008. * @param void
  1009. * @return void
  1010. */
  1011. function http_DELETE()
  1012. {
  1013. // check RFC 2518 Section 9.2, last paragraph
  1014. if (isset($_SERVER["HTTP_DEPTH"])) {
  1015. if ($_SERVER["HTTP_DEPTH"] != "infinity") {
  1016. $this->http_status("400 Bad Request");
  1017. return;
  1018. }
  1019. }
  1020. // check lock status
  1021. if ($this->_check_lock_status($this->path)) {
  1022. // ok, proceed
  1023. $options = Array();
  1024. $options["path"] = $this->path;
  1025. $stat = $this->DELETE($options);
  1026. $this->http_status($stat);
  1027. } else {
  1028. // sorry, its locked
  1029. $this->http_status("423 Locked");
  1030. }
  1031. }
  1032. // }}}
  1033. // {{{ http_COPY()
  1034. /**
  1035. * COPY method handler
  1036. *
  1037. * @param void
  1038. * @return void
  1039. */
  1040. function http_COPY()
  1041. {
  1042. // no need to check source lock status here
  1043. // destination lock status is always checked by the helper method
  1044. $this->_copymove("copy");
  1045. }
  1046. // }}}
  1047. // {{{ http_MOVE()
  1048. /**
  1049. * MOVE method handler
  1050. *
  1051. * @param void
  1052. * @return void
  1053. */
  1054. function http_MOVE()
  1055. {
  1056. if ($this->_check_lock_status($this->path)) {
  1057. // destination lock status is always checked by the helper method
  1058. $this->_copymove("move");
  1059. } else {
  1060. $this->http_status("423 Locked");
  1061. }
  1062. }
  1063. // }}}
  1064. // {{{ http_LOCK()
  1065. /**
  1066. * LOCK method handler
  1067. *
  1068. * @param void
  1069. * @return void
  1070. */
  1071. function http_LOCK()
  1072. {
  1073. $options = Array();
  1074. $options["path"] = $this->path;
  1075. if (isset($_SERVER['HTTP_DEPTH'])) {
  1076. $options["depth"] = $_SERVER["HTTP_DEPTH"];
  1077. } else {
  1078. $options["depth"] = "infinity";
  1079. }
  1080. if (isset($_SERVER["HTTP_TIMEOUT"])) {
  1081. $options["timeout"] = explode(",", $_SERVER["HTTP_TIMEOUT"]);
  1082. }
  1083. if(empty($_SERVER['CONTENT_LENGTH']) && !empty($_SERVER['HTTP_IF'])) {
  1084. // check if locking is possible
  1085. if(!$this->_check_lock_status($this->path)) {
  1086. $this->http_status("423 Locked");
  1087. return;
  1088. }
  1089. // refresh lock
  1090. $options["update"] = substr($_SERVER['HTTP_IF'], 2, -2);
  1091. $stat = $this->LOCK($options);
  1092. } else {
  1093. // extract lock request information from request XML payload
  1094. $lockinfo = new _parse_lockinfo("php://input");
  1095. if (!$lockinfo->success) {
  1096. $this->http_status("400 bad request");
  1097. }
  1098. // check if locking is possible
  1099. if(!$this->_check_lock_status($this->path, $lockinfo->lockscope === "shared")) {
  1100. $this->http_status("423 Locked");
  1101. return;
  1102. }
  1103. // new lock
  1104. $options["scope"] = $lockinfo->lockscope;
  1105. $options["type"] = $lockinfo->locktype;
  1106. $options["owner"] = $lockinfo->owner;
  1107. $options["locktoken"] = $this->_new_locktoken();
  1108. $stat = $this->LOCK($options);
  1109. }
  1110. if(is_bool($stat)) {
  1111. $http_stat = $stat ? "200 OK" : "423 Locked";
  1112. } else {
  1113. $http_stat = $stat;
  1114. }
  1115. $this->http_status($http_stat);
  1116. if ($http_stat{0} == 2) { // 2xx states are ok
  1117. if($options["timeout"]) {
  1118. // more than a million is considered an absolute timestamp
  1119. // less is more likely a relative value
  1120. if($options["timeout"]>1000000) {
  1121. $timeout = "Second-".($options['timeout']-time());
  1122. } else {
  1123. $timeout = "Second-$options[timeout]";
  1124. }
  1125. } else {
  1126. $timeout = "Infinite";
  1127. }
  1128. header('Content-Type: text/xml; charset="utf-8"');
  1129. header("Lock-Token: <$options[locktoken]>");
  1130. echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  1131. echo "<D:prop xmlns:D=\"DAV:\">\n";
  1132. echo " <D:lockdiscovery>\n";
  1133. echo " <D:activelock>\n";
  1134. echo " <D:lockscope><D:$options[scope]/></D:lockscope>\n";
  1135. echo " <D:locktype><D:$options[type]/></D:locktype>\n";
  1136. echo " <D:depth>$options[depth]</D:depth>\n";
  1137. echo " <D:owner>$options[owner]</D:owner>\n";
  1138. echo " <D:timeout>$timeout</D:timeout>\n";
  1139. echo " <D:locktoken><D:href>$options[locktoken]</D:href></D:locktoken>\n";
  1140. echo " </D:activelock>\n";
  1141. echo " </D:lockdiscovery>\n";
  1142. echo "</D:prop>\n\n";
  1143. }
  1144. }
  1145. // }}}
  1146. // {{{ http_UNLOCK()
  1147. /**
  1148. * UNLOCK method handler
  1149. *
  1150. * @param void
  1151. * @return void
  1152. */
  1153. function http_UNLOCK()
  1154. {
  1155. $options = Array();
  1156. $options["path"] = $this->path;
  1157. if (isset($_SERVER['HTTP_DEPTH'])) {
  1158. $options["depth"] = $_SERVER["HTTP_DEPTH"];
  1159. } else {
  1160. $options["depth"] = "infinity";
  1161. }
  1162. // strip surrounding <>
  1163. $options["token"] = substr(trim($_SERVER["HTTP_LOCK_TOKEN"]), 1, -1);
  1164. // call user method
  1165. $stat = $this->UNLOCK($options);
  1166. $this->http_status($stat);
  1167. }
  1168. // }}}
  1169. // }}}
  1170. // {{{ _copymove()
  1171. function _copymove($what)
  1172. {
  1173. $options = Array();
  1174. $options["path"] = $this->path;
  1175. if (isset($_SERVER["HTTP_DEPTH"])) {
  1176. $options["depth"] = $_SERVER["HTTP_DEPTH"];
  1177. } else {
  1178. $options["depth"] = "infinity";
  1179. }
  1180. extract(parse_url($_SERVER["HTTP_DESTINATION"]));
  1181. $path = urldecode($path);
  1182. $http_host = $host;
  1183. if (isset($port) && $port != 80)
  1184. $http_host.= ":$port";
  1185. $http_header_host = preg_replace("/:80$/", "", $_SERVER["HTTP_HOST"]);
  1186. if ($http_host == $http_header_host &&
  1187. !strncmp($_SERVER["SCRIPT_NAME"], $path,
  1188. strlen($_SERVER["SCRIPT_NAME"]))) {
  1189. $options["dest"] = substr($path, strlen($_SERVER["SCRIPT_NAME"]));
  1190. if (!$this->_check_lock_status($options["dest"])) {
  1191. $this->http_status("423 Locked");
  1192. return;
  1193. }
  1194. } else {
  1195. $options["dest_url"] = $_SERVER["HTTP_DESTINATION"];
  1196. }
  1197. // see RFC 2518 Sections 9.6, 8.8.4 and 8.9.3
  1198. if (isset($_SERVER["HTTP_OVERWRITE"])) {
  1199. $options["overwrite"] = $_SERVER["HTTP_OVERWRITE"] == "T";
  1200. } else {
  1201. $options["overwrite"] = true;
  1202. }
  1203. $stat = $this->$what($options);
  1204. $this->http_status($stat);
  1205. }
  1206. // }}}
  1207. // {{{ _allow()
  1208. /**
  1209. * check for implemented HTTP methods
  1210. *
  1211. * @param void
  1212. * @return array something
  1213. */
  1214. function _allow()
  1215. {
  1216. // OPTIONS is always there
  1217. $allow = array("OPTIONS" =>"OPTIONS");
  1218. // all other METHODS need both a http_method() wrapper
  1219. // and a method() implementation
  1220. // the base class supplies wrappers only
  1221. foreach(get_class_methods($this) as $method) {
  1222. if (!strncmp("http_", $method, 5)) {
  1223. $method = strtoupper(substr($method, 5));
  1224. if (method_exists($this, $method)) {
  1225. $allow[$method] = $method;
  1226. }
  1227. }
  1228. }
  1229. // we can emulate a missing HEAD implemetation using GET
  1230. if (isset($allow["GET"]))
  1231. $allow["HEAD"] = "HEAD";
  1232. // no LOCK without checklok()
  1233. if (!method_exists($this, "checklock")) {
  1234. unset($allow["LOCK"]);
  1235. unset($allow["UNLOCK"]);
  1236. }
  1237. return $allow;
  1238. }
  1239. // }}}
  1240. /**
  1241. * helper for property element creation
  1242. *
  1243. * @param string XML namespace (optional)
  1244. * @param string property name
  1245. * @param string property value
  1246. * @return array property array
  1247. */
  1248. function mkprop()
  1249. {
  1250. $args = func_get_args();
  1251. if (count($args) == 3) {
  1252. return array("ns" => $args[0],
  1253. "name" => $args[1],
  1254. "val" => $args[2]);
  1255. } else {
  1256. return array("ns" => "DAV:",
  1257. "name" => $args[0],
  1258. "val" => $args[1]);
  1259. }
  1260. }
  1261. // {{{ _check_auth
  1262. /**
  1263. * check authentication if check is implemented
  1264. *
  1265. * @param void
  1266. * @return bool true if authentication succeded or not necessary
  1267. */
  1268. function _check_auth()
  1269. {
  1270. if (method_exists($this, "checkAuth")) {
  1271. // PEAR style method name
  1272. return $this->checkAuth(@$_SERVER["AUTH_TYPE"],
  1273. @$_SERVER["PHP_AUTH_USER"],
  1274. @$_SERVER["PHP_AUTH_PW"]);
  1275. } else if (method_exists($this, "check_auth")) {
  1276. // old (pre 1.0) method name
  1277. return $this->check_auth(@$_SERVER["AUTH_TYPE"],
  1278. @$_SERVER["PHP_AUTH_USER"],
  1279. @$_SERVER["PHP_AUTH_PW"]);
  1280. } else {
  1281. // no method found -> no authentication required
  1282. return true;
  1283. }
  1284. }
  1285. // }}}
  1286. // {{{ UUID stuff
  1287. /**
  1288. * generate Unique Universal IDentifier for lock token
  1289. *
  1290. * @param void
  1291. * @return string a new UUID
  1292. */
  1293. function _new_uuid()
  1294. {
  1295. // use uuid extension from PECL if available
  1296. if (function_exists("uuid_create")) {
  1297. return uuid_create();
  1298. }
  1299. // fallback
  1300. $uuid = md5(microtime().getmypid()); // this should be random enough for now
  1301. // set variant and version fields for 'true' random uuid
  1302. $uuid{12} = "4";
  1303. $n = 8 + (ord($uuid{16}) & 3);
  1304. $hex = "0123456789abcdef";
  1305. $uuid{16} = $hex{$n};
  1306. // return formated uuid
  1307. return substr($uuid, 0, 8)."-"
  1308. . substr($uuid, 8, 4)."-"
  1309. . substr($uuid, 12, 4)."-"
  1310. . substr($uuid, 16, 4)."-"
  1311. . substr($uuid, 20);
  1312. }
  1313. /**
  1314. * create a new opaque lock token as defined in RFC2518
  1315. *
  1316. * @param void
  1317. * @return string new RFC2518 opaque lock token
  1318. */
  1319. function _new_locktoken()
  1320. {
  1321. return "opaquelocktoken:".$this->_new_uuid();
  1322. }
  1323. // }}}
  1324. // {{{ WebDAV If: header parsing
  1325. /**
  1326. *
  1327. *
  1328. * @param string header string to parse
  1329. * @param int current parsing position
  1330. * @return array next token (type and value)
  1331. */
  1332. function _if_header_lexer($string, &$pos)
  1333. {
  1334. // skip whitespace
  1335. while (ctype_space($string{$pos})) {
  1336. ++$pos;
  1337. }
  1338. // already at end of string?
  1339. if (strlen($string) <= $pos) {
  1340. return false;
  1341. }
  1342. // get next character
  1343. $c = $string{$pos++};
  1344. // now it depends on what we found
  1345. switch ($c) {
  1346. case "<":
  1347. // URIs are enclosed in <...>
  1348. $pos2 = strpos($string, ">", $pos);
  1349. $uri = substr($string, $pos, $pos2 - $pos);
  1350. $pos = $pos2 + 1;
  1351. return array("URI", $uri);
  1352. case "[":
  1353. //Etags are enclosed in [...]
  1354. if ($string{$pos} == "W") {
  1355. $type = "ETAG_WEAK";
  1356. $pos += 2;
  1357. } else {
  1358. $type = "ETAG_STRONG";
  1359. }
  1360. $pos2 = strpos($string, "]", $pos);
  1361. $etag = substr($string, $pos + 1, $pos2 - $pos - 2);
  1362. $pos = $pos2 + 1;
  1363. return array($type, $etag);
  1364. case "N":
  1365. // "N" indicates negation
  1366. $pos += 2;
  1367. return array("NOT", "Not");
  1368. default:
  1369. // anything else is passed verbatim char by char
  1370. return array("CHAR", $c);
  1371. }
  1372. }
  1373. /**
  1374. * parse If: header
  1375. *
  1376. * @param string header string
  1377. * @return array URIs and their conditions
  1378. */
  1379. function _if_header_parser($str)
  1380. {
  1381. $pos = 0;
  1382. $len = strlen($str);
  1383. $uris = array();
  1384. // parser loop
  1385. while ($pos < $len) {
  1386. // get next token
  1387. $token = $this->_if_header_lexer($str, $pos);
  1388. // check for URI
  1389. if ($token[0] == "URI") {
  1390. $uri = $token[1]; // remember URI
  1391. $token = $this->_if_header_lexer($str, $pos); // get next token
  1392. } else {
  1393. $uri = "";
  1394. }
  1395. // sanity check
  1396. if ($token[0] != "CHAR" || $token[1] != "(") {
  1397. return false;
  1398. }
  1399. $list = array();
  1400. $level = 1;
  1401. $not = "";
  1402. while ($level) {
  1403. $token = $this->_if_header_lexer($str, $pos);
  1404. if ($token[0] == "NOT") {
  1405. $not = "!";
  1406. continue;
  1407. }
  1408. switch ($token[0]) {
  1409. case "CHAR":
  1410. switch ($token[1]) {
  1411. case "(":
  1412. $level++;
  1413. break;
  1414. case ")":
  1415. $level--;
  1416. break;
  1417. default:
  1418. return false;
  1419. }
  1420. break;
  1421. case "URI":
  1422. $list[] = $not."<$token[1]>";
  1423. break;
  1424. case "ETAG_WEAK":
  1425. $list[] = $not."[W/'$token[1]']>";
  1426. break;
  1427. case "ETAG_STRONG":
  1428. $list[] = $not."['$token[1]']>";
  1429. break;
  1430. default:
  1431. return false;
  1432. }
  1433. $not = "";
  1434. }
  1435. if (@is_array($uris[$uri])) {
  1436. $uris[$uri] = array_merge($uris[$uri],$list);
  1437. } else {
  1438. $uris[$uri] = $list;
  1439. }
  1440. }
  1441. return $uris;
  1442. }
  1443. /**
  1444. * check if conditions from "If:" headers are meat
  1445. *
  1446. * the "If:" header is an extension to HTTP/1.1
  1447. * defined in RFC 2518 section 9.4
  1448. *
  1449. * @param void
  1450. * @return void
  1451. */
  1452. function _check_if_header_conditions()
  1453. {
  1454. if (isset($_SERVER["HTTP_IF"])) {
  1455. $this->_if_header_uris =
  1456. $this->_if_header_parser($_SERVER["HTTP_IF"]);
  1457. foreach($this->_if_header_uris as $uri => $conditions) {
  1458. if ($uri == "") {
  1459. $uri = $this->uri;
  1460. }
  1461. // all must match
  1462. $state = true;
  1463. foreach($conditions as $condition) {
  1464. // lock tokens may be free form (RFC2518 6.3)
  1465. // but if opaquelocktokens are used (RFC2518 6.4)
  1466. // we have to check the format (litmus tests this)
  1467. if (!strncmp($condition, "<opaquelocktoken:", strlen("<opaquelocktoken"))) {
  1468. if (!preg_match('/^<opaquelocktoken:[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}>$/', $condition)) {
  1469. $this->http_status("423 Locked");
  1470. return false;
  1471. }
  1472. }
  1473. if (!$this->_check_uri_condition($uri, $condition)) {
  1474. $this->http_status("412 Precondition failed");
  1475. $state = false;
  1476. break;
  1477. }
  1478. }
  1479. // any match is ok
  1480. if ($state == true) {
  1481. return true;
  1482. }
  1483. }
  1484. return false;
  1485. }
  1486. return true;
  1487. }
  1488. /**
  1489. * Check a single URI condition parsed from an if-header
  1490. *
  1491. * Check a single URI condition parsed from an if-header
  1492. *
  1493. * @abstract
  1494. * @param string $uri URI to check
  1495. * @param string $condition Condition to check for this URI
  1496. * @returns bool Condition check result
  1497. */
  1498. function _check_uri_condition($uri, $condition)
  1499. {
  1500. // not really implemented here,
  1501. // implementations must override
  1502. return true;
  1503. }
  1504. /**
  1505. *
  1506. *
  1507. * @param string path of resource to check
  1508. * @param bool exclusive lock?
  1509. */
  1510. function _check_lock_status($path, $exclusive_only = false)
  1511. {
  1512. // FIXME depth -> ignored for now
  1513. if (method_exists($this, "checkLock")) {
  1514. // is locked?
  1515. $lock = $this->checkLock($path);
  1516. // ... and lock is not owned?
  1517. if (is_array($lock) && count($lock)) {
  1518. // FIXME doesn't check uri restrictions yet
  1519. if (!isset($_SERVER["HTTP_IF"]) || !strstr($_SERVER["HTTP_IF"], $lock["token"])) {
  1520. if (!$exclusive_only || ($lock["scope"] !== "shared"))
  1521. return false;
  1522. }
  1523. }
  1524. }
  1525. return true;
  1526. }
  1527. // }}}
  1528. /**
  1529. * Generate lockdiscovery reply from checklock() result
  1530. *
  1531. * @param string resource path to check
  1532. * @return string lockdiscovery response
  1533. */
  1534. function lockdiscovery($path)
  1535. {
  1536. // no lock support without checklock() method
  1537. if (!method_exists($this, "checklock")) {
  1538. return "";
  1539. }
  1540. // collect response here
  1541. $activelocks = "";
  1542. // get checklock() reply
  1543. $lock = $this->checklock($path);
  1544. // generate <activelock> block for returned data
  1545. if (is_array($lock) && count($lock)) {
  1546. // check for 'timeout' or 'expires'
  1547. if (!empty($lock["expires"])) {
  1548. $timeout = "Second-".($lock["expires"] - time());
  1549. } else if (!empty($lock["timeout"])) {
  1550. $timeout = "Second-$lock[timeout]";
  1551. } else {
  1552. $timeout = "Infinite";
  1553. }
  1554. // genreate response block
  1555. $activelocks.= "
  1556. <D:activelock>
  1557. <D:lockscope><D:$lock[scope]/></D:lockscope>
  1558. <D:locktype><D:$lock[type]/></D:locktype>
  1559. <D:depth>$lock[depth]</D:depth>
  1560. <D:owner>$lock[owner]</D:owner>
  1561. <D:timeout>$timeout</D:timeout>
  1562. <D:locktoken><D:href>$lock[token]</D:href></D:locktoken>
  1563. </D:activelock>
  1564. ";
  1565. }
  1566. // return generated response
  1567. return $activelocks;
  1568. }
  1569. /**
  1570. * set HTTP return status and mirror it in a private header
  1571. *
  1572. * @param string status code and message
  1573. * @return void
  1574. */
  1575. function http_status($status)
  1576. {
  1577. // simplified success case
  1578. if($status === true) {
  1579. $status = "200 OK";
  1580. }
  1581. // remember status
  1582. $this->_http_status = $status;
  1583. // generate HTTP status response
  1584. header("HTTP/1.1 $status");
  1585. header("X-WebDAV-Status: $status", true);
  1586. }
  1587. /**
  1588. * private minimalistic version of PHP urlencode()
  1589. *
  1590. * only blanks and XML special chars must be encoded here
  1591. * full urlencode() encoding confuses some clients ...
  1592. *
  1593. * @param string URL to encode
  1594. * @return string encoded URL
  1595. */
  1596. function _urlencode($url)
  1597. {
  1598. return strtr($url, array(" "=>"%20",
  1599. "&"=>"%26",
  1600. "<"=>"%3C",
  1601. ">"=>"%3E",
  1602. ));
  1603. }
  1604. /**
  1605. * private version of PHP urldecode
  1606. *
  1607. * not really needed but added for completenes
  1608. *
  1609. * @param string URL to decode
  1610. * @return string decoded URL
  1611. */
  1612. function _urldecode($path)
  1613. {
  1614. return urldecode($path);
  1615. }
  1616. /**
  1617. * UTF-8 encode property values if not already done so
  1618. *
  1619. * @param string text to encode
  1620. * @return string utf-8 encoded text
  1621. */
  1622. function _prop_encode($text)
  1623. {
  1624. switch (strtolower($this->_prop_encoding)) {
  1625. case "utf-8":
  1626. return $text;
  1627. case "iso-8859-1":
  1628. case "iso-8859-15":
  1629. case "latin-1":
  1630. default:
  1631. return utf8_encode($text);
  1632. }
  1633. }
  1634. /**
  1635. * Slashify - make sure path ends in a slash
  1636. *
  1637. * @param string directory path
  1638. * @returns string directory path wiht trailing slash
  1639. */
  1640. function _slashify($path) {
  1641. if ($path[strlen($path)-1] != '/') {
  1642. $path = $path."/";
  1643. }
  1644. return $path;
  1645. }
  1646. /**
  1647. * Unslashify - make sure path doesn't in a slash
  1648. *
  1649. * @param string directory path
  1650. * @returns string directory path wihtout trailing slash
  1651. */
  1652. function _unslashify($path) {
  1653. if ($path[strlen($path)-1] == '/') {
  1654. $path = substr($path, 0, strlen($path, 0, -1));
  1655. }
  1656. return $path;
  1657. }
  1658. /**
  1659. * Merge two pathes, make sure there is exactly one slash between them
  1660. *
  1661. * @param string parent path
  1662. * @param string child path
  1663. * @return string merged path
  1664. */
  1665. function _mergePathes($parent, $child)
  1666. {
  1667. if ($child{0} == '/') {
  1668. return $this->_unslashify($parent).$child;
  1669. } else {
  1670. return $this->_slashify($parent).$child;
  1671. }
  1672. }
  1673. }
  1674. /*
  1675. * Local variables:
  1676. * tab-width: 4
  1677. * c-basic-offset: 4
  1678. * End:
  1679. */
  1680. ?>