PageRenderTime 59ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Sabre/DAV/Server.php

https://github.com/KOLANICH/SabreDAV
PHP | 2457 lines | 1050 code | 536 blank | 871 comment | 216 complexity | 4099fb9655e490df667c55d86cd0cbd3 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. namespace Sabre\DAV;
  3. use Sabre\HTTP;
  4. /**
  5. * Main DAV server class
  6. *
  7. * @copyright Copyright (C) 2007-2013 fruux GmbH (https://fruux.com/).
  8. * @author Evert Pot (http://evertpot.com/)
  9. * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
  10. */
  11. class Server {
  12. /**
  13. * Infinity is used for some request supporting the HTTP Depth header and indicates that the operation should traverse the entire tree
  14. */
  15. const DEPTH_INFINITY = -1;
  16. /**
  17. * Nodes that are files, should have this as the type property
  18. */
  19. const NODE_FILE = 1;
  20. /**
  21. * Nodes that are directories, should use this value as the type property
  22. */
  23. const NODE_DIRECTORY = 2;
  24. /**
  25. * XML namespace for all SabreDAV related elements
  26. */
  27. const NS_SABREDAV = 'http://sabredav.org/ns';
  28. /**
  29. * The tree object
  30. *
  31. * @var Sabre\DAV\Tree
  32. */
  33. public $tree;
  34. /**
  35. * The base uri
  36. *
  37. * @var string
  38. */
  39. protected $baseUri = null;
  40. /**
  41. * httpResponse
  42. *
  43. * @var Sabre\HTTP\Response
  44. */
  45. public $httpResponse;
  46. /**
  47. * httpRequest
  48. *
  49. * @var Sabre\HTTP\Request
  50. */
  51. public $httpRequest;
  52. /**
  53. * The list of plugins
  54. *
  55. * @var array
  56. */
  57. protected $plugins = [];
  58. /**
  59. * This array contains a list of callbacks we should call when certain events are triggered
  60. *
  61. * @var array
  62. */
  63. protected $eventSubscriptions = [];
  64. /**
  65. * This property will be filled with a unique string that describes the
  66. * transaction. This is useful for performance measuring and logging
  67. * purposes.
  68. *
  69. * By default it will just fill it with a lowercased HTTP method name, but
  70. * plugins override this. For example, the WebDAV-Sync sync-collection
  71. * report will set this to 'report-sync-collection'.
  72. *
  73. * @var string
  74. */
  75. public $transactionType;
  76. /**
  77. * This is a default list of namespaces.
  78. *
  79. * If you are defining your own custom namespace, add it here to reduce
  80. * bandwidth and improve legibility of xml bodies.
  81. *
  82. * @var array
  83. */
  84. public $xmlNamespaces = [
  85. 'DAV:' => 'd',
  86. 'http://sabredav.org/ns' => 's',
  87. ];
  88. /**
  89. * The propertymap can be used to map properties from
  90. * requests to property classes.
  91. *
  92. * @var array
  93. */
  94. public $propertyMap = [
  95. '{DAV:}resourcetype' => 'Sabre\\DAV\\Property\\ResourceType',
  96. ];
  97. public $protectedProperties = [
  98. // RFC4918
  99. '{DAV:}getcontentlength',
  100. '{DAV:}getetag',
  101. '{DAV:}getlastmodified',
  102. '{DAV:}lockdiscovery',
  103. '{DAV:}supportedlock',
  104. // RFC4331
  105. '{DAV:}quota-available-bytes',
  106. '{DAV:}quota-used-bytes',
  107. // RFC3744
  108. '{DAV:}supported-privilege-set',
  109. '{DAV:}current-user-privilege-set',
  110. '{DAV:}acl',
  111. '{DAV:}acl-restrictions',
  112. '{DAV:}inherited-acl-set',
  113. ];
  114. /**
  115. * This is a flag that allow or not showing file, line and code
  116. * of the exception in the returned XML
  117. *
  118. * @var bool
  119. */
  120. public $debugExceptions = false;
  121. /**
  122. * This property allows you to automatically add the 'resourcetype' value
  123. * based on a node's classname or interface.
  124. *
  125. * The preset ensures that {DAV:}collection is automaticlly added for nodes
  126. * implementing Sabre\DAV\ICollection.
  127. *
  128. * @var array
  129. */
  130. public $resourceTypeMapping = [
  131. 'Sabre\\DAV\\ICollection' => '{DAV:}collection',
  132. ];
  133. /**
  134. * If this setting is turned off, SabreDAV's version number will be hidden
  135. * from various places.
  136. *
  137. * Some people feel this is a good security measure.
  138. *
  139. * @var bool
  140. */
  141. static public $exposeVersion = true;
  142. /**
  143. * Sets up the server
  144. *
  145. * If a Sabre\DAV\Tree object is passed as an argument, it will
  146. * use it as the directory tree. If a Sabre\DAV\INode is passed, it
  147. * will create a Sabre\DAV\ObjectTree and use the node as the root.
  148. *
  149. * If nothing is passed, a Sabre\DAV\SimpleCollection is created in
  150. * a Sabre\DAV\ObjectTree.
  151. *
  152. * If an array is passed, we automatically create a root node, and use
  153. * the nodes in the array as top-level children.
  154. *
  155. * @param Tree|INode|array|null $treeOrNode The tree object
  156. */
  157. public function __construct($treeOrNode = null) {
  158. if ($treeOrNode instanceof Tree) {
  159. $this->tree = $treeOrNode;
  160. } elseif ($treeOrNode instanceof INode) {
  161. $this->tree = new ObjectTree($treeOrNode);
  162. } elseif (is_array($treeOrNode)) {
  163. // If it's an array, a list of nodes was passed, and we need to
  164. // create the root node.
  165. foreach($treeOrNode as $node) {
  166. if (!($node instanceof INode)) {
  167. throw new Exception('Invalid argument passed to constructor. If you\'re passing an array, all the values must implement Sabre\\DAV\\INode');
  168. }
  169. }
  170. $root = new SimpleCollection('root', $treeOrNode);
  171. $this->tree = new ObjectTree($root);
  172. } elseif (is_null($treeOrNode)) {
  173. $root = new SimpleCollection('root');
  174. $this->tree = new ObjectTree($root);
  175. } else {
  176. throw new Exception('Invalid argument passed to constructor. Argument must either be an instance of Sabre\\DAV\\Tree, Sabre\\DAV\\INode, an array or null');
  177. }
  178. $this->httpResponse = new HTTP\Response();
  179. $this->httpRequest = new HTTP\Request();
  180. }
  181. /**
  182. * Starts the DAV Server
  183. *
  184. * @return void
  185. */
  186. public function exec() {
  187. try {
  188. // If nginx (pre-1.2) is used as a proxy server, and SabreDAV as an
  189. // origin, we must make sure we send back HTTP/1.0 if this was
  190. // requested.
  191. // This is mainly because nginx doesn't support Chunked Transfer
  192. // Encoding, and this forces the webserver SabreDAV is running on,
  193. // to buffer entire responses to calculate Content-Length.
  194. $this->httpResponse->defaultHttpVersion = $this->httpRequest->getHTTPVersion();
  195. $this->invokeMethod($this->httpRequest->getMethod(), $this->getRequestUri());
  196. } catch (Exception $e) {
  197. try {
  198. $this->broadcastEvent('exception', [$e]);
  199. } catch (Exception $ignore) {
  200. }
  201. $DOM = new \DOMDocument('1.0','utf-8');
  202. $DOM->formatOutput = true;
  203. $error = $DOM->createElementNS('DAV:','d:error');
  204. $error->setAttribute('xmlns:s',self::NS_SABREDAV);
  205. $DOM->appendChild($error);
  206. $h = function($v) {
  207. return htmlspecialchars($v, ENT_NOQUOTES, 'UTF-8');
  208. };
  209. if (self::$exposeVersion) {
  210. $error->appendChild($DOM->createElement('s:sabredav-version',$h(Version::VERSION)));
  211. }
  212. $error->appendChild($DOM->createElement('s:exception',$h(get_class($e))));
  213. $error->appendChild($DOM->createElement('s:message',$h($e->getMessage())));
  214. if ($this->debugExceptions) {
  215. $error->appendChild($DOM->createElement('s:file',$h($e->getFile())));
  216. $error->appendChild($DOM->createElement('s:line',$h($e->getLine())));
  217. $error->appendChild($DOM->createElement('s:code',$h($e->getCode())));
  218. $error->appendChild($DOM->createElement('s:stacktrace',$h($e->getTraceAsString())));
  219. }
  220. if ($this->debugExceptions) {
  221. $previous = $e;
  222. while ($previous = $previous->getPrevious()) {
  223. $xPrevious = $DOM->createElement('s:previous-exception');
  224. $xPrevious->appendChild($DOM->createElement('s:exception',$h(get_class($previous))));
  225. $xPrevious->appendChild($DOM->createElement('s:message',$h($previous->getMessage())));
  226. $xPrevious->appendChild($DOM->createElement('s:file',$h($previous->getFile())));
  227. $xPrevious->appendChild($DOM->createElement('s:line',$h($previous->getLine())));
  228. $xPrevious->appendChild($DOM->createElement('s:code',$h($previous->getCode())));
  229. $xPrevious->appendChild($DOM->createElement('s:stacktrace',$h($previous->getTraceAsString())));
  230. $error->appendChild($xPrevious);
  231. }
  232. }
  233. if($e instanceof Exception) {
  234. $httpCode = $e->getHTTPCode();
  235. $e->serialize($this,$error);
  236. $headers = $e->getHTTPHeaders($this);
  237. } else {
  238. $httpCode = 500;
  239. $headers = [];
  240. }
  241. $headers['Content-Type'] = 'application/xml; charset=utf-8';
  242. $this->httpResponse->sendStatus($httpCode);
  243. $this->httpResponse->setHeaders($headers);
  244. $this->httpResponse->sendBody($DOM->saveXML());
  245. }
  246. }
  247. /**
  248. * Sets the base server uri
  249. *
  250. * @param string $uri
  251. * @return void
  252. */
  253. public function setBaseUri($uri) {
  254. // If the baseUri does not end with a slash, we must add it
  255. if ($uri[strlen($uri)-1]!=='/')
  256. $uri.='/';
  257. $this->baseUri = $uri;
  258. }
  259. /**
  260. * Returns the base responding uri
  261. *
  262. * @return string
  263. */
  264. public function getBaseUri() {
  265. if (is_null($this->baseUri)) $this->baseUri = $this->guessBaseUri();
  266. return $this->baseUri;
  267. }
  268. /**
  269. * This method attempts to detect the base uri.
  270. * Only the PATH_INFO variable is considered.
  271. *
  272. * If this variable is not set, the root (/) is assumed.
  273. *
  274. * @return string
  275. */
  276. public function guessBaseUri() {
  277. $pathInfo = $this->httpRequest->getRawServerValue('PATH_INFO');
  278. $uri = $this->httpRequest->getRawServerValue('REQUEST_URI');
  279. // If PATH_INFO is found, we can assume it's accurate.
  280. if (!empty($pathInfo)) {
  281. // We need to make sure we ignore the QUERY_STRING part
  282. if ($pos = strpos($uri,'?'))
  283. $uri = substr($uri,0,$pos);
  284. // PATH_INFO is only set for urls, such as: /example.php/path
  285. // in that case PATH_INFO contains '/path'.
  286. // Note that REQUEST_URI is percent encoded, while PATH_INFO is
  287. // not, Therefore they are only comparable if we first decode
  288. // REQUEST_INFO as well.
  289. $decodedUri = URLUtil::decodePath($uri);
  290. // A simple sanity check:
  291. if(substr($decodedUri,strlen($decodedUri)-strlen($pathInfo))===$pathInfo) {
  292. $baseUri = substr($decodedUri,0,strlen($decodedUri)-strlen($pathInfo));
  293. return rtrim($baseUri,'/') . '/';
  294. }
  295. throw new Exception('The REQUEST_URI ('. $uri . ') did not end with the contents of PATH_INFO (' . $pathInfo . '). This server might be misconfigured.');
  296. }
  297. // The last fallback is that we're just going to assume the server root.
  298. return '/';
  299. }
  300. /**
  301. * Adds a plugin to the server
  302. *
  303. * For more information, console the documentation of Sabre\DAV\ServerPlugin
  304. *
  305. * @param ServerPlugin $plugin
  306. * @return void
  307. */
  308. public function addPlugin(ServerPlugin $plugin) {
  309. $this->plugins[$plugin->getPluginName()] = $plugin;
  310. $plugin->initialize($this);
  311. }
  312. /**
  313. * Returns an initialized plugin by it's name.
  314. *
  315. * This function returns null if the plugin was not found.
  316. *
  317. * @param string $name
  318. * @return ServerPlugin
  319. */
  320. public function getPlugin($name) {
  321. if (isset($this->plugins[$name]))
  322. return $this->plugins[$name];
  323. // This is a fallback and deprecated.
  324. foreach($this->plugins as $plugin) {
  325. if (get_class($plugin)===$name) return $plugin;
  326. }
  327. return null;
  328. }
  329. /**
  330. * Returns all plugins
  331. *
  332. * @return array
  333. */
  334. public function getPlugins() {
  335. return $this->plugins;
  336. }
  337. /**
  338. * Subscribe to an event.
  339. *
  340. * When the event is triggered, we'll call all the specified callbacks.
  341. * It is possible to control the order of the callbacks through the
  342. * priority argument.
  343. *
  344. * This is for example used to make sure that the authentication plugin
  345. * is triggered before anything else. If it's not needed to change this
  346. * number, it is recommended to ommit.
  347. *
  348. * @param string $event
  349. * @param callback $callback
  350. * @param int $priority
  351. * @return void
  352. */
  353. public function subscribeEvent($event, $callback, $priority = 100) {
  354. if (!isset($this->eventSubscriptions[$event])) {
  355. $this->eventSubscriptions[$event] = [];
  356. }
  357. while(isset($this->eventSubscriptions[$event][$priority])) $priority++;
  358. $this->eventSubscriptions[$event][$priority] = $callback;
  359. ksort($this->eventSubscriptions[$event]);
  360. }
  361. /**
  362. * Broadcasts an event
  363. *
  364. * This method will call all subscribers. If one of the subscribers returns false, the process stops.
  365. *
  366. * The arguments parameter will be sent to all subscribers
  367. *
  368. * @param string $eventName
  369. * @param array $arguments
  370. * @return bool
  371. */
  372. public function broadcastEvent($eventName,$arguments = []) {
  373. if (isset($this->eventSubscriptions[$eventName])) {
  374. foreach($this->eventSubscriptions[$eventName] as $subscriber) {
  375. $result = call_user_func_array($subscriber,$arguments);
  376. if ($result===false) return false;
  377. }
  378. }
  379. return true;
  380. }
  381. /**
  382. * Handles a http request, and execute a method based on its name
  383. *
  384. * @param string $method
  385. * @param string $uri
  386. * @return void
  387. */
  388. public function invokeMethod($method, $uri) {
  389. $method = strtoupper($method);
  390. if (!$this->broadcastEvent('beforeMethod',[$method, $uri])) return;
  391. // Make sure this is a HTTP method we support
  392. $internalMethods = [
  393. 'OPTIONS',
  394. 'GET',
  395. 'HEAD',
  396. 'DELETE',
  397. 'PROPFIND',
  398. 'MKCOL',
  399. 'PUT',
  400. 'PROPPATCH',
  401. 'COPY',
  402. 'MOVE',
  403. 'REPORT'
  404. ];
  405. $this->transactionType = strtolower($method);
  406. if (in_array($method,$internalMethods)) {
  407. call_user_func([$this, 'http' . $method], $uri);
  408. } else {
  409. if ($this->broadcastEvent('unknownMethod',[$method, $uri])) {
  410. // Unsupported method
  411. throw new Exception\NotImplemented('There was no handler found for this "' . $method . '" method');
  412. }
  413. }
  414. }
  415. // {{{ HTTP Method implementations
  416. /**
  417. * HTTP OPTIONS
  418. *
  419. * @param string $uri
  420. * @return void
  421. */
  422. protected function httpOptions($uri) {
  423. $methods = $this->getAllowedMethods($uri);
  424. $this->httpResponse->setHeader('Allow',strtoupper(implode(', ',$methods)));
  425. $features = ['1','3', 'extended-mkcol'];
  426. foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures());
  427. $this->httpResponse->setHeader('DAV',implode(', ',$features));
  428. $this->httpResponse->setHeader('MS-Author-Via','DAV');
  429. $this->httpResponse->setHeader('Accept-Ranges','bytes');
  430. if (self::$exposeVersion) {
  431. $this->httpResponse->setHeader('X-Sabre-Version',Version::VERSION);
  432. }
  433. $this->httpResponse->setHeader('Content-Length',0);
  434. $this->httpResponse->sendStatus(200);
  435. }
  436. /**
  437. * HTTP GET
  438. *
  439. * This method simply fetches the contents of a uri, like normal
  440. *
  441. * @param string $uri
  442. * @return bool
  443. */
  444. protected function httpGet($uri) {
  445. $node = $this->tree->getNodeForPath($uri,0);
  446. if (!$this->checkPreconditions(true)) return false;
  447. if (!$node instanceof IFile) throw new Exception\NotImplemented('GET is only implemented on File objects');
  448. $body = $node->get();
  449. // Converting string into stream, if needed.
  450. if (is_string($body)) {
  451. $stream = fopen('php://temp','r+');
  452. fwrite($stream,$body);
  453. rewind($stream);
  454. $body = $stream;
  455. }
  456. /*
  457. * TODO: getetag, getlastmodified, getsize should also be used using
  458. * this method
  459. */
  460. $httpHeaders = $this->getHTTPHeaders($uri);
  461. /* ContentType needs to get a default, because many webservers will otherwise
  462. * default to text/html, and we don't want this for security reasons.
  463. */
  464. if (!isset($httpHeaders['Content-Type'])) {
  465. $httpHeaders['Content-Type'] = 'application/octet-stream';
  466. }
  467. if (isset($httpHeaders['Content-Length'])) {
  468. $nodeSize = $httpHeaders['Content-Length'];
  469. // Need to unset Content-Length, because we'll handle that during figuring out the range
  470. unset($httpHeaders['Content-Length']);
  471. } else {
  472. $nodeSize = null;
  473. }
  474. $this->httpResponse->setHeaders($httpHeaders);
  475. $range = $this->getHTTPRange();
  476. $ifRange = $this->httpRequest->getHeader('If-Range');
  477. $ignoreRangeHeader = false;
  478. // If ifRange is set, and range is specified, we first need to check
  479. // the precondition.
  480. if ($nodeSize && $range && $ifRange) {
  481. // if IfRange is parsable as a date we'll treat it as a DateTime
  482. // otherwise, we must treat it as an etag.
  483. try {
  484. $ifRangeDate = new \DateTime($ifRange);
  485. // It's a date. We must check if the entity is modified since
  486. // the specified date.
  487. if (!isset($httpHeaders['Last-Modified'])) $ignoreRangeHeader = true;
  488. else {
  489. $modified = new \DateTime($httpHeaders['Last-Modified']);
  490. if($modified > $ifRangeDate) $ignoreRangeHeader = true;
  491. }
  492. } catch (\Exception $e) {
  493. // It's an entity. We can do a simple comparison.
  494. if (!isset($httpHeaders['ETag'])) $ignoreRangeHeader = true;
  495. elseif ($httpHeaders['ETag']!==$ifRange) $ignoreRangeHeader = true;
  496. }
  497. }
  498. // We're only going to support HTTP ranges if the backend provided a filesize
  499. if (!$ignoreRangeHeader && $nodeSize && $range) {
  500. // Determining the exact byte offsets
  501. if (!is_null($range[0])) {
  502. $start = $range[0];
  503. $end = $range[1]?$range[1]:$nodeSize-1;
  504. if($start >= $nodeSize)
  505. throw new Exception\RequestedRangeNotSatisfiable('The start offset (' . $range[0] . ') exceeded the size of the entity (' . $nodeSize . ')');
  506. if($end < $start) throw new Exception\RequestedRangeNotSatisfiable('The end offset (' . $range[1] . ') is lower than the start offset (' . $range[0] . ')');
  507. if($end >= $nodeSize) $end = $nodeSize-1;
  508. } else {
  509. $start = $nodeSize-$range[1];
  510. $end = $nodeSize-1;
  511. if ($start<0) $start = 0;
  512. }
  513. // New read/write stream
  514. $newStream = fopen('php://temp','r+');
  515. // stream_copy_to_stream() has a bug/feature: the `whence` argument
  516. // is interpreted as SEEK_SET (count from absolute offset 0), while
  517. // for a stream it should be SEEK_CUR (count from current offset).
  518. // If a stream is nonseekable, the function fails. So we *emulate*
  519. // the correct behaviour with fseek():
  520. if ($start > 0) {
  521. if (($curOffs = ftell($body)) === false) $curOffs = 0;
  522. fseek($body, $start - $curOffs, SEEK_CUR);
  523. }
  524. stream_copy_to_stream($body, $newStream, $end-$start+1);
  525. rewind($newStream);
  526. $this->httpResponse->setHeader('Content-Length', $end-$start+1);
  527. $this->httpResponse->setHeader('Content-Range','bytes ' . $start . '-' . $end . '/' . $nodeSize);
  528. $this->httpResponse->sendStatus(206);
  529. $this->httpResponse->sendBody($newStream);
  530. } else {
  531. if ($nodeSize) $this->httpResponse->setHeader('Content-Length',$nodeSize);
  532. $this->httpResponse->sendStatus(200);
  533. $this->httpResponse->sendBody($body);
  534. }
  535. }
  536. /**
  537. * HTTP HEAD
  538. *
  539. * This method is normally used to take a peak at a url, and only get the HTTP response headers, without the body
  540. * This is used by clients to determine if a remote file was changed, so they can use a local cached version, instead of downloading it again
  541. *
  542. * @param string $uri
  543. * @return void
  544. */
  545. protected function httpHead($uri) {
  546. $node = $this->tree->getNodeForPath($uri);
  547. /* This information is only collection for File objects.
  548. * Ideally we want to throw 405 Method Not Allowed for every
  549. * non-file, but MS Office does not like this
  550. */
  551. if ($node instanceof IFile) {
  552. $headers = $this->getHTTPHeaders($this->getRequestUri());
  553. if (!isset($headers['Content-Type'])) {
  554. $headers['Content-Type'] = 'application/octet-stream';
  555. }
  556. $this->httpResponse->setHeaders($headers);
  557. }
  558. $this->httpResponse->sendStatus(200);
  559. }
  560. /**
  561. * HTTP Delete
  562. *
  563. * The HTTP delete method, deletes a given uri
  564. *
  565. * @param string $uri
  566. * @return void
  567. */
  568. protected function httpDelete($uri) {
  569. $this->checkPreconditions();
  570. if (!$this->broadcastEvent('beforeUnbind',[$uri])) return;
  571. $this->tree->delete($uri);
  572. $this->broadcastEvent('afterUnbind',[$uri]);
  573. $this->httpResponse->sendStatus(204);
  574. $this->httpResponse->setHeader('Content-Length','0');
  575. }
  576. /**
  577. * WebDAV PROPFIND
  578. *
  579. * This WebDAV method requests information about an uri resource, or a list of resources
  580. * If a client wants to receive the properties for a single resource it will add an HTTP Depth: header with a 0 value
  581. * If the value is 1, it means that it also expects a list of sub-resources (e.g.: files in a directory)
  582. *
  583. * The request body contains an XML data structure that has a list of properties the client understands
  584. * The response body is also an xml document, containing information about every uri resource and the requested properties
  585. *
  586. * It has to return a HTTP 207 Multi-status status code
  587. *
  588. * @param string $uri
  589. * @return void
  590. */
  591. protected function httpPropfind($uri) {
  592. $requestedProperties = $this->parsePropFindRequest($this->httpRequest->getBody(true));
  593. $depth = $this->getHTTPDepth(1);
  594. // The only two options for the depth of a propfind is 0 or 1
  595. if ($depth!=0) $depth = 1;
  596. $newProperties = $this->getPropertiesForPath($uri,$requestedProperties,$depth);
  597. // This is a multi-status response
  598. $this->httpResponse->sendStatus(207);
  599. $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
  600. $this->httpResponse->setHeader('Vary','Brief,Prefer');
  601. // Normally this header is only needed for OPTIONS responses, however..
  602. // iCal seems to also depend on these being set for PROPFIND. Since
  603. // this is not harmful, we'll add it.
  604. $features = ['1', '3', 'extended-mkcol'];
  605. foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures());
  606. $this->httpResponse->setHeader('DAV',implode(', ',$features));
  607. $prefer = $this->getHTTPPrefer();
  608. $minimal = $prefer['return-minimal'];
  609. $data = $this->generateMultiStatus($newProperties, $minimal);
  610. $this->httpResponse->sendBody($data);
  611. }
  612. /**
  613. * WebDAV PROPPATCH
  614. *
  615. * This method is called to update properties on a Node. The request is an XML body with all the mutations.
  616. * In this XML body it is specified which properties should be set/updated and/or deleted
  617. *
  618. * @param string $uri
  619. * @return void
  620. */
  621. protected function httpPropPatch($uri) {
  622. $this->checkPreconditions();
  623. $newProperties = $this->parsePropPatchRequest($this->httpRequest->getBody(true));
  624. $result = $this->updateProperties($uri, $newProperties);
  625. $prefer = $this->getHTTPPrefer();
  626. $this->httpResponse->setHeader('Vary','Brief,Prefer');
  627. if ($prefer['return-minimal']) {
  628. // If return-minimal is specified, we only have to check if the
  629. // request was succesful, and don't need to return the
  630. // multi-status.
  631. $ok = true;
  632. foreach($result as $code=>$prop) {
  633. if ((int)$code > 299) {
  634. $ok = false;
  635. }
  636. }
  637. if ($ok) {
  638. $this->httpResponse->sendStatus(204);
  639. return;
  640. }
  641. }
  642. $this->httpResponse->sendStatus(207);
  643. $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
  644. $this->httpResponse->sendBody(
  645. $this->generateMultiStatus([$result])
  646. );
  647. }
  648. /**
  649. * HTTP PUT method
  650. *
  651. * This HTTP method updates a file, or creates a new one.
  652. *
  653. * If a new resource was created, a 201 Created status code should be returned. If an existing resource is updated, it's a 204 No Content
  654. *
  655. * @param string $uri
  656. * @return bool
  657. */
  658. protected function httpPut($uri) {
  659. $body = $this->httpRequest->getBody();
  660. // Intercepting Content-Range
  661. if ($this->httpRequest->getHeader('Content-Range')) {
  662. /**
  663. Content-Range is dangerous for PUT requests: PUT per definition
  664. stores a full resource. draft-ietf-httpbis-p2-semantics-15 says
  665. in section 7.6:
  666. An origin server SHOULD reject any PUT request that contains a
  667. Content-Range header field, since it might be misinterpreted as
  668. partial content (or might be partial content that is being mistakenly
  669. PUT as a full representation). Partial content updates are possible
  670. by targeting a separately identified resource with state that
  671. overlaps a portion of the larger resource, or by using a different
  672. method that has been specifically defined for partial updates (for
  673. example, the PATCH method defined in [RFC5789]).
  674. This clarifies RFC2616 section 9.6:
  675. The recipient of the entity MUST NOT ignore any Content-*
  676. (e.g. Content-Range) headers that it does not understand or implement
  677. and MUST return a 501 (Not Implemented) response in such cases.
  678. OTOH is a PUT request with a Content-Range currently the only way to
  679. continue an aborted upload request and is supported by curl, mod_dav,
  680. Tomcat and others. Since some clients do use this feature which results
  681. in unexpected behaviour (cf PEAR::HTTP_WebDAV_Client 1.0.1), we reject
  682. all PUT requests with a Content-Range for now.
  683. */
  684. throw new Exception\NotImplemented('PUT with Content-Range is not allowed.');
  685. }
  686. // Intercepting the Finder problem
  687. if (($expected = $this->httpRequest->getHeader('X-Expected-Entity-Length')) && $expected > 0) {
  688. /**
  689. Many webservers will not cooperate well with Finder PUT requests,
  690. because it uses 'Chunked' transfer encoding for the request body.
  691. The symptom of this problem is that Finder sends files to the
  692. server, but they arrive as 0-length files in PHP.
  693. If we don't do anything, the user might think they are uploading
  694. files successfully, but they end up empty on the server. Instead,
  695. we throw back an error if we detect this.
  696. The reason Finder uses Chunked, is because it thinks the files
  697. might change as it's being uploaded, and therefore the
  698. Content-Length can vary.
  699. Instead it sends the X-Expected-Entity-Length header with the size
  700. of the file at the very start of the request. If this header is set,
  701. but we don't get a request body we will fail the request to
  702. protect the end-user.
  703. */
  704. // Only reading first byte
  705. $firstByte = fread($body,1);
  706. if (strlen($firstByte)!==1) {
  707. throw new Exception\Forbidden('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.');
  708. }
  709. // The body needs to stay intact, so we copy everything to a
  710. // temporary stream.
  711. $newBody = fopen('php://temp','r+');
  712. fwrite($newBody,$firstByte);
  713. stream_copy_to_stream($body, $newBody);
  714. rewind($newBody);
  715. $body = $newBody;
  716. }
  717. if ($this->tree->nodeExists($uri)) {
  718. $node = $this->tree->getNodeForPath($uri);
  719. // Checking If-None-Match and related headers.
  720. if (!$this->checkPreconditions()) return;
  721. // If the node is a collection, we'll deny it
  722. if (!($node instanceof IFile)) throw new Exception\Conflict('PUT is not allowed on non-files.');
  723. // It is possible for an event handler to modify the content of the
  724. // body, before it gets written. If this is the case, $modified
  725. // should be set to true.
  726. //
  727. // If $modified is true, we must not send back an etag.
  728. $modified = false;
  729. if (!$this->broadcastEvent('beforeWriteContent',[$uri, $node, &$body, &$modified])) return false;
  730. $etag = $node->put($body);
  731. $this->broadcastEvent('afterWriteContent',[$uri, $node]);
  732. $this->httpResponse->setHeader('Content-Length','0');
  733. if ($etag && !$modified) $this->httpResponse->setHeader('ETag',$etag);
  734. $this->httpResponse->sendStatus(204);
  735. } else {
  736. $etag = null;
  737. // If we got here, the resource didn't exist yet.
  738. if (!$this->createFile($this->getRequestUri(),$body,$etag)) {
  739. // For one reason or another the file was not created.
  740. return;
  741. }
  742. $this->httpResponse->setHeader('Content-Length','0');
  743. if ($etag) $this->httpResponse->setHeader('ETag', $etag);
  744. $this->httpResponse->sendStatus(201);
  745. }
  746. }
  747. /**
  748. * WebDAV MKCOL
  749. *
  750. * The MKCOL method is used to create a new collection (directory) on the server
  751. *
  752. * @param string $uri
  753. * @return void
  754. */
  755. protected function httpMkcol($uri) {
  756. $requestBody = $this->httpRequest->getBody(true);
  757. if ($requestBody) {
  758. $contentType = $this->httpRequest->getHeader('Content-Type');
  759. if (strpos($contentType,'application/xml')!==0 && strpos($contentType,'text/xml')!==0) {
  760. // We must throw 415 for unsupported mkcol bodies
  761. throw new Exception\UnsupportedMediaType('The request body for the MKCOL request must have an xml Content-Type');
  762. }
  763. $dom = XMLUtil::loadDOMDocument($requestBody);
  764. if (XMLUtil::toClarkNotation($dom->firstChild)!=='{DAV:}mkcol') {
  765. // We must throw 415 for unsupported mkcol bodies
  766. throw new Exception\UnsupportedMediaType('The request body for the MKCOL request must be a {DAV:}mkcol request construct.');
  767. }
  768. $properties = [];
  769. foreach($dom->firstChild->childNodes as $childNode) {
  770. if (XMLUtil::toClarkNotation($childNode)!=='{DAV:}set') continue;
  771. $properties = array_merge($properties, XMLUtil::parseProperties($childNode, $this->propertyMap));
  772. }
  773. if (!isset($properties['{DAV:}resourcetype']))
  774. throw new Exception\BadRequest('The mkcol request must include a {DAV:}resourcetype property');
  775. $resourceType = $properties['{DAV:}resourcetype']->getValue();
  776. unset($properties['{DAV:}resourcetype']);
  777. } else {
  778. $properties = [];
  779. $resourceType = ['{DAV:}collection'];
  780. }
  781. $result = $this->createCollection($uri, $resourceType, $properties);
  782. if (is_array($result)) {
  783. $this->httpResponse->sendStatus(207);
  784. $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
  785. $this->httpResponse->sendBody(
  786. $this->generateMultiStatus([$result])
  787. );
  788. } else {
  789. $this->httpResponse->setHeader('Content-Length','0');
  790. $this->httpResponse->sendStatus(201);
  791. }
  792. }
  793. /**
  794. * WebDAV HTTP MOVE method
  795. *
  796. * This method moves one uri to a different uri. A lot of the actual request processing is done in getCopyMoveInfo
  797. *
  798. * @param string $uri
  799. * @return bool
  800. */
  801. protected function httpMove($uri) {
  802. $this->checkPreconditions();
  803. $moveInfo = $this->getCopyAndMoveInfo();
  804. // If the destination is part of the source tree, we must fail
  805. if ($moveInfo['destination']==$uri)
  806. throw new Exception\Forbidden('Source and destination uri are identical.');
  807. if ($moveInfo['destinationExists']) {
  808. if (!$this->broadcastEvent('beforeUnbind',[$moveInfo['destination']])) return false;
  809. $this->tree->delete($moveInfo['destination']);
  810. $this->broadcastEvent('afterUnbind',[$moveInfo['destination']]);
  811. }
  812. if (!$this->broadcastEvent('beforeUnbind',[$uri])) return false;
  813. if (!$this->broadcastEvent('beforeBind',[$moveInfo['destination']])) return false;
  814. $this->tree->move($uri,$moveInfo['destination']);
  815. $this->broadcastEvent('afterUnbind',[$uri]);
  816. $this->broadcastEvent('afterBind',[$moveInfo['destination']]);
  817. // If a resource was overwritten we should send a 204, otherwise a 201
  818. $this->httpResponse->setHeader('Content-Length','0');
  819. $this->httpResponse->sendStatus($moveInfo['destinationExists']?204:201);
  820. }
  821. /**
  822. * WebDAV HTTP COPY method
  823. *
  824. * This method copies one uri to a different uri, and works much like the MOVE request
  825. * A lot of the actual request processing is done in getCopyMoveInfo
  826. *
  827. * @param string $uri
  828. * @return bool
  829. */
  830. protected function httpCopy($uri) {
  831. $this->checkPreconditions();
  832. $copyInfo = $this->getCopyAndMoveInfo();
  833. // If the destination is part of the source tree, we must fail
  834. if ($copyInfo['destination']==$uri)
  835. throw new Exception\Forbidden('Source and destination uri are identical.');
  836. if ($copyInfo['destinationExists']) {
  837. if (!$this->broadcastEvent('beforeUnbind',[$copyInfo['destination']])) return false;
  838. $this->tree->delete($copyInfo['destination']);
  839. }
  840. if (!$this->broadcastEvent('beforeBind',[$copyInfo['destination']])) return false;
  841. $this->tree->copy($uri,$copyInfo['destination']);
  842. $this->broadcastEvent('afterBind',[$copyInfo['destination']]);
  843. // If a resource was overwritten we should send a 204, otherwise a 201
  844. $this->httpResponse->setHeader('Content-Length','0');
  845. $this->httpResponse->sendStatus($copyInfo['destinationExists']?204:201);
  846. }
  847. /**
  848. * HTTP REPORT method implementation
  849. *
  850. * Although the REPORT method is not part of the standard WebDAV spec (it's from rfc3253)
  851. * It's used in a lot of extensions, so it made sense to implement it into the core.
  852. *
  853. * @param string $uri
  854. * @return void
  855. */
  856. protected function httpReport($uri) {
  857. $body = $this->httpRequest->getBody(true);
  858. $dom = XMLUtil::loadDOMDocument($body);
  859. $reportName = XMLUtil::toClarkNotation($dom->firstChild);
  860. if ($this->broadcastEvent('report',[$reportName, $dom, $uri])) {
  861. // If broadcastEvent returned true, it means the report was not supported
  862. throw new Exception\ReportNotSupported();
  863. }
  864. }
  865. // }}}
  866. // {{{ HTTP/WebDAV protocol helpers
  867. /**
  868. * Returns an array with all the supported HTTP methods for a specific uri.
  869. *
  870. * @param string $uri
  871. * @return array
  872. */
  873. public function getAllowedMethods($uri) {
  874. $methods = [
  875. 'OPTIONS',
  876. 'GET',
  877. 'HEAD',
  878. 'DELETE',
  879. 'PROPFIND',
  880. 'PUT',
  881. 'PROPPATCH',
  882. 'COPY',
  883. 'MOVE',
  884. 'REPORT'
  885. ];
  886. // The MKCOL is only allowed on an unmapped uri
  887. try {
  888. $this->tree->getNodeForPath($uri);
  889. } catch (Exception\NotFound $e) {
  890. $methods[] = 'MKCOL';
  891. }
  892. // We're also checking if any of the plugins register any new methods
  893. foreach($this->plugins as $plugin) $methods = array_merge($methods, $plugin->getHTTPMethods($uri));
  894. array_unique($methods);
  895. return $methods;
  896. }
  897. /**
  898. * Gets the uri for the request, keeping the base uri into consideration
  899. *
  900. * @return string
  901. */
  902. public function getRequestUri() {
  903. return $this->calculateUri($this->httpRequest->getUri());
  904. }
  905. /**
  906. * Calculates the uri for a request, making sure that the base uri is stripped out
  907. *
  908. * @param string $uri
  909. * @throws Exception\Forbidden A permission denied exception is thrown whenever there was an attempt to supply a uri outside of the base uri
  910. * @return string
  911. */
  912. public function calculateUri($uri) {
  913. if ($uri[0]!='/' && strpos($uri,'://')) {
  914. $uri = parse_url($uri,PHP_URL_PATH);
  915. }
  916. $uri = str_replace('//','/',$uri);
  917. if (strpos($uri,$this->getBaseUri())===0) {
  918. return trim(URLUtil::decodePath(substr($uri,strlen($this->getBaseUri()))),'/');
  919. // A special case, if the baseUri was accessed without a trailing
  920. // slash, we'll accept it as well.
  921. } elseif ($uri.'/' === $this->getBaseUri()) {
  922. return '';
  923. } else {
  924. throw new Exception\Forbidden('Requested uri (' . $uri . ') is out of base uri (' . $this->getBaseUri() . ')');
  925. }
  926. }
  927. /**
  928. * Returns the HTTP depth header
  929. *
  930. * This method returns the contents of the HTTP depth request header. If the depth header was 'infinity' it will return the Sabre\DAV\Server::DEPTH_INFINITY object
  931. * It is possible to supply a default depth value, which is used when the depth header has invalid content, or is completely non-existent
  932. *
  933. * @param mixed $default
  934. * @return int
  935. */
  936. public function getHTTPDepth($default = self::DEPTH_INFINITY) {
  937. // If its not set, we'll grab the default
  938. $depth = $this->httpRequest->getHeader('Depth');
  939. if (is_null($depth)) return $default;
  940. if ($depth == 'infinity') return self::DEPTH_INFINITY;
  941. // If its an unknown value. we'll grab the default
  942. if (!ctype_digit($depth)) return $default;
  943. return (int)$depth;
  944. }
  945. /**
  946. * Returns the HTTP range header
  947. *
  948. * This method returns null if there is no well-formed HTTP range request
  949. * header or array($start, $end).
  950. *
  951. * The first number is the offset of the first byte in the range.
  952. * The second number is the offset of the last byte in the range.
  953. *
  954. * If the second offset is null, it should be treated as the offset of the last byte of the entity
  955. * If the first offset is null, the second offset should be used to retrieve the last x bytes of the entity
  956. *
  957. * @return array|null
  958. */
  959. public function getHTTPRange() {
  960. $range = $this->httpRequest->getHeader('range');
  961. if (is_null($range)) return null;
  962. // Matching "Range: bytes=1234-5678: both numbers are optional
  963. if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i',$range,$matches)) return null;
  964. if ($matches[1]==='' && $matches[2]==='') return null;
  965. return [
  966. $matches[1]!==''?$matches[1]:null,
  967. $matches[2]!==''?$matches[2]:null,
  968. ];
  969. }
  970. /**
  971. * Returns the HTTP Prefer header information.
  972. *
  973. * The prefer header is defined in:
  974. * http://tools.ietf.org/html/draft-snell-http-prefer-14
  975. *
  976. * This method will return an array with options.
  977. *
  978. * Currently, the following options may be returned:
  979. * [
  980. * 'return-asynch' => true,
  981. * 'return-minimal' => true,
  982. * 'return-representation' => true,
  983. * 'wait' => 30,
  984. * 'strict' => true,
  985. * 'lenient' => true,
  986. * ]
  987. *
  988. * This method also supports the Brief header, and will also return
  989. * 'return-minimal' if the brief header was set to 't'.
  990. *
  991. * For the boolean options, false will be returned if the headers are not
  992. * specified. For the integer options it will be 'null'.
  993. *
  994. * @return array
  995. */
  996. public function getHTTPPrefer() {
  997. $result = [
  998. 'return-asynch' => false,
  999. 'return-minimal' => false,
  1000. 'return-representation' => false,
  1001. 'wait' => null,
  1002. 'strict' => false,
  1003. 'lenient' => false,
  1004. ];
  1005. if ($prefer = $this->httpRequest->getHeader('Prefer')) {
  1006. $parameters = array_map('trim',
  1007. explode(',', $prefer)
  1008. );
  1009. foreach($parameters as $parameter) {
  1010. // Right now our regex only supports the tokens actually
  1011. // specified in the draft. We may need to expand this if new
  1012. // tokens get registered.
  1013. if(!preg_match('/^(?P<token>[a-z0-9-]+)(?:=(?P<value>[0-9]+))?$/', $parameter, $matches)) {
  1014. continue;
  1015. }
  1016. switch($matches['token']) {
  1017. case 'return-asynch' :
  1018. case 'return-minimal' :
  1019. case 'return-representation' :
  1020. case 'strict' :
  1021. case 'lenient' :
  1022. $result[$matches['token']] = true;
  1023. break;
  1024. case 'wait' :
  1025. $result[$matches['token']] = $matches['value'];
  1026. break;
  1027. }
  1028. }
  1029. }
  1030. if ($this->httpRequest->getHeader('Brief')=='t') {
  1031. $result['return-minimal'] = true;
  1032. }
  1033. return $result;
  1034. }
  1035. /**
  1036. * Returns information about Copy and Move requests
  1037. *
  1038. * This function is created to help getting information about the source and the destination for the
  1039. * WebDAV MOVE and COPY HTTP request. It also validates a lot of information and throws proper exceptions
  1040. *
  1041. * The returned value is an array with the following keys:
  1042. * * destination - Destination path
  1043. * * destinationExists - Whether or not the destination is an existing url (and should therefore be overwritten)
  1044. *
  1045. * @return array
  1046. */
  1047. public function getCopyAndMoveInfo() {
  1048. // Collecting the relevant HTTP headers
  1049. if (!$this->httpRequest->getHeader('Destination')) throw new Exception\BadRequest('The destination header was not supplied');
  1050. $destination = $this->calculateUri($this->httpRequest->getHeader('Destination'));
  1051. $overwrite = $this->httpRequest->getHeader('Overwrite');
  1052. if (!$overwrite) $overwrite = 'T';
  1053. if (strtoupper($overwrite)=='T') $overwrite = true;
  1054. elseif (strtoupper($overwrite)=='F') $overwrite = false;
  1055. // We need to throw a bad request exception, if the header was invalid
  1056. else throw new Exception\BadRequest('The HTTP Overwrite header should be either T or F');
  1057. list($destinationDir) = URLUtil::splitPath($destination);
  1058. try {
  1059. $destinationParent = $this->tree->getNodeForPath($destinationDir);
  1060. if (!($destinationParent instanceof ICollection)) throw new Exception\UnsupportedMediaType('The destination node is not a collection');
  1061. } catch (Exception\NotFound $e) {
  1062. // If the destination parent node is not found, we throw a 409
  1063. throw new Exception\Conflict('The destination node is not found');
  1064. }
  1065. try {
  1066. $destinationNode = $this->tree->getNodeForPath($destination);
  1067. // If this succeeded, it means the destination already exists
  1068. // we'll need to throw precondition failed in case overwrite is false
  1069. if (!$overwrite) throw new Exception\PreconditionFailed('The destination node already exists, and the overwrite header is set to false','Overwrite');
  1070. } catch (Exception\NotFound $e) {
  1071. // Destination didn't exist, we're all good
  1072. $destinationNode = false;
  1073. }
  1074. // These are the three relevant properties we need to return
  1075. return [
  1076. 'destination' => $destination,
  1077. 'destinationExists' => $destinationNode==true,
  1078. 'destinationNode' => $destinationNode,
  1079. ];
  1080. }
  1081. /**
  1082. * Returns a list of properties for a path
  1083. *
  1084. * This is a simplified version getPropertiesForPath.
  1085. * if you aren't interested in status codes, but you just
  1086. * want to have a flat list of properties. Use this method.
  1087. *
  1088. * @param string $path
  1089. * @param array $propertyNames
  1090. */
  1091. public function getProperties($path, $propertyNames) {
  1092. $result = $this->getPropertiesForPath($path,$propertyNames,0);
  1093. return $result[0][200];
  1094. }
  1095. /**
  1096. * A kid-friendly way to fetch properties for a node's children.
  1097. *
  1098. * The returned array will be indexed by the path of the of child node.
  1099. * Only properties that are actually found will be returned.
  1100. *
  1101. * The parent node will not be returned.
  1102. *
  1103. * @param string $path
  1104. * @param array $propertyNames
  1105. * @return array
  1106. */
  1107. public function getPropertiesForChildren($path, $propertyNames) {
  1108. $result = [];
  1109. foreach($this->getPropertiesForPath($path,$propertyNames,1) as $k=>$row) {
  1110. // Skipping the parent path
  1111. if ($k === 0) continue;
  1112. $result[$row['href']] = $row[200];
  1113. }
  1114. return $result;
  1115. }
  1116. /**
  1117. * Returns a list of HTTP headers for a particular resource
  1118. *
  1119. * The generated http headers are based on properties provided by the
  1120. * resource. The method basically provides a simple mapping between
  1121. * DAV property and HTTP header.
  1122. *
  1123. * The headers are intended to be used for HEAD and GET requests.
  1124. *
  1125. * @param string $path
  1126. * @return array
  1127. */
  1128. public function getHTTPHeaders($path) {
  1129. $propertyMap = [
  1130. '{DAV:}getcontenttype' => 'Content-Type',
  1131. '{DAV:}getcontentlength' => 'Content-Length',
  1132. '{DAV:}getlastmodified' => 'Last-Modified',
  1133. '{DAV:}getetag' => 'ETag',
  1134. ];
  1135. $properties = $this->getProperties($path,array_keys($propertyMap));
  1136. $headers = [];
  1137. foreach($propertyMap as $property=>$header) {
  1138. if (!isset($properties[$property])) continue;
  1139. if (is_scalar($properties[$property])) {
  1140. $headers[$header] = $properties[$property];
  1141. // GetLastModified gets special cased
  1142. } elseif ($properties[$property] instanceof Property\GetLastModified) {
  1143. $headers[$header] = HTTP\Util::toHTTPDate($properties[$property]->getTime());
  1144. }
  1145. }
  1146. return $headers;
  1147. }
  1148. /**
  1149. * Returns a list of properties for a given path
  1150. *
  1151. * The path that should be supplied should have the baseUrl stripped out
  1152. * The list of properties should be supplied in Clark notation. If the list is empty
  1153. * 'allprops' is assumed.
  1154. *
  1155. * If a depth of 1 is requested child elements will also be returned.
  1156. *
  1157. * @param string $path
  1158. * @param array $propertyNames
  1159. * @param int $depth
  1160. * @return array
  1161. */
  1162. public function getPropertiesForPath($path, $propertyNames = [], $depth = 0) {
  1163. if ($depth!=0) $depth = 1;
  1164. $path = rtrim($path,'/');
  1165. $returnPropertyList = [];
  1166. $parentNode = $this->tree->getNodeForPath($path);
  1167. $nodes = [
  1168. $path => $parentNode
  1169. ];
  1170. if ($depth==1 && $parentNode instanceof ICollection) {
  1171. foreach($this->tree->getChildren($path) as $childNode)
  1172. $nodes[$path . '/' . $childNode->getName()] = $childNode;
  1173. }
  1174. foreach($nodes as $myPath=>$node) {
  1175. $r = $this->getPropertiesByNode($myPath, $node, $propertyNames);
  1176. if ($r) {
  1177. $returnPropertyList[] = $r;
  1178. }
  1179. }
  1180. return $returnPropertyList;
  1181. }
  1182. /**
  1183. * Returns a list of properties for a list of paths.
  1184. *
  1185. * The path that should be supplied should have the baseUrl stripped out
  1186. * The list of properties should be supplied in Clark notation. If the list is empty
  1187. * 'allprops' is assumed.
  1188. *
  1189. * The result is returned as an array, with paths for it's keys.
  1190. * The result may be returned out of order.
  1191. *
  1192. * @param array $paths
  1193. * @param array $propertyNames
  1194. * @return array
  1195. */
  1196. public function getPropertiesForMultiplePaths(array $paths, array $propertyNames = []) {
  1197. $result = [
  1198. ];
  1199. $nodes = $this->tree->getMultipleNodes($paths);
  1200. foreach($nodes as $path=>$node) {
  1201. $result[$path] = $this->getPropertiesByNode($path, $node, $propertyNames);
  1202. }
  1203. return $result;
  1204. }
  1205. /**
  1206. * Determines all properties for a node.
  1207. *
  1208. * This method tries to grab all properties for a node. This method is used
  1209. * internally getPropertiesForPath and a few others.
  1210. *
  1211. * @param string $path The path we're properties for fetching.
  1212. * @param INode $node
  1213. * @param array $propertyNames list of properties to fetch.
  1214. * @return array
  1215. */
  1216. protected function getPropertiesByNode($path, INode $node, array $propertyNames) {
  1217. $newProperties = [
  1218. '200' => [],
  1219. '404' => [],
  1220. ];
  1221. // If no properties were supplied, it means this was an 'allprops'
  1222. // request, and we use a default set of properties.
  1223. $allProperties = count($propertyNames)===0;
  1224. if ($allProperties) {
  1225. // Default list of propertyNames, when all properties were requested.
  1226. $propertyNames = [
  1227. '{DAV:}getlastmodified',
  1228. '{DAV:}getcontentlength',
  1229. '{DAV:}resourcetype',
  1230. '{DAV:}quota-used-bytes',
  1231. '{DAV:}quota-available-bytes',
  1232. '{DAV:}getetag',
  1233. '{DAV:}getcontenttype',
  1234. ];
  1235. }
  1236. // If the resourceType was not part of the list, we manually add it
  1237. // and mark it for removal. We need to know the resourcetype in order
  1238. // to make certain decisions about the entry.
  1239. // WebDAV dictates we should add a / and the end of href's for collections
  1240. $removeRT = false;
  1241. if (!in_array('{DAV:}resourcetype',$propertyNames)) {
  1242. $propertyNames[] = '{DAV:}resourcetype';
  1243. $removeRT = true;
  1244. }
  1245. $result = $this->broadcastEvent('beforeGetProperties',[$path, $node, &$propertyNames, &$newProperties]);
  1246. // If this method explicitly returned false, we must ignore this
  1247. // node as it is inaccessible.
  1248. if ($result===false) return;
  1249. if (count($propertyNames) > 0) {
  1250. if ($node instanceof IProperties) {
  1251. $nodeProperties = $node->getProperties($propertyNames);
  1252. // The getProperties method may give us too much,
  1253. // properties, in case the implementor was lazy.
  1254. //
  1255. // So as we loop through this list, we will only take the
  1256. // properties that were actually requested and discard the
  1257. // rest.
  1258. foreach($propertyNames as $k=>$propertyName) {
  1259. if (isset($nodeProperties[$propertyName])) {
  1260. unset($propertyNames[$k]);
  1261. $newProperties[200][$propertyName] = $nodeProperties[$propertyName];
  1262. }
  1263. }
  1264. }
  1265. }
  1266. foreach($propertyNames as $prop) {
  1267. if (isset($newProperties[200][$prop])) continue;
  1268. switch($prop) {
  1269. case '{DAV:}getlastmodified' : if ($node->getLastModified()) $newProperties[200][$prop] = new Property\GetLastModified($node->getLastModified()); break;
  1270. case '{DAV:}getcontentlength' :
  1271. if ($node instanceof IFile) {
  1272. $size = $node->getSize();
  1273. if (!is_null($size)) {
  1274. $newProperties[200][$prop] = (int)$node->getSize();
  1275. }
  1276. }
  1277. break;
  1278. case '{DAV:}quota-used-bytes' :
  1279. if ($node instanceof IQuota) {
  1280. $quotaInfo = $node->getQuotaInfo();
  1281. $newProperties[200][$prop] = $quotaInfo[0];
  1282. }
  1283. break;
  1284. case '{DAV:}quota-available-bytes' :
  1285. if ($node instanceof IQuota) {
  1286. $quotaInfo = $node->getQuotaInfo();
  1287. $newProperties[200][$prop] = $quotaInfo[1];
  1288. }
  1289. break;
  1290. case '{DAV:}getetag' : if ($node instanceof IFile && $etag = $node->getETag()) $newProperties[200][$prop] = $etag; break;
  1291. case '{DAV:}getcontenttype' : if ($node instanceof IFile && $ct = $node->getContentType()) $newProperties[200][$prop] = $ct; break;
  1292. case '{DAV:}supported-report-set' :
  1293. $reports = [];
  1294. foreach($this->plugins as $plugin) {
  1295. $reports = array_merge($reports, $plugin->getSupportedReportSet($path));
  1296. }
  1297. $newProperties[200][$prop] = new Property\SupportedReportSet($reports);
  1298. break;
  1299. case '{DAV:}resourcetype' :
  1300. $newProperties[200]['{DAV:}resourcetype'] = new Property\ResourceType();
  1301. foreach($this->resourceTypeMapping as $className => $resourceType) {
  1302. if ($node instanceof $className) $newProperties[200]['{DAV:}resourcetype']->add($resourceType);
  1303. }
  1304. break;
  1305. }
  1306. // If we were unable to find the property, we will list it as 404.
  1307. if (!$allProperties && !isset($newProperties[200][$prop])) $newProperties[404][$prop] = null;
  1308. }
  1309. $this->broadcastEvent('afterGetProperties',[trim($path,'/'),&$newProperties, $node]);
  1310. $newProperties['href'] = trim($path,'/');
  1311. // Its is a WebDAV recommendation to add a trailing slash to collectionnames.
  1312. // Apple's iCal also requires a trailing slash for principals (rfc 3744), though this is non-standard.
  1313. if ($path!='' && isset($newProperties[200]['{DAV:}resourcetype'])) {
  1314. $rt = $newProperties[200]['{DAV:}resourcetype'];
  1315. if ($rt->is('{DAV:}collection') || $rt->is('{DAV:}principal')) {
  1316. $newProperties['href'] .='/';
  1317. }
  1318. }
  1319. // If the resourcetype property was manually added to the requested property list,
  1320. // we will remove it again.
  1321. if ($removeRT) unset($newProperties[200]['{DAV:}resourcetype']);
  1322. return $newProperties;
  1323. }
  1324. /**
  1325. * This method is invoked by sub-systems creating a new file.
  1326. *
  1327. * Currently this is done by HTTP PUT and HTTP LOCK (in the Locks_Plugin).
  1328. * It was important to get this done through a centralized function,
  1329. * allowing plugins to intercept this using the beforeCreateFile event.
  1330. *
  1331. * This method will return true if the file was actually created
  1332. *
  1333. * @param string $uri
  1334. * @param resource $data
  1335. * @param string $etag
  1336. * @return bool
  1337. */
  1338. public function createFile($uri,$data, &$etag = null) {
  1339. list($dir,$name) = URLUtil::splitPath($uri);
  1340. if (!$this->broadcastEvent('beforeBind',[$uri])) return false;
  1341. $parent = $this->tree->getNodeForPath($dir);
  1342. if (!$parent instanceof ICollection) {
  1343. throw new Exception\Conflict('Files can only be created as children of collections');
  1344. }
  1345. // It is possible for an event handler to modify the content of the
  1346. // body, before it gets written. If this is the case, $modified
  1347. // should be set to true.
  1348. //
  1349. // If $modified is true, we must not send back an etag.
  1350. $modified = false;
  1351. if (!$this->broadcastEvent('beforeCreateFile',[$uri, &$data, $parent, &$modified])) return false;
  1352. $etag = $parent->createFile($name,$data);
  1353. if ($modified) $etag = null;
  1354. $this->tree->markDirty($dir . '/' . $name);
  1355. $this->broadcastEvent('afterBind',[$uri]);
  1356. $this->broadcastEvent('afterCreateFile',[$uri, $parent]);
  1357. return true;
  1358. }
  1359. /**
  1360. * This method is invoked by sub-systems creating a new directory.
  1361. *
  1362. * @param string $uri
  1363. * @return void
  1364. */
  1365. public function createDirectory($uri) {
  1366. $this->createCollection($uri,['{DAV:}collection'], []);
  1367. }
  1368. /**
  1369. * Use this method to create a new collection
  1370. *
  1371. * The {DAV:}resourcetype is specified using the resourceType array.
  1372. * At the very least it must contain {DAV:}collection.
  1373. *
  1374. * The properties array can contain a list of additional properties.
  1375. *
  1376. * @param string $uri The new uri
  1377. * @param array $resourceType The resourceType(s)
  1378. * @param array $properties A list of properties
  1379. * @return array|null
  1380. */
  1381. public function createCollection($uri, array $resourceType, array $properties) {
  1382. list($parentUri,$newName) = URLUtil::splitPath($uri);
  1383. // Making sure {DAV:}collection was specified as resourceType
  1384. if (!in_array('{DAV:}collection', $resourceType)) {
  1385. throw new Exception\InvalidResourceType('The resourceType for this collection must at least include {DAV:}collection');
  1386. }
  1387. // Making sure the parent exists
  1388. try {
  1389. $parent = $this->tree->getNodeForPath($parentUri);
  1390. } catch (Exception\NotFound $e) {
  1391. throw new Exception\Conflict('Parent node does not exist');
  1392. }
  1393. // Making sure the parent is a collection
  1394. if (!$parent instanceof ICollection) {
  1395. throw new Exception\Conflict('Parent node is not a collection');
  1396. }
  1397. // Making sure the child does not already exist
  1398. try {
  1399. $parent->getChild($newName);
  1400. // If we got here.. it means there's already a node on that url, and we need to throw a 405
  1401. throw new Exception\MethodNotAllowed('The resource you tried to create already exists');
  1402. } catch (Exception\NotFound $e) {
  1403. // This is correct
  1404. }
  1405. if (!$this->broadcastEvent('beforeBind',[$uri])) return;
  1406. // There are 2 modes of operation. The standard collection
  1407. // creates the directory, and then updates properties
  1408. // the extended collection can create it directly.
  1409. if ($parent instanceof IExtendedCollection) {
  1410. $parent->createExtendedCollection($newName, $resourceType, $properties);
  1411. } else {
  1412. // No special resourcetypes are supported
  1413. if (count($resourceType)>1) {
  1414. throw new Exception\InvalidResourceType('The {DAV:}resourcetype you specified is not supported here.');
  1415. }
  1416. $parent->createDirectory($newName);
  1417. $rollBack = false;
  1418. $exception = null;
  1419. $errorResult = null;
  1420. if (count($properties)>0) {
  1421. try {
  1422. $errorResult = $this->updateProperties($uri, $properties);
  1423. if (!isset($errorResult[200])) {
  1424. $rollBack = true;
  1425. }
  1426. } catch (Exception $e) {
  1427. $rollBack = true;
  1428. $exception = $e;
  1429. }
  1430. }
  1431. if ($rollBack) {
  1432. if (!$this->broadcastEvent('beforeUnbind',[$uri])) return;
  1433. $this->tree->delete($uri);
  1434. // Re-throwing exception
  1435. if ($exception) throw $exception;
  1436. return $errorResult;
  1437. }
  1438. }
  1439. $this->tree->markDirty($parentUri);
  1440. $this->broadcastEvent('afterBind',[$uri]);
  1441. }
  1442. /**
  1443. * This method updates a resource's properties
  1444. *
  1445. * The properties array must be a list of properties. Array-keys are
  1446. * property names in clarknotation, array-values are it's values.
  1447. * If a property must be deleted, the value should be null.
  1448. *
  1449. * Note that this request should either completely succeed, or
  1450. * completely fail.
  1451. *
  1452. * The response is an array with statuscodes for keys, which in turn
  1453. * contain arrays with propertynames. This response can be used
  1454. * to generate a multistatus body.
  1455. *
  1456. * @param string $uri
  1457. * @param array $properties
  1458. * @return array
  1459. */
  1460. public function updateProperties($uri, array $properties) {
  1461. // we'll start by grabbing the node, this will throw the appropriate
  1462. // exceptions if it doesn't.
  1463. $node = $this->tree->getNodeForPath($uri);
  1464. $result = [
  1465. 200 => [],
  1466. 403 => [],
  1467. 424 => [],
  1468. ];
  1469. $remainingProperties = $properties;
  1470. $hasError = false;
  1471. // Running through all properties to make sure none of them are protected
  1472. if (!$hasError) foreach($properties as $propertyName => $value) {
  1473. if(in_array($propertyName, $this->protectedProperties)) {
  1474. $result[403][$propertyName] = null;
  1475. unset($remainingProperties[$propertyName]);
  1476. $hasError = true;
  1477. }
  1478. }
  1479. if (!$hasError) {
  1480. // Allowing plugins to take care of property updating
  1481. $hasError = !$this->broadcastEvent('updateProperties', [
  1482. &$remainingProperties,
  1483. &$result,
  1484. $node
  1485. ]);
  1486. }
  1487. // If the node is not an instance of Sabre\DAV\IProperties, every
  1488. // property is 403 Forbidden
  1489. if (!$hasError && count($remainingProperties) && !($node instanceof IProperties)) {
  1490. $hasError = true;
  1491. foreach($properties as $propertyName=> $value) {
  1492. $result[403][$propertyName] = null;
  1493. }
  1494. $remainingProperties = [];
  1495. }
  1496. // Only if there were no errors we may attempt to update the resource
  1497. if (!$hasError) {
  1498. if (count($remainingProperties)>0) {
  1499. $updateResult = $node->updateProperties($remainingProperties);
  1500. if ($updateResult===true) {
  1501. // success
  1502. foreach($remainingProperties as $propertyName=>$value) {
  1503. $result[200][$propertyName] = null;
  1504. }
  1505. } elseif ($updateResult===false) {
  1506. // The node failed to update the properties for an
  1507. // unknown reason
  1508. foreach($remainingProperties as $propertyName=>$value) {
  1509. $result[403][$propertyName] = null;
  1510. }
  1511. } elseif (is_array($updateResult)) {
  1512. // The node has detailed update information
  1513. // We need to merge the results with the earlier results.
  1514. foreach($updateResult as $status => $props) {
  1515. if (is_array($props)) {
  1516. if (!isset($result[$status]))
  1517. $result[$status] = [];
  1518. $result[$status] = array_merge($result[$status], $updateResult[$status]);
  1519. }
  1520. }
  1521. } else {
  1522. throw new Exception('Invalid result from updateProperties');
  1523. }
  1524. $remainingProperties = [];
  1525. }
  1526. }
  1527. foreach($remainingProperties as $propertyName=>$value) {
  1528. // if there are remaining properties, it must mean
  1529. // there's a dependency failure
  1530. $result[424][$propertyName] = null;
  1531. }
  1532. // Removing empty array values
  1533. foreach($result as $status=>$props) {
  1534. if (count($props)===0) unset($result[$status]);
  1535. }
  1536. $result['href'] = $uri;
  1537. return $result;
  1538. }
  1539. /**
  1540. * This method checks the main HTTP preconditions.
  1541. *
  1542. * Currently these are:
  1543. * * If-Match
  1544. * * If-None-Match
  1545. * * If-Modified-Since
  1546. * * If-Unmodified-Since
  1547. *
  1548. * The method will return true if all preconditions are met
  1549. * The method will return false, or throw an exception if preconditions
  1550. * failed. If false is returned the operation should be aborted, and
  1551. * the appropriate HTTP response headers are already set.
  1552. *
  1553. * Normally this method will throw 412 Precondition Failed for failures
  1554. * related to If-None-Match, If-Match and If-Unmodified Since. It will
  1555. * set the status to 304 Not Modified for If-Modified_since.
  1556. *
  1557. * If the $handleAsGET argument is set to true, it will also return 304
  1558. * Not Modified for failure of the If-None-Match precondition. This is the
  1559. * desired behaviour for HTTP GET and HTTP HEAD requests.
  1560. *
  1561. * @param bool $handleAsGET
  1562. * @return bool
  1563. */
  1564. public function checkPreconditions($handleAsGET = false) {
  1565. $uri = $this->getRequestUri();
  1566. $node = null;
  1567. $lastMod = null;
  1568. $etag = null;
  1569. if ($ifMatch = $this->httpRequest->getHeader('If-Match')) {
  1570. // If-Match contains an entity tag. Only if the entity-tag
  1571. // matches we are allowed to make the request succeed.
  1572. // If the entity-tag is '*' we are only allowed to make the
  1573. // request succeed if a resource exists at that url.
  1574. try {
  1575. $node = $this->tree->getNodeForPath($uri);
  1576. } catch (Exception\NotFound $e) {
  1577. throw new Exception\PreconditionFailed('An If-Match header was specified and the resource did not exist','If-Match');
  1578. }
  1579. // Only need to check entity tags if they are not *
  1580. if ($ifMatch!=='*') {
  1581. // There can be multiple etags
  1582. $ifMatch = explode(',',$ifMatch);
  1583. $haveMatch = false;
  1584. foreach($ifMatch as $ifMatchItem) {
  1585. // Stripping any extra spaces
  1586. $ifMatchItem = trim($ifMatchItem,' ');
  1587. $etag = $node->getETag();
  1588. if ($etag===$ifMatchItem) {
  1589. $haveMatch = true;
  1590. } else {
  1591. // Evolution has a bug where it sometimes prepends the "
  1592. // with a \. This is our workaround.
  1593. if (str_replace('\\"','"', $ifMatchItem) === $etag) {
  1594. $haveMatch = true;
  1595. }
  1596. }
  1597. }
  1598. if (!$haveMatch) {
  1599. throw new Exception\PreconditionFailed('An If-Match header was specified, but none of the specified the ETags matched.','If-Match');
  1600. }
  1601. }
  1602. }
  1603. if ($ifNoneMatch = $this->httpRequest->getHeader('If-None-Match')) {
  1604. // The If-None-Match header contains an etag.
  1605. // Only if the ETag does not match the current ETag, the request will succeed
  1606. // The header can also contain *, in which case the request
  1607. // will only succeed if the entity does not exist at all.
  1608. $nodeExists = true;
  1609. if (!$node) {
  1610. try {
  1611. $node = $this->tree->getNodeForPath($uri);
  1612. } catch (Exception\NotFound $e) {
  1613. $nodeExists = false;
  1614. }
  1615. }
  1616. if ($nodeExists) {
  1617. $haveMatch = false;
  1618. if ($ifNoneMatch==='*') $haveMatch = true;
  1619. else {
  1620. // There might be multiple etags
  1621. $ifNoneMatch = explode(',', $ifNoneMatch);
  1622. $etag = $node->getETag();
  1623. foreach($ifNoneMatch as $ifNoneMatchItem) {
  1624. // Stripping any extra spaces
  1625. $ifNoneMatchItem = trim($ifNoneMatchItem,' ');
  1626. if ($etag===$ifNoneMatchItem) $haveMatch = true;
  1627. }
  1628. }
  1629. if ($haveMatch) {
  1630. if ($handleAsGET) {
  1631. $this->httpResponse->sendStatus(304);
  1632. return false;
  1633. } else {
  1634. throw new Exception\PreconditionFailed('An If-None-Match header was specified, but the ETag matched (or * was specified).','If-None-Match');
  1635. }
  1636. }
  1637. }
  1638. }
  1639. if (!$ifNoneMatch && ($ifModifiedSince = $this->httpRequest->getHeader('If-Modified-Since'))) {
  1640. // The If-Modified-Since header contains a date. We
  1641. // will only return the entity if it has been changed since
  1642. // that date. If it hasn't been changed, we return a 304
  1643. // header
  1644. // Note that this header only has to be checked if there was no If-None-Match header
  1645. // as per the HTTP spec.
  1646. $date = HTTP\Util::parseHTTPDate($ifModifiedSince);
  1647. if ($date) {
  1648. if (is_null($node)) {
  1649. $node = $this->tree->getNodeForPath($uri);
  1650. }
  1651. $lastMod = $node->getLastModified();
  1652. if ($lastMod) {
  1653. $lastMod = new \DateTime('@' . $lastMod);
  1654. if ($lastMod <= $date) {
  1655. $this->httpResponse->sendStatus(304);
  1656. $this->httpResponse->setHeader('Last-Modified', HTTP\Util::toHTTPDate($lastMod));
  1657. return false;
  1658. }
  1659. }
  1660. }
  1661. }
  1662. if ($ifUnmodifiedSince = $this->httpRequest->getHeader('If-Unmodified-Since')) {
  1663. // The If-Unmodified-Since will allow allow the request if the
  1664. // entity has not changed since the specified date.
  1665. $date = HTTP\Util::parseHTTPDate($ifUnmodifiedSince);
  1666. // We must only check the date if it's valid
  1667. if ($date) {
  1668. if (is_null($node)) {
  1669. $node = $this->tree->getNodeForPath($uri);
  1670. }
  1671. $lastMod = $node->getLastModified();
  1672. if ($lastMod) {
  1673. $lastMod = new \DateTime('@' . $lastMod);
  1674. if ($lastMod > $date) {
  1675. throw new Exception\PreconditionFailed('An If-Unmodified-Since header was specified, but the entity has been changed since the specified date.','If-Unmodified-Since');
  1676. }
  1677. }
  1678. }
  1679. }
  1680. // Now the hardest, the If: header. The If: header can contain multiple
  1681. // urls, etags and so-called 'state tokens'.
  1682. //
  1683. // Examples of state tokens include lock-tokens (as defined in rfc4918)
  1684. // and sync-tokens (as defined in rfc6578).
  1685. //
  1686. // The only proper way to deal with these, is to emit events, that a
  1687. // Sync and Lock plugin can pick up.
  1688. $ifConditions = $this->getIfConditions();
  1689. foreach($ifConditions as $kk => $ifCondition) {
  1690. foreach($ifCondition['tokens'] as $ii => $token) {
  1691. $ifConditions[$kk]['tokens'][$ii]['validToken'] = false;
  1692. }
  1693. }
  1694. // Plugins are responsible for validating all the tokens.
  1695. // If a plugin deemed a token 'valid', it will set 'validToken' to
  1696. // true.
  1697. $this->broadcastEvent('validateTokens', [ &$ifConditions ]);
  1698. // Now we're going to analyze the result.
  1699. // Every ifCondition needs to validate to true, so we exit as soon as
  1700. // we have an invalid condition.
  1701. foreach($ifConditions as $ifCondition) {
  1702. $uri = $ifCondition['uri'];
  1703. $tokens = $ifCondition['tokens'];
  1704. // We only need 1 valid token for the condition to succeed.
  1705. foreach($tokens as $token) {
  1706. $tokenValid = $token['validToken'] || !$token['token'];
  1707. $etagValid = false;
  1708. if (!$token['etag']) {
  1709. $etagValid = true;
  1710. }
  1711. // Checking the etag, only if the token was already deamed
  1712. // valid and there is one.
  1713. if ($token['etag'] && $tokenValid) {
  1714. // The token was valid, and there was an etag.. We must
  1715. // grab the current etag and check it.
  1716. $node = $this->tree->getNodeForPath($uri);
  1717. $etagValid = $node->getETag() == $token['etag'];
  1718. }
  1719. if (($tokenValid && $etagValid) ^ $token['negate']) {
  1720. // Both were valid, so we can go to the next condition.
  1721. continue 2;
  1722. }
  1723. }
  1724. // If we ended here, it means there was no valid etag + token
  1725. // combination found for the current condition. This means we fail!
  1726. throw new Exception\PreconditionFailed('Failed to find a valid token/etag combination for ' . $uri, 'If');
  1727. }
  1728. return true;
  1729. }
  1730. /**
  1731. * This method is created to extract information from the WebDAV HTTP 'If:' header
  1732. *
  1733. * The If header can be quite complex, and has a bunch of features. We're using a regex to extract all relevant information
  1734. * The function will return an array, containing structs with the following keys
  1735. *
  1736. * * uri - the uri the condition applies to.
  1737. * * tokens - The lock token. another 2 dimensional array containing 3 elements
  1738. *
  1739. * Example 1:
  1740. *
  1741. * If: (<opaquelocktoken:181d4fae-7d8c-11d0-a765-00a0c91e6bf2>)
  1742. *
  1743. * Would result in:
  1744. *
  1745. * [
  1746. * [
  1747. * 'uri' => '/request/uri',
  1748. * 'tokens' => [
  1749. * [
  1750. * [
  1751. * 'negate' => false,
  1752. * 'token' => 'opaquelocktoken:181d4fae-7d8c-11d0-a765-00a0c91e6bf2',
  1753. * 'etag' => ""
  1754. * ]
  1755. * ]
  1756. * ],
  1757. * ]
  1758. * ]
  1759. *
  1760. * Example 2:
  1761. *
  1762. * If: </path/> (Not <opaquelocktoken:181d4fae-7d8c-11d0-a765-00a0c91e6bf2> ["Im An ETag"]) (["Another ETag"]) </path2/> (Not ["Path2 ETag"])
  1763. *
  1764. * Would result in:
  1765. *
  1766. * [
  1767. * [
  1768. * 'uri' => 'path',
  1769. * 'tokens' => [
  1770. * [
  1771. * [
  1772. * 'negate' => true,
  1773. * 'token' => 'opaquelocktoken:181d4fae-7d8c-11d0-a765-00a0c91e6bf2',
  1774. * 'etag' => '"Im An ETag"'
  1775. * ],
  1776. * [
  1777. * 'negate' => false,
  1778. * 'token' => '',
  1779. * 'etag' => '"Another ETag"'
  1780. * ]
  1781. * ]
  1782. * ],
  1783. * ],
  1784. * [
  1785. * 'uri' => 'path2',
  1786. * 'tokens' => [
  1787. * [
  1788. * [
  1789. * 'negate' => true,
  1790. * 'token' => '',
  1791. * 'etag' => '"Path2 ETag"'
  1792. * ]
  1793. * ]
  1794. * ],
  1795. * ],
  1796. * ]
  1797. *
  1798. * @return array
  1799. */
  1800. public function getIfConditions() {
  1801. $header = $this->httpRequest->getHeader('If');
  1802. if (!$header) return [];
  1803. $matches = [];
  1804. $regex = '/(?:\<(?P<uri>.*?)\>\s)?\((?P<not>Not\s)?(?:\<(?P<token>[^\>]*)\>)?(?:\s?)(?:\[(?P<etag>[^\]]*)\])?\)/im';
  1805. preg_match_all($regex,$header,$matches,PREG_SET_ORDER);
  1806. $conditions = [];
  1807. foreach($matches as $match) {
  1808. // If there was no uri specified in this match, and there were
  1809. // already conditions parsed, we add the condition to the list of
  1810. // conditions for the previous uri.
  1811. if (!$match['uri'] && count($conditions)) {
  1812. $conditions[count($conditions)-1]['tokens'][] = [
  1813. 'negate' => $match['not']?true:false,
  1814. 'token' => $match['token'],
  1815. 'etag' => isset($match['etag'])?$match['etag']:''
  1816. ];
  1817. } else {
  1818. if (!$match['uri']) {
  1819. $realUri = $this->getRequestUri();
  1820. } else {
  1821. $realUri = $this->calculateUri($match['uri']);
  1822. }
  1823. $conditions[] = [
  1824. 'uri' => $realUri,
  1825. 'tokens' => [
  1826. [
  1827. 'negate' => $match['not']?true:false,
  1828. 'token' => $match['token'],
  1829. 'etag' => isset($match['etag'])?$match['etag']:''
  1830. ]
  1831. ],
  1832. ];
  1833. }
  1834. }
  1835. return $conditions;
  1836. }
  1837. // }}}
  1838. // {{{ XML Readers & Writers
  1839. /**
  1840. * Generates a WebDAV propfind response body based on a list of nodes.
  1841. *
  1842. * If 'strip404s' is set to true, all 404 responses will be removed.
  1843. *
  1844. * @param array $fileProperties The list with nodes
  1845. * @param bool strip404s
  1846. * @return string
  1847. */
  1848. public function generateMultiStatus(array $fileProperties, $strip404s = false) {
  1849. $dom = new \DOMDocument('1.0','utf-8');
  1850. //$dom->formatOutput = true;
  1851. $multiStatus = $dom->createElement('d:multistatus');
  1852. $dom->appendChild($multiStatus);
  1853. // Adding in default namespaces
  1854. foreach($this->xmlNamespaces as $namespace=>$prefix) {
  1855. $multiStatus->setAttribute('xmlns:' . $prefix,$namespace);
  1856. }
  1857. foreach($fileProperties as $entry) {
  1858. $href = $entry['href'];
  1859. unset($entry['href']);
  1860. if ($strip404s && isset($entry[404])) {
  1861. unset($entry[404]);
  1862. }
  1863. $response = new Property\Response($href,$entry);
  1864. $response->serialize($this,$multiStatus);
  1865. }
  1866. return $dom->saveXML();
  1867. }
  1868. /**
  1869. * This method parses a PropPatch request
  1870. *
  1871. * PropPatch changes the properties for a resource. This method
  1872. * returns a list of properties.
  1873. *
  1874. * The keys in the returned array contain the property name (e.g.: {DAV:}displayname,
  1875. * and the value contains the property value. If a property is to be removed the value
  1876. * will be null.
  1877. *
  1878. * @param string $body xml body
  1879. * @return array list of properties in need of updating or deletion
  1880. */
  1881. public function parsePropPatchRequest($body) {
  1882. //We'll need to change the DAV namespace declaration to something else in order to make it parsable
  1883. $dom = XMLUtil::loadDOMDocument($body);
  1884. $newProperties = [];
  1885. foreach($dom->firstChild->childNodes as $child) {
  1886. if ($child->nodeType !== XML_ELEMENT_NODE) continue;
  1887. $operation = XMLUtil::toClarkNotation($child);
  1888. if ($operation!=='{DAV:}set' && $operation!=='{DAV:}remove') continue;
  1889. $innerProperties = XMLUtil::parseProperties($child, $this->propertyMap);
  1890. foreach($innerProperties as $propertyName=>$propertyValue) {
  1891. if ($operation==='{DAV:}remove') {
  1892. $propertyValue = null;
  1893. }
  1894. $newProperties[$propertyName] = $propertyValue;
  1895. }
  1896. }
  1897. return $newProperties;
  1898. }
  1899. /**
  1900. * This method parses the PROPFIND request and returns its information
  1901. *
  1902. * This will either be a list of properties, or an empty array; in which case
  1903. * an {DAV:}allprop was requested.
  1904. *
  1905. * @param string $body
  1906. * @return array
  1907. */
  1908. public function parsePropFindRequest($body) {
  1909. // If the propfind body was empty, it means IE is requesting 'all' properties
  1910. if (!$body) return [];
  1911. $dom = XMLUtil::loadDOMDocument($body);
  1912. $elem = $dom->getElementsByTagNameNS('urn:DAV','propfind')->item(0);
  1913. if (is_null($elem)) throw new Exception\UnsupportedMediaType('We could not find a {DAV:}propfind element in the xml request body');
  1914. return array_keys(XMLUtil::parseProperties($elem));
  1915. }
  1916. // }}}
  1917. }