Blame view

sources/3rdparty/sabre/dav/lib/Sabre/DAV/Server.php 72.3 KB
03e52840d   Kload   Init
1
  <?php
6d9380f96   Cédric Dupont   Update sources OC...
2
3
  namespace Sabre\DAV;
  use Sabre\HTTP;
03e52840d   Kload   Init
4
5
6
  /**
   * Main DAV server class
   *
6d9380f96   Cédric Dupont   Update sources OC...
7
8
9
   * @copyright Copyright (C) 2007-2014 fruux GmbH (https://fruux.com/).
   * @author Evert Pot (http://evertpot.com/)
   * @license http://sabre.io/license/ Modified BSD License
03e52840d   Kload   Init
10
   */
6d9380f96   Cédric Dupont   Update sources OC...
11
  class Server {
03e52840d   Kload   Init
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  
      /**
       * Infinity is used for some request supporting the HTTP Depth header and indicates that the operation should traverse the entire tree
       */
      const DEPTH_INFINITY = -1;
  
      /**
       * Nodes that are files, should have this as the type property
       */
      const NODE_FILE = 1;
  
      /**
       * Nodes that are directories, should use this value as the type property
       */
      const NODE_DIRECTORY = 2;
  
      /**
       * XML namespace for all SabreDAV related elements
       */
      const NS_SABREDAV = 'http://sabredav.org/ns';
  
      /**
       * The tree object
       *
6d9380f96   Cédric Dupont   Update sources OC...
36
       * @var Sabre\DAV\Tree
03e52840d   Kload   Init
37
38
39
40
41
42
43
44
45
46
47
48
49
       */
      public $tree;
  
      /**
       * The base uri
       *
       * @var string
       */
      protected $baseUri = null;
  
      /**
       * httpResponse
       *
6d9380f96   Cédric Dupont   Update sources OC...
50
       * @var Sabre\HTTP\Response
03e52840d   Kload   Init
51
52
53
54
55
56
       */
      public $httpResponse;
  
      /**
       * httpRequest
       *
6d9380f96   Cédric Dupont   Update sources OC...
57
       * @var Sabre\HTTP\Request
03e52840d   Kload   Init
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
       */
      public $httpRequest;
  
      /**
       * The list of plugins
       *
       * @var array
       */
      protected $plugins = array();
  
      /**
       * This array contains a list of callbacks we should call when certain events are triggered
       *
       * @var array
       */
      protected $eventSubscriptions = array();
  
      /**
       * This is a default list of namespaces.
       *
       * If you are defining your own custom namespace, add it here to reduce
       * bandwidth and improve legibility of xml bodies.
       *
       * @var array
       */
      public $xmlNamespaces = array(
          'DAV:' => 'd',
          'http://sabredav.org/ns' => 's',
      );
  
      /**
       * The propertymap can be used to map properties from
       * requests to property classes.
       *
       * @var array
       */
      public $propertyMap = array(
6d9380f96   Cédric Dupont   Update sources OC...
95
          '{DAV:}resourcetype' => 'Sabre\\DAV\\Property\\ResourceType',
03e52840d   Kload   Init
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
      );
  
      public $protectedProperties = array(
          // RFC4918
          '{DAV:}getcontentlength',
          '{DAV:}getetag',
          '{DAV:}getlastmodified',
          '{DAV:}lockdiscovery',
          '{DAV:}supportedlock',
  
          // RFC4331
          '{DAV:}quota-available-bytes',
          '{DAV:}quota-used-bytes',
  
          // RFC3744
          '{DAV:}supported-privilege-set',
          '{DAV:}current-user-privilege-set',
          '{DAV:}acl',
          '{DAV:}acl-restrictions',
          '{DAV:}inherited-acl-set',
  
      );
  
      /**
       * This is a flag that allow or not showing file, line and code
       * of the exception in the returned XML
       *
       * @var bool
       */
      public $debugExceptions = false;
  
      /**
       * This property allows you to automatically add the 'resourcetype' value
       * based on a node's classname or interface.
       *
       * The preset ensures that {DAV:}collection is automaticlly added for nodes
6d9380f96   Cédric Dupont   Update sources OC...
132
       * implementing Sabre\DAV\ICollection.
03e52840d   Kload   Init
133
134
135
136
       *
       * @var array
       */
      public $resourceTypeMapping = array(
6d9380f96   Cédric Dupont   Update sources OC...
137
          'Sabre\\DAV\\ICollection' => '{DAV:}collection',
03e52840d   Kload   Init
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
      );
  
      /**
       * If this setting is turned off, SabreDAV's version number will be hidden
       * from various places.
       *
       * Some people feel this is a good security measure.
       *
       * @var bool
       */
      static public $exposeVersion = true;
  
      /**
       * Sets up the server
       *
6d9380f96   Cédric Dupont   Update sources OC...
153
154
155
       * If a Sabre\DAV\Tree object is passed as an argument, it will
       * use it as the directory tree. If a Sabre\DAV\INode is passed, it
       * will create a Sabre\DAV\ObjectTree and use the node as the root.
03e52840d   Kload   Init
156
       *
6d9380f96   Cédric Dupont   Update sources OC...
157
158
       * If nothing is passed, a Sabre\DAV\SimpleCollection is created in
       * a Sabre\DAV\ObjectTree.
03e52840d   Kload   Init
159
160
161
162
       *
       * If an array is passed, we automatically create a root node, and use
       * the nodes in the array as top-level children.
       *
6d9380f96   Cédric Dupont   Update sources OC...
163
       * @param Tree|INode|array|null $treeOrNode The tree object
03e52840d   Kload   Init
164
165
       */
      public function __construct($treeOrNode = null) {
6d9380f96   Cédric Dupont   Update sources OC...
166
          if ($treeOrNode instanceof Tree) {
03e52840d   Kload   Init
167
              $this->tree = $treeOrNode;
6d9380f96   Cédric Dupont   Update sources OC...
168
169
          } elseif ($treeOrNode instanceof INode) {
              $this->tree = new ObjectTree($treeOrNode);
03e52840d   Kload   Init
170
171
172
173
174
          } elseif (is_array($treeOrNode)) {
  
              // If it's an array, a list of nodes was passed, and we need to
              // create the root node.
              foreach($treeOrNode as $node) {
6d9380f96   Cédric Dupont   Update sources OC...
175
176
                  if (!($node instanceof INode)) {
                      throw new Exception('Invalid argument passed to constructor. If you\'re passing an array, all the values must implement Sabre\\DAV\\INode');
03e52840d   Kload   Init
177
178
                  }
              }
6d9380f96   Cédric Dupont   Update sources OC...
179
180
              $root = new SimpleCollection('root', $treeOrNode);
              $this->tree = new ObjectTree($root);
03e52840d   Kload   Init
181
182
  
          } elseif (is_null($treeOrNode)) {
6d9380f96   Cédric Dupont   Update sources OC...
183
184
              $root = new SimpleCollection('root');
              $this->tree = new ObjectTree($root);
03e52840d   Kload   Init
185
          } else {
6d9380f96   Cédric Dupont   Update sources OC...
186
              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');
03e52840d   Kload   Init
187
          }
6d9380f96   Cédric Dupont   Update sources OC...
188
189
          $this->httpResponse = new HTTP\Response();
          $this->httpRequest = new HTTP\Request();
03e52840d   Kload   Init
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
  
      }
  
      /**
       * Starts the DAV Server
       *
       * @return void
       */
      public function exec() {
  
          try {
  
              // If nginx (pre-1.2) is used as a proxy server, and SabreDAV as an
              // origin, we must make sure we send back HTTP/1.0 if this was
              // requested.
              // This is mainly because nginx doesn't support Chunked Transfer
              // Encoding, and this forces the webserver SabreDAV is running on,
              // to buffer entire responses to calculate Content-Length.
              $this->httpResponse->defaultHttpVersion = $this->httpRequest->getHTTPVersion();
  
              $this->invokeMethod($this->httpRequest->getMethod(), $this->getRequestUri());
  
          } catch (Exception $e) {
  
              try {
                  $this->broadcastEvent('exception', array($e));
              } catch (Exception $ignore) {
              }
6d9380f96   Cédric Dupont   Update sources OC...
218
              $DOM = new \DOMDocument('1.0','utf-8');
03e52840d   Kload   Init
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
              $DOM->formatOutput = true;
  
              $error = $DOM->createElementNS('DAV:','d:error');
              $error->setAttribute('xmlns:s',self::NS_SABREDAV);
              $DOM->appendChild($error);
  
              $h = function($v) {
  
                  return htmlspecialchars($v, ENT_NOQUOTES, 'UTF-8');
  
              };
  
              $error->appendChild($DOM->createElement('s:exception',$h(get_class($e))));
              $error->appendChild($DOM->createElement('s:message',$h($e->getMessage())));
              if ($this->debugExceptions) {
                  $error->appendChild($DOM->createElement('s:file',$h($e->getFile())));
                  $error->appendChild($DOM->createElement('s:line',$h($e->getLine())));
                  $error->appendChild($DOM->createElement('s:code',$h($e->getCode())));
                  $error->appendChild($DOM->createElement('s:stacktrace',$h($e->getTraceAsString())));
  
              }
              if (self::$exposeVersion) {
6d9380f96   Cédric Dupont   Update sources OC...
241
                  $error->appendChild($DOM->createElement('s:sabredav-version',$h(Version::VERSION)));
03e52840d   Kload   Init
242
              }
6d9380f96   Cédric Dupont   Update sources OC...
243
              if($e instanceof Exception) {
03e52840d   Kload   Init
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
  
                  $httpCode = $e->getHTTPCode();
                  $e->serialize($this,$error);
                  $headers = $e->getHTTPHeaders($this);
  
              } else {
  
                  $httpCode = 500;
                  $headers = array();
  
              }
              $headers['Content-Type'] = 'application/xml; charset=utf-8';
  
              $this->httpResponse->sendStatus($httpCode);
              $this->httpResponse->setHeaders($headers);
              $this->httpResponse->sendBody($DOM->saveXML());
  
          }
  
      }
  
      /**
       * Sets the base server uri
       *
       * @param string $uri
       * @return void
       */
      public function setBaseUri($uri) {
  
          // If the baseUri does not end with a slash, we must add it
          if ($uri[strlen($uri)-1]!=='/')
              $uri.='/';
  
          $this->baseUri = $uri;
  
      }
  
      /**
       * Returns the base responding uri
       *
       * @return string
       */
      public function getBaseUri() {
  
          if (is_null($this->baseUri)) $this->baseUri = $this->guessBaseUri();
          return $this->baseUri;
  
      }
  
      /**
       * This method attempts to detect the base uri.
       * Only the PATH_INFO variable is considered.
       *
       * If this variable is not set, the root (/) is assumed.
       *
       * @return string
       */
      public function guessBaseUri() {
  
          $pathInfo = $this->httpRequest->getRawServerValue('PATH_INFO');
          $uri = $this->httpRequest->getRawServerValue('REQUEST_URI');
  
          // If PATH_INFO is found, we can assume it's accurate.
          if (!empty($pathInfo)) {
  
              // We need to make sure we ignore the QUERY_STRING part
              if ($pos = strpos($uri,'?'))
                  $uri = substr($uri,0,$pos);
  
              // PATH_INFO is only set for urls, such as: /example.php/path
              // in that case PATH_INFO contains '/path'.
              // Note that REQUEST_URI is percent encoded, while PATH_INFO is
              // not, Therefore they are only comparable if we first decode
              // REQUEST_INFO as well.
6d9380f96   Cédric Dupont   Update sources OC...
318
              $decodedUri = URLUtil::decodePath($uri);
03e52840d   Kload   Init
319
320
321
322
323
324
  
              // A simple sanity check:
              if(substr($decodedUri,strlen($decodedUri)-strlen($pathInfo))===$pathInfo) {
                  $baseUri = substr($decodedUri,0,strlen($decodedUri)-strlen($pathInfo));
                  return rtrim($baseUri,'/') . '/';
              }
6d9380f96   Cédric Dupont   Update sources OC...
325
              throw new Exception('The REQUEST_URI ('. $uri . ') did not end with the contents of PATH_INFO (' . $pathInfo . '). This server might be misconfigured.');
03e52840d   Kload   Init
326
327
328
329
330
331
332
333
334
335
336
  
          }
  
          // The last fallback is that we're just going to assume the server root.
          return '/';
  
      }
  
      /**
       * Adds a plugin to the server
       *
6d9380f96   Cédric Dupont   Update sources OC...
337
       * For more information, console the documentation of Sabre\DAV\ServerPlugin
03e52840d   Kload   Init
338
       *
6d9380f96   Cédric Dupont   Update sources OC...
339
       * @param ServerPlugin $plugin
03e52840d   Kload   Init
340
341
       * @return void
       */
6d9380f96   Cédric Dupont   Update sources OC...
342
      public function addPlugin(ServerPlugin $plugin) {
03e52840d   Kload   Init
343
344
345
346
347
348
349
350
351
352
353
354
  
          $this->plugins[$plugin->getPluginName()] = $plugin;
          $plugin->initialize($this);
  
      }
  
      /**
       * Returns an initialized plugin by it's name.
       *
       * This function returns null if the plugin was not found.
       *
       * @param string $name
6d9380f96   Cédric Dupont   Update sources OC...
355
       * @return ServerPlugin
03e52840d   Kload   Init
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
       */
      public function getPlugin($name) {
  
          if (isset($this->plugins[$name]))
              return $this->plugins[$name];
  
          // This is a fallback and deprecated.
          foreach($this->plugins as $plugin) {
              if (get_class($plugin)===$name) return $plugin;
          }
  
          return null;
  
      }
  
      /**
       * Returns all plugins
       *
       * @return array
       */
      public function getPlugins() {
  
          return $this->plugins;
  
      }
  
  
      /**
       * Subscribe to an event.
       *
       * When the event is triggered, we'll call all the specified callbacks.
       * It is possible to control the order of the callbacks through the
       * priority argument.
       *
       * This is for example used to make sure that the authentication plugin
       * is triggered before anything else. If it's not needed to change this
       * number, it is recommended to ommit.
       *
       * @param string $event
       * @param callback $callback
       * @param int $priority
       * @return void
       */
      public function subscribeEvent($event, $callback, $priority = 100) {
  
          if (!isset($this->eventSubscriptions[$event])) {
              $this->eventSubscriptions[$event] = array();
          }
          while(isset($this->eventSubscriptions[$event][$priority])) $priority++;
          $this->eventSubscriptions[$event][$priority] = $callback;
          ksort($this->eventSubscriptions[$event]);
  
      }
  
      /**
       * Broadcasts an event
       *
       * This method will call all subscribers. If one of the subscribers returns false, the process stops.
       *
       * The arguments parameter will be sent to all subscribers
       *
       * @param string $eventName
       * @param array $arguments
       * @return bool
       */
      public function broadcastEvent($eventName,$arguments = array()) {
  
          if (isset($this->eventSubscriptions[$eventName])) {
  
              foreach($this->eventSubscriptions[$eventName] as $subscriber) {
  
                  $result = call_user_func_array($subscriber,$arguments);
                  if ($result===false) return false;
  
              }
  
          }
  
          return true;
  
      }
  
      /**
       * Handles a http request, and execute a method based on its name
       *
       * @param string $method
       * @param string $uri
       * @return void
       */
      public function invokeMethod($method, $uri) {
  
          $method = strtoupper($method);
  
          if (!$this->broadcastEvent('beforeMethod',array($method, $uri))) return;
  
          // Make sure this is a HTTP method we support
          $internalMethods = array(
              'OPTIONS',
              'GET',
              'HEAD',
              'DELETE',
              'PROPFIND',
              'MKCOL',
              'PUT',
              'PROPPATCH',
              'COPY',
              'MOVE',
              'REPORT'
          );
  
          if (in_array($method,$internalMethods)) {
  
              call_user_func(array($this,'http' . $method), $uri);
  
          } else {
  
              if ($this->broadcastEvent('unknownMethod',array($method, $uri))) {
                  // Unsupported method
6d9380f96   Cédric Dupont   Update sources OC...
474
                  throw new Exception\NotImplemented('There was no handler found for this "' . $method . '" method');
03e52840d   Kload   Init
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
              }
  
          }
  
      }
  
      // {{{ HTTP Method implementations
  
      /**
       * HTTP OPTIONS
       *
       * @param string $uri
       * @return void
       */
      protected function httpOptions($uri) {
  
          $methods = $this->getAllowedMethods($uri);
  
          $this->httpResponse->setHeader('Allow',strtoupper(implode(', ',$methods)));
          $features = array('1','3', 'extended-mkcol');
  
          foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures());
  
          $this->httpResponse->setHeader('DAV',implode(', ',$features));
          $this->httpResponse->setHeader('MS-Author-Via','DAV');
          $this->httpResponse->setHeader('Accept-Ranges','bytes');
          if (self::$exposeVersion) {
6d9380f96   Cédric Dupont   Update sources OC...
502
              $this->httpResponse->setHeader('X-Sabre-Version',Version::VERSION);
03e52840d   Kload   Init
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
          }
          $this->httpResponse->setHeader('Content-Length',0);
          $this->httpResponse->sendStatus(200);
  
      }
  
      /**
       * HTTP GET
       *
       * This method simply fetches the contents of a uri, like normal
       *
       * @param string $uri
       * @return bool
       */
      protected function httpGet($uri) {
  
          $node = $this->tree->getNodeForPath($uri,0);
  
          if (!$this->checkPreconditions(true)) return false;
6d9380f96   Cédric Dupont   Update sources OC...
522
          if (!$node instanceof IFile) throw new Exception\NotImplemented('GET is only implemented on File objects');
03e52840d   Kload   Init
523

03e52840d   Kload   Init
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
          $body = $node->get();
  
          // Converting string into stream, if needed.
          if (is_string($body)) {
              $stream = fopen('php://temp','r+');
              fwrite($stream,$body);
              rewind($stream);
              $body = $stream;
          }
  
          /*
           * TODO: getetag, getlastmodified, getsize should also be used using
           * this method
           */
          $httpHeaders = $this->getHTTPHeaders($uri);
  
          /* ContentType needs to get a default, because many webservers will otherwise
           * default to text/html, and we don't want this for security reasons.
           */
          if (!isset($httpHeaders['Content-Type'])) {
              $httpHeaders['Content-Type'] = 'application/octet-stream';
          }
  
  
          if (isset($httpHeaders['Content-Length'])) {
  
              $nodeSize = $httpHeaders['Content-Length'];
  
              // Need to unset Content-Length, because we'll handle that during figuring out the range
              unset($httpHeaders['Content-Length']);
  
          } else {
              $nodeSize = null;
          }
  
          $this->httpResponse->setHeaders($httpHeaders);
  
          $range = $this->getHTTPRange();
          $ifRange = $this->httpRequest->getHeader('If-Range');
          $ignoreRangeHeader = false;
  
          // If ifRange is set, and range is specified, we first need to check
          // the precondition.
          if ($nodeSize && $range && $ifRange) {
  
              // if IfRange is parsable as a date we'll treat it as a DateTime
              // otherwise, we must treat it as an etag.
              try {
6d9380f96   Cédric Dupont   Update sources OC...
572
                  $ifRangeDate = new \DateTime($ifRange);
03e52840d   Kload   Init
573
574
575
576
577
  
                  // It's a date. We must check if the entity is modified since
                  // the specified date.
                  if (!isset($httpHeaders['Last-Modified'])) $ignoreRangeHeader = true;
                  else {
6d9380f96   Cédric Dupont   Update sources OC...
578
                      $modified = new \DateTime($httpHeaders['Last-Modified']);
03e52840d   Kload   Init
579
580
                      if($modified > $ifRangeDate) $ignoreRangeHeader = true;
                  }
6d9380f96   Cédric Dupont   Update sources OC...
581
              } catch (\Exception $e) {
03e52840d   Kload   Init
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
  
                  // It's an entity. We can do a simple comparison.
                  if (!isset($httpHeaders['ETag'])) $ignoreRangeHeader = true;
                  elseif ($httpHeaders['ETag']!==$ifRange) $ignoreRangeHeader = true;
              }
          }
  
          // We're only going to support HTTP ranges if the backend provided a filesize
          if (!$ignoreRangeHeader && $nodeSize && $range) {
  
              // Determining the exact byte offsets
              if (!is_null($range[0])) {
  
                  $start = $range[0];
                  $end = $range[1]?$range[1]:$nodeSize-1;
                  if($start >= $nodeSize)
6d9380f96   Cédric Dupont   Update sources OC...
598
                      throw new Exception\RequestedRangeNotSatisfiable('The start offset (' . $range[0] . ') exceeded the size of the entity (' . $nodeSize . ')');
03e52840d   Kload   Init
599

6d9380f96   Cédric Dupont   Update sources OC...
600
                  if($end < $start) throw new Exception\RequestedRangeNotSatisfiable('The end offset (' . $range[1] . ') is lower than the start offset (' . $range[0] . ')');
03e52840d   Kload   Init
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
                  if($end >= $nodeSize) $end = $nodeSize-1;
  
              } else {
  
                  $start = $nodeSize-$range[1];
                  $end  = $nodeSize-1;
  
                  if ($start<0) $start = 0;
  
              }
  
              // New read/write stream
              $newStream = fopen('php://temp','r+');
  
              // stream_copy_to_stream() has a bug/feature: the `whence` argument
              // is interpreted as SEEK_SET (count from absolute offset 0), while
              // for a stream it should be SEEK_CUR (count from current offset).
              // If a stream is nonseekable, the function fails. So we *emulate*
              // the correct behaviour with fseek():
              if ($start > 0) {
                  if (($curOffs = ftell($body)) === false) $curOffs = 0;
                  fseek($body, $start - $curOffs, SEEK_CUR);
              }
              stream_copy_to_stream($body, $newStream, $end-$start+1);
              rewind($newStream);
  
              $this->httpResponse->setHeader('Content-Length', $end-$start+1);
              $this->httpResponse->setHeader('Content-Range','bytes ' . $start . '-' . $end . '/' . $nodeSize);
              $this->httpResponse->sendStatus(206);
              $this->httpResponse->sendBody($newStream);
  
  
          } else {
  
              if ($nodeSize) $this->httpResponse->setHeader('Content-Length',$nodeSize);
              $this->httpResponse->sendStatus(200);
              $this->httpResponse->sendBody($body);
  
          }
  
      }
  
      /**
       * HTTP HEAD
       *
       * This method is normally used to take a peak at a url, and only get the HTTP response headers, without the body
       * 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
       *
       * @param string $uri
       * @return void
       */
      protected function httpHead($uri) {
  
          $node = $this->tree->getNodeForPath($uri);
          /* This information is only collection for File objects.
           * Ideally we want to throw 405 Method Not Allowed for every
           * non-file, but MS Office does not like this
           */
6d9380f96   Cédric Dupont   Update sources OC...
659
          if ($node instanceof IFile) {
03e52840d   Kload   Init
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
              $headers = $this->getHTTPHeaders($this->getRequestUri());
              if (!isset($headers['Content-Type'])) {
                  $headers['Content-Type'] = 'application/octet-stream';
              }
              $this->httpResponse->setHeaders($headers);
          }
          $this->httpResponse->sendStatus(200);
  
      }
  
      /**
       * HTTP Delete
       *
       * The HTTP delete method, deletes a given uri
       *
       * @param string $uri
       * @return void
       */
      protected function httpDelete($uri) {
6d9380f96   Cédric Dupont   Update sources OC...
679
680
          // Checking If-None-Match and related headers.
          if (!$this->checkPreconditions()) return;
03e52840d   Kload   Init
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
          if (!$this->broadcastEvent('beforeUnbind',array($uri))) return;
          $this->tree->delete($uri);
          $this->broadcastEvent('afterUnbind',array($uri));
  
          $this->httpResponse->sendStatus(204);
          $this->httpResponse->setHeader('Content-Length','0');
  
      }
  
  
      /**
       * WebDAV PROPFIND
       *
       * This WebDAV method requests information about an uri resource, or a list of resources
       * If a client wants to receive the properties for a single resource it will add an HTTP Depth: header with a 0 value
       * If the value is 1, it means that it also expects a list of sub-resources (e.g.: files in a directory)
       *
       * The request body contains an XML data structure that has a list of properties the client understands
       * The response body is also an xml document, containing information about every uri resource and the requested properties
       *
       * It has to return a HTTP 207 Multi-status status code
       *
       * @param string $uri
       * @return void
       */
      protected function httpPropfind($uri) {
03e52840d   Kload   Init
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
          $requestedProperties = $this->parsePropFindRequest($this->httpRequest->getBody(true));
  
          $depth = $this->getHTTPDepth(1);
          // The only two options for the depth of a propfind is 0 or 1
          if ($depth!=0) $depth = 1;
  
          $newProperties = $this->getPropertiesForPath($uri,$requestedProperties,$depth);
  
          // This is a multi-status response
          $this->httpResponse->sendStatus(207);
          $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
          $this->httpResponse->setHeader('Vary','Brief,Prefer');
  
          // Normally this header is only needed for OPTIONS responses, however..
          // iCal seems to also depend on these being set for PROPFIND. Since
          // this is not harmful, we'll add it.
          $features = array('1','3', 'extended-mkcol');
          foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures());
          $this->httpResponse->setHeader('DAV',implode(', ',$features));
  
          $prefer = $this->getHTTPPrefer();
          $minimal = $prefer['return-minimal'];
  
          $data = $this->generateMultiStatus($newProperties, $minimal);
          $this->httpResponse->sendBody($data);
  
      }
  
      /**
       * WebDAV PROPPATCH
       *
       * This method is called to update properties on a Node. The request is an XML body with all the mutations.
       * In this XML body it is specified which properties should be set/updated and/or deleted
       *
       * @param string $uri
       * @return void
       */
      protected function httpPropPatch($uri) {
  
          $newProperties = $this->parsePropPatchRequest($this->httpRequest->getBody(true));
  
          $result = $this->updateProperties($uri, $newProperties);
  
          $prefer = $this->getHTTPPrefer();
          $this->httpResponse->setHeader('Vary','Brief,Prefer');
  
          if ($prefer['return-minimal']) {
  
              // If return-minimal is specified, we only have to check if the
              // request was succesful, and don't need to return the
              // multi-status.
              $ok = true;
              foreach($result as $code=>$prop) {
                  if ((int)$code > 299) {
                      $ok = false;
                  }
              }
  
              if ($ok) {
  
                  $this->httpResponse->sendStatus(204);
                  return;
  
              }
  
          }
  
          $this->httpResponse->sendStatus(207);
          $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
  
          $this->httpResponse->sendBody(
              $this->generateMultiStatus(array($result))
          );
  
      }
  
      /**
       * HTTP PUT method
       *
       * This HTTP method updates a file, or creates a new one.
       *
       * 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
       *
       * @param string $uri
       * @return bool
       */
      protected function httpPut($uri) {
  
          $body = $this->httpRequest->getBody();
  
          // Intercepting Content-Range
          if ($this->httpRequest->getHeader('Content-Range')) {
              /**
              Content-Range is dangerous for PUT requests:  PUT per definition
              stores a full resource.  draft-ietf-httpbis-p2-semantics-15 says
              in section 7.6:
                An origin server SHOULD reject any PUT request that contains a
                Content-Range header field, since it might be misinterpreted as
                partial content (or might be partial content that is being mistakenly
                PUT as a full representation).  Partial content updates are possible
                by targeting a separately identified resource with state that
                overlaps a portion of the larger resource, or by using a different
                method that has been specifically defined for partial updates (for
                example, the PATCH method defined in [RFC5789]).
              This clarifies RFC2616 section 9.6:
                The recipient of the entity MUST NOT ignore any Content-*
                (e.g. Content-Range) headers that it does not understand or implement
                and MUST return a 501 (Not Implemented) response in such cases.
              OTOH is a PUT request with a Content-Range currently the only way to
              continue an aborted upload request and is supported by curl, mod_dav,
              Tomcat and others.  Since some clients do use this feature which results
              in unexpected behaviour (cf PEAR::HTTP_WebDAV_Client 1.0.1), we reject
              all PUT requests with a Content-Range for now.
              */
6d9380f96   Cédric Dupont   Update sources OC...
821
              throw new Exception\NotImplemented('PUT with Content-Range is not allowed.');
03e52840d   Kload   Init
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
          }
  
          // Intercepting the Finder problem
          if (($expected = $this->httpRequest->getHeader('X-Expected-Entity-Length')) && $expected > 0) {
  
              /**
              Many webservers will not cooperate well with Finder PUT requests,
              because it uses 'Chunked' transfer encoding for the request body.
  
              The symptom of this problem is that Finder sends files to the
              server, but they arrive as 0-length files in PHP.
  
              If we don't do anything, the user might think they are uploading
              files successfully, but they end up empty on the server. Instead,
              we throw back an error if we detect this.
  
              The reason Finder uses Chunked, is because it thinks the files
              might change as it's being uploaded, and therefore the
              Content-Length can vary.
  
              Instead it sends the X-Expected-Entity-Length header with the size
              of the file at the very start of the request. If this header is set,
              but we don't get a request body we will fail the request to
              protect the end-user.
              */
  
              // Only reading first byte
              $firstByte = fread($body,1);
              if (strlen($firstByte)!==1) {
6d9380f96   Cédric Dupont   Update sources OC...
851
                  throw new Exception\Forbidden('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.');
03e52840d   Kload   Init
852
853
854
855
856
857
858
859
860
861
862
863
864
              }
  
              // The body needs to stay intact, so we copy everything to a
              // temporary stream.
  
              $newBody = fopen('php://temp','r+');
              fwrite($newBody,$firstByte);
              stream_copy_to_stream($body, $newBody);
              rewind($newBody);
  
              $body = $newBody;
  
          }
6d9380f96   Cédric Dupont   Update sources OC...
865
866
          // Checking If-None-Match and related headers.
          if (!$this->checkPreconditions()) return;
03e52840d   Kload   Init
867
868
869
          if ($this->tree->nodeExists($uri)) {
  
              $node = $this->tree->getNodeForPath($uri);
03e52840d   Kload   Init
870
              // If the node is a collection, we'll deny it
6d9380f96   Cédric Dupont   Update sources OC...
871
              if (!($node instanceof IFile)) throw new Exception\Conflict('PUT is not allowed on non-files.');
03e52840d   Kload   Init
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
              if (!$this->broadcastEvent('beforeWriteContent',array($uri, $node, &$body))) return false;
  
              $etag = $node->put($body);
  
              $this->broadcastEvent('afterWriteContent',array($uri, $node));
  
              $this->httpResponse->setHeader('Content-Length','0');
              if ($etag) $this->httpResponse->setHeader('ETag',$etag);
              $this->httpResponse->sendStatus(204);
  
          } else {
  
              $etag = null;
              // If we got here, the resource didn't exist yet.
              if (!$this->createFile($this->getRequestUri(),$body,$etag)) {
                  // For one reason or another the file was not created.
                  return;
              }
  
              $this->httpResponse->setHeader('Content-Length','0');
              if ($etag) $this->httpResponse->setHeader('ETag', $etag);
              $this->httpResponse->sendStatus(201);
  
          }
  
      }
  
  
      /**
       * WebDAV MKCOL
       *
       * The MKCOL method is used to create a new collection (directory) on the server
       *
       * @param string $uri
       * @return void
       */
      protected function httpMkcol($uri) {
  
          $requestBody = $this->httpRequest->getBody(true);
  
          if ($requestBody) {
  
              $contentType = $this->httpRequest->getHeader('Content-Type');
              if (strpos($contentType,'application/xml')!==0 && strpos($contentType,'text/xml')!==0) {
  
                  // We must throw 415 for unsupported mkcol bodies
6d9380f96   Cédric Dupont   Update sources OC...
918
                  throw new Exception\UnsupportedMediaType('The request body for the MKCOL request must have an xml Content-Type');
03e52840d   Kload   Init
919
920
  
              }
6d9380f96   Cédric Dupont   Update sources OC...
921
922
              $dom = XMLUtil::loadDOMDocument($requestBody);
              if (XMLUtil::toClarkNotation($dom->firstChild)!=='{DAV:}mkcol') {
03e52840d   Kload   Init
923
924
  
                  // We must throw 415 for unsupported mkcol bodies
6d9380f96   Cédric Dupont   Update sources OC...
925
                  throw new Exception\UnsupportedMediaType('The request body for the MKCOL request must be a {DAV:}mkcol request construct.');
03e52840d   Kload   Init
926
927
928
929
930
  
              }
  
              $properties = array();
              foreach($dom->firstChild->childNodes as $childNode) {
6d9380f96   Cédric Dupont   Update sources OC...
931
932
                  if (XMLUtil::toClarkNotation($childNode)!=='{DAV:}set') continue;
                  $properties = array_merge($properties, XMLUtil::parseProperties($childNode, $this->propertyMap));
03e52840d   Kload   Init
933
934
935
  
              }
              if (!isset($properties['{DAV:}resourcetype']))
6d9380f96   Cédric Dupont   Update sources OC...
936
                  throw new Exception\BadRequest('The mkcol request must include a {DAV:}resourcetype property');
03e52840d   Kload   Init
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
  
              $resourceType = $properties['{DAV:}resourcetype']->getValue();
              unset($properties['{DAV:}resourcetype']);
  
          } else {
  
              $properties = array();
              $resourceType = array('{DAV:}collection');
  
          }
  
          $result = $this->createCollection($uri, $resourceType, $properties);
  
          if (is_array($result)) {
              $this->httpResponse->sendStatus(207);
              $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8');
  
              $this->httpResponse->sendBody(
                  $this->generateMultiStatus(array($result))
              );
  
          } else {
              $this->httpResponse->setHeader('Content-Length','0');
              $this->httpResponse->sendStatus(201);
          }
  
      }
  
      /**
       * WebDAV HTTP MOVE method
       *
       * This method moves one uri to a different uri. A lot of the actual request processing is done in getCopyMoveInfo
       *
       * @param string $uri
       * @return bool
       */
      protected function httpMove($uri) {
  
          $moveInfo = $this->getCopyAndMoveInfo();
  
          // If the destination is part of the source tree, we must fail
          if ($moveInfo['destination']==$uri)
6d9380f96   Cédric Dupont   Update sources OC...
979
              throw new Exception\Forbidden('Source and destination uri are identical.');
03e52840d   Kload   Init
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
  
          if ($moveInfo['destinationExists']) {
  
              if (!$this->broadcastEvent('beforeUnbind',array($moveInfo['destination']))) return false;
              $this->tree->delete($moveInfo['destination']);
              $this->broadcastEvent('afterUnbind',array($moveInfo['destination']));
  
          }
  
          if (!$this->broadcastEvent('beforeUnbind',array($uri))) return false;
          if (!$this->broadcastEvent('beforeBind',array($moveInfo['destination']))) return false;
          $this->tree->move($uri,$moveInfo['destination']);
          $this->broadcastEvent('afterUnbind',array($uri));
          $this->broadcastEvent('afterBind',array($moveInfo['destination']));
  
          // If a resource was overwritten we should send a 204, otherwise a 201
          $this->httpResponse->setHeader('Content-Length','0');
          $this->httpResponse->sendStatus($moveInfo['destinationExists']?204:201);
  
      }
  
      /**
       * WebDAV HTTP COPY method
       *
       * This method copies one uri to a different uri, and works much like the MOVE request
       * A lot of the actual request processing is done in getCopyMoveInfo
       *
       * @param string $uri
       * @return bool
       */
      protected function httpCopy($uri) {
  
          $copyInfo = $this->getCopyAndMoveInfo();
          // If the destination is part of the source tree, we must fail
          if ($copyInfo['destination']==$uri)
6d9380f96   Cédric Dupont   Update sources OC...
1015
              throw new Exception\Forbidden('Source and destination uri are identical.');
03e52840d   Kload   Init
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
  
          if ($copyInfo['destinationExists']) {
              if (!$this->broadcastEvent('beforeUnbind',array($copyInfo['destination']))) return false;
              $this->tree->delete($copyInfo['destination']);
  
          }
          if (!$this->broadcastEvent('beforeBind',array($copyInfo['destination']))) return false;
          $this->tree->copy($uri,$copyInfo['destination']);
          $this->broadcastEvent('afterBind',array($copyInfo['destination']));
  
          // If a resource was overwritten we should send a 204, otherwise a 201
          $this->httpResponse->setHeader('Content-Length','0');
          $this->httpResponse->sendStatus($copyInfo['destinationExists']?204:201);
  
      }
  
  
  
      /**
       * HTTP REPORT method implementation
       *
       * Although the REPORT method is not part of the standard WebDAV spec (it's from rfc3253)
       * It's used in a lot of extensions, so it made sense to implement it into the core.
       *
       * @param string $uri
       * @return void
       */
      protected function httpReport($uri) {
  
          $body = $this->httpRequest->getBody(true);
6d9380f96   Cédric Dupont   Update sources OC...
1046
          $dom = XMLUtil::loadDOMDocument($body);
03e52840d   Kload   Init
1047

6d9380f96   Cédric Dupont   Update sources OC...
1048
          $reportName = XMLUtil::toClarkNotation($dom->firstChild);
03e52840d   Kload   Init
1049
1050
1051
1052
  
          if ($this->broadcastEvent('report',array($reportName,$dom, $uri))) {
  
              // If broadcastEvent returned true, it means the report was not supported
6d9380f96   Cédric Dupont   Update sources OC...
1053
              throw new Exception\ReportNotSupported();
03e52840d   Kload   Init
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
  
          }
  
      }
  
      // }}}
      // {{{ HTTP/WebDAV protocol helpers
  
      /**
       * Returns an array with all the supported HTTP methods for a specific uri.
       *
       * @param string $uri
       * @return array
       */
      public function getAllowedMethods($uri) {
  
          $methods = array(
              'OPTIONS',
              'GET',
              'HEAD',
              'DELETE',
              'PROPFIND',
              'PUT',
              'PROPPATCH',
              'COPY',
              'MOVE',
              'REPORT'
          );
  
          // The MKCOL is only allowed on an unmapped uri
          try {
              $this->tree->getNodeForPath($uri);
6d9380f96   Cédric Dupont   Update sources OC...
1086
          } catch (Exception\NotFound $e) {
03e52840d   Kload   Init
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
              $methods[] = 'MKCOL';
          }
  
          // We're also checking if any of the plugins register any new methods
          foreach($this->plugins as $plugin) $methods = array_merge($methods, $plugin->getHTTPMethods($uri));
          array_unique($methods);
  
          return $methods;
  
      }
  
      /**
       * Gets the uri for the request, keeping the base uri into consideration
       *
       * @return string
       */
      public function getRequestUri() {
  
          return $this->calculateUri($this->httpRequest->getUri());
  
      }
  
      /**
       * Calculates the uri for a request, making sure that the base uri is stripped out
       *
       * @param string $uri
6d9380f96   Cédric Dupont   Update sources OC...
1113
       * @throws Exception\Forbidden A permission denied exception is thrown whenever there was an attempt to supply a uri outside of the base uri
03e52840d   Kload   Init
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
       * @return string
       */
      public function calculateUri($uri) {
  
          if ($uri[0]!='/' && strpos($uri,'://')) {
  
              $uri = parse_url($uri,PHP_URL_PATH);
  
          }
  
          $uri = str_replace('//','/',$uri);
  
          if (strpos($uri,$this->getBaseUri())===0) {
6d9380f96   Cédric Dupont   Update sources OC...
1127
              return trim(URLUtil::decodePath(substr($uri,strlen($this->getBaseUri()))),'/');
03e52840d   Kload   Init
1128
1129
1130
1131
1132
1133
1134
1135
  
          // A special case, if the baseUri was accessed without a trailing
          // slash, we'll accept it as well.
          } elseif ($uri.'/' === $this->getBaseUri()) {
  
              return '';
  
          } else {
6d9380f96   Cédric Dupont   Update sources OC...
1136
              throw new Exception\Forbidden('Requested uri (' . $uri . ') is out of base uri (' . $this->getBaseUri() . ')');
03e52840d   Kload   Init
1137
1138
1139
1140
1141
1142
1143
1144
  
          }
  
      }
  
      /**
       * Returns the HTTP depth header
       *
6d9380f96   Cédric Dupont   Update sources OC...
1145
       * 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
03e52840d   Kload   Init
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
       * It is possible to supply a default depth value, which is used when the depth header has invalid content, or is completely non-existent
       *
       * @param mixed $default
       * @return int
       */
      public function getHTTPDepth($default = self::DEPTH_INFINITY) {
  
          // If its not set, we'll grab the default
          $depth = $this->httpRequest->getHeader('Depth');
  
          if (is_null($depth)) return $default;
  
          if ($depth == 'infinity') return self::DEPTH_INFINITY;
  
  
          // If its an unknown value. we'll grab the default
          if (!ctype_digit($depth)) return $default;
  
          return (int)$depth;
  
      }
  
      /**
       * Returns the HTTP range header
       *
       * This method returns null if there is no well-formed HTTP range request
       * header or array($start, $end).
       *
       * The first number is the offset of the first byte in the range.
       * The second number is the offset of the last byte in the range.
       *
       * If the second offset is null, it should be treated as the offset of the last byte of the entity
       * If the first offset is null, the second offset should be used to retrieve the last x bytes of the entity
       *
       * @return array|null
       */
      public function getHTTPRange() {
  
          $range = $this->httpRequest->getHeader('range');
          if (is_null($range)) return null;
  
          // Matching "Range: bytes=1234-5678: both numbers are optional
  
          if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i',$range,$matches)) return null;
  
          if ($matches[1]==='' && $matches[2]==='') return null;
  
          return array(
              $matches[1]!==''?$matches[1]:null,
              $matches[2]!==''?$matches[2]:null,
          );
  
      }
  
      /**
       * Returns the HTTP Prefer header information.
       *
       * The prefer header is defined in:
       * http://tools.ietf.org/html/draft-snell-http-prefer-14
       *
       * This method will return an array with options.
       *
       * Currently, the following options may be returned:
       *   array(
       *      'return-asynch'         => true,
       *      'return-minimal'        => true,
       *      'return-representation' => true,
       *      'wait'                  => 30,
       *      'strict'                => true,
       *      'lenient'               => true,
       *   )
       *
       * This method also supports the Brief header, and will also return
       * 'return-minimal' if the brief header was set to 't'.
       *
       * For the boolean options, false will be returned if the headers are not
       * specified. For the integer options it will be 'null'.
       *
       * @return array
       */
      public function getHTTPPrefer() {
  
          $result = array(
              'return-asynch'         => false,
              'return-minimal'        => false,
              'return-representation' => false,
              'wait'                  => null,
              'strict'                => false,
              'lenient'               => false,
          );
  
          if ($prefer = $this->httpRequest->getHeader('Prefer')) {
  
              $parameters = array_map('trim',
                  explode(',', $prefer)
              );
  
              foreach($parameters as $parameter) {
  
                  // Right now our regex only supports the tokens actually
                  // specified in the draft. We may need to expand this if new
                  // tokens get registered.
                  if(!preg_match('/^(?P<token>[a-z0-9-]+)(?:=(?P<value>[0-9]+))?$/', $parameter, $matches)) {
                      continue;
                  }
  
                  switch($matches['token']) {
  
                      case 'return-asynch' :
                      case 'return-minimal' :
                      case 'return-representation' :
                      case 'strict' :
                      case 'lenient' :
                          $result[$matches['token']] = true;
                          break;
                      case 'wait' :
                          $result[$matches['token']] = $matches['value'];
                          break;
  
                  }
  
              }
  
          }
  
          if ($this->httpRequest->getHeader('Brief')=='t') {
              $result['return-minimal'] = true;
          }
  
          return $result;
  
      }
  
  
      /**
       * Returns information about Copy and Move requests
       *
       * This function is created to help getting information about the source and the destination for the
       * WebDAV MOVE and COPY HTTP request. It also validates a lot of information and throws proper exceptions
       *
       * The returned value is an array with the following keys:
       *   * destination - Destination path
       *   * destinationExists - Whether or not the destination is an existing url (and should therefore be overwritten)
       *
       * @return array
       */
      public function getCopyAndMoveInfo() {
  
          // Collecting the relevant HTTP headers
6d9380f96   Cédric Dupont   Update sources OC...
1295
          if (!$this->httpRequest->getHeader('Destination')) throw new Exception\BadRequest('The destination header was not supplied');
03e52840d   Kload   Init
1296
1297
1298
1299
1300
1301
          $destination = $this->calculateUri($this->httpRequest->getHeader('Destination'));
          $overwrite = $this->httpRequest->getHeader('Overwrite');
          if (!$overwrite) $overwrite = 'T';
          if (strtoupper($overwrite)=='T') $overwrite = true;
          elseif (strtoupper($overwrite)=='F') $overwrite = false;
          // We need to throw a bad request exception, if the header was invalid
6d9380f96   Cédric Dupont   Update sources OC...
1302
          else throw new Exception\BadRequest('The HTTP Overwrite header should be either T or F');
03e52840d   Kload   Init
1303

6d9380f96   Cédric Dupont   Update sources OC...
1304
          list($destinationDir) = URLUtil::splitPath($destination);
03e52840d   Kload   Init
1305
1306
1307
  
          try {
              $destinationParent = $this->tree->getNodeForPath($destinationDir);
6d9380f96   Cédric Dupont   Update sources OC...
1308
1309
              if (!($destinationParent instanceof ICollection)) throw new Exception\UnsupportedMediaType('The destination node is not a collection');
          } catch (Exception\NotFound $e) {
03e52840d   Kload   Init
1310
1311
  
              // If the destination parent node is not found, we throw a 409
6d9380f96   Cédric Dupont   Update sources OC...
1312
              throw new Exception\Conflict('The destination node is not found');
03e52840d   Kload   Init
1313
1314
1315
1316
1317
1318
1319
1320
          }
  
          try {
  
              $destinationNode = $this->tree->getNodeForPath($destination);
  
              // If this succeeded, it means the destination already exists
              // we'll need to throw precondition failed in case overwrite is false
6d9380f96   Cédric Dupont   Update sources OC...
1321
              if (!$overwrite) throw new Exception\PreconditionFailed('The destination node already exists, and the overwrite header is set to false','Overwrite');
03e52840d   Kload   Init
1322

6d9380f96   Cédric Dupont   Update sources OC...
1323
          } catch (Exception\NotFound $e) {
03e52840d   Kload   Init
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
  
              // Destination didn't exist, we're all good
              $destinationNode = false;
  
  
  
          }
  
          // These are the three relevant properties we need to return
          return array(
              'destination'       => $destination,
              'destinationExists' => $destinationNode==true,
              'destinationNode'   => $destinationNode,
          );
  
      }
  
      /**
       * Returns a list of properties for a path
       *
       * This is a simplified version getPropertiesForPath.
       * if you aren't interested in status codes, but you just
       * want to have a flat list of properties. Use this method.
       *
       * @param string $path
       * @param array $propertyNames
       */
      public function getProperties($path, $propertyNames) {
  
          $result = $this->getPropertiesForPath($path,$propertyNames,0);
          return $result[0][200];
  
      }
  
      /**
       * A kid-friendly way to fetch properties for a node's children.
       *
       * The returned array will be indexed by the path of the of child node.
       * Only properties that are actually found will be returned.
       *
       * The parent node will not be returned.
       *
       * @param string $path
       * @param array $propertyNames
       * @return array
       */
      public function getPropertiesForChildren($path, $propertyNames) {
  
          $result = array();
          foreach($this->getPropertiesForPath($path,$propertyNames,1) as $k=>$row) {
  
              // Skipping the parent path
              if ($k === 0) continue;
  
              $result[$row['href']] = $row[200];
  
          }
          return $result;
  
      }
  
      /**
       * Returns a list of HTTP headers for a particular resource
       *
       * The generated http headers are based on properties provided by the
       * resource. The method basically provides a simple mapping between
       * DAV property and HTTP header.
       *
       * The headers are intended to be used for HEAD and GET requests.
       *
       * @param string $path
       * @return array
       */
      public function getHTTPHeaders($path) {
  
          $propertyMap = array(
              '{DAV:}getcontenttype'   => 'Content-Type',
              '{DAV:}getcontentlength' => 'Content-Length',
              '{DAV:}getlastmodified'  => 'Last-Modified',
              '{DAV:}getetag'          => 'ETag',
          );
  
          $properties = $this->getProperties($path,array_keys($propertyMap));
  
          $headers = array();
          foreach($propertyMap as $property=>$header) {
              if (!isset($properties[$property])) continue;
  
              if (is_scalar($properties[$property])) {
                  $headers[$header] = $properties[$property];
  
              // GetLastModified gets special cased
6d9380f96   Cédric Dupont   Update sources OC...
1416
1417
              } elseif ($properties[$property] instanceof Property\GetLastModified) {
                  $headers[$header] = HTTP\Util::toHTTPDate($properties[$property]->getTime());
03e52840d   Kload   Init
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
              }
  
          }
  
          return $headers;
  
      }
  
      /**
       * Returns a list of properties for a given path
       *
       * The path that should be supplied should have the baseUrl stripped out
       * The list of properties should be supplied in Clark notation. If the list is empty
       * 'allprops' is assumed.
       *
       * If a depth of 1 is requested child elements will also be returned.
       *
       * @param string $path
       * @param array $propertyNames
       * @param int $depth
       * @return array
       */
      public function getPropertiesForPath($path, $propertyNames = array(), $depth = 0) {
  
          if ($depth!=0) $depth = 1;
  
          $path = rtrim($path,'/');
6d9380f96   Cédric Dupont   Update sources OC...
1445
1446
1447
1448
1449
1450
          // This event allows people to intercept these requests early on in the
          // process.
          //
          // We're not doing anything with the result, but this can be helpful to
          // pre-fetch certain expensive live properties.
          $this->broadCastEvent('beforeGetPropertiesForPath', array($path, $propertyNames, $depth));
03e52840d   Kload   Init
1451
1452
1453
1454
1455
1456
          $returnPropertyList = array();
  
          $parentNode = $this->tree->getNodeForPath($path);
          $nodes = array(
              $path => $parentNode
          );
6d9380f96   Cédric Dupont   Update sources OC...
1457
          if ($depth==1 && $parentNode instanceof ICollection) {
03e52840d   Kload   Init
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
              foreach($this->tree->getChildren($path) as $childNode)
                  $nodes[$path . '/' . $childNode->getName()] = $childNode;
          }
  
          // If the propertyNames array is empty, it means all properties are requested.
          // We shouldn't actually return everything we know though, and only return a
          // sensible list.
          $allProperties = count($propertyNames)==0;
  
          foreach($nodes as $myPath=>$node) {
  
              $currentPropertyNames = $propertyNames;
  
              $newProperties = array(
                  '200' => array(),
                  '404' => array(),
              );
  
              if ($allProperties) {
                  // Default list of propertyNames, when all properties were requested.
                  $currentPropertyNames = array(
                      '{DAV:}getlastmodified',
                      '{DAV:}getcontentlength',
                      '{DAV:}resourcetype',
                      '{DAV:}quota-used-bytes',
                      '{DAV:}quota-available-bytes',
                      '{DAV:}getetag',
                      '{DAV:}getcontenttype',
                  );
              }
  
              // If the resourceType was not part of the list, we manually add it
              // and mark it for removal. We need to know the resourcetype in order
              // to make certain decisions about the entry.
              // WebDAV dictates we should add a / and the end of href's for collections
              $removeRT = false;
              if (!in_array('{DAV:}resourcetype',$currentPropertyNames)) {
                  $currentPropertyNames[] = '{DAV:}resourcetype';
                  $removeRT = true;
              }
  
              $result = $this->broadcastEvent('beforeGetProperties',array($myPath, $node, &$currentPropertyNames, &$newProperties));
              // If this method explicitly returned false, we must ignore this
              // node as it is inaccessible.
              if ($result===false) continue;
  
              if (count($currentPropertyNames) > 0) {
6d9380f96   Cédric Dupont   Update sources OC...
1505
                  if ($node instanceof IProperties) {
03e52840d   Kload   Init
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
                      $nodeProperties = $node->getProperties($currentPropertyNames);
  
                      // The getProperties method may give us too much,
                      // properties, in case the implementor was lazy.
                      //
                      // So as we loop through this list, we will only take the
                      // properties that were actually requested and discard the
                      // rest.
                      foreach($currentPropertyNames as $k=>$currentPropertyName) {
                          if (isset($nodeProperties[$currentPropertyName])) {
                              unset($currentPropertyNames[$k]);
                              $newProperties[200][$currentPropertyName] = $nodeProperties[$currentPropertyName];
                          }
                      }
  
                  }
  
              }
  
              foreach($currentPropertyNames as $prop) {
  
                  if (isset($newProperties[200][$prop])) continue;
  
                  switch($prop) {
6d9380f96   Cédric Dupont   Update sources OC...
1530
                      case '{DAV:}getlastmodified'       : if ($node->getLastModified()) $newProperties[200][$prop] = new Property\GetLastModified($node->getLastModified()); break;
03e52840d   Kload   Init
1531
                      case '{DAV:}getcontentlength'      :
6d9380f96   Cédric Dupont   Update sources OC...
1532
                          if ($node instanceof IFile) {
03e52840d   Kload   Init
1533
1534
1535
1536
1537
1538
1539
                              $size = $node->getSize();
                              if (!is_null($size)) {
                                  $newProperties[200][$prop] = (int)$node->getSize();
                              }
                          }
                          break;
                      case '{DAV:}quota-used-bytes'      :
6d9380f96   Cédric Dupont   Update sources OC...
1540
                          if ($node instanceof IQuota) {
03e52840d   Kload   Init
1541
1542
1543
1544
1545
                              $quotaInfo = $node->getQuotaInfo();
                              $newProperties[200][$prop] = $quotaInfo[0];
                          }
                          break;
                      case '{DAV:}quota-available-bytes' :
6d9380f96   Cédric Dupont   Update sources OC...
1546
                          if ($node instanceof IQuota) {
03e52840d   Kload   Init
1547
1548
1549
1550
                              $quotaInfo = $node->getQuotaInfo();
                              $newProperties[200][$prop] = $quotaInfo[1];
                          }
                          break;
6d9380f96   Cédric Dupont   Update sources OC...
1551
1552
                      case '{DAV:}getetag'               : if ($node instanceof IFile && $etag = $node->getETag())  $newProperties[200][$prop] = $etag; break;
                      case '{DAV:}getcontenttype'        : if ($node instanceof IFile && $ct = $node->getContentType())  $newProperties[200][$prop] = $ct; break;
03e52840d   Kload   Init
1553
1554
1555
1556
1557
                      case '{DAV:}supported-report-set'  :
                          $reports = array();
                          foreach($this->plugins as $plugin) {
                              $reports = array_merge($reports, $plugin->getSupportedReportSet($myPath));
                          }
6d9380f96   Cédric Dupont   Update sources OC...
1558
                          $newProperties[200][$prop] = new Property\SupportedReportSet($reports);
03e52840d   Kload   Init
1559
1560
                          break;
                      case '{DAV:}resourcetype' :
6d9380f96   Cédric Dupont   Update sources OC...
1561
                          $newProperties[200]['{DAV:}resourcetype'] = new Property\ResourceType();
03e52840d   Kload   Init
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
                          foreach($this->resourceTypeMapping as $className => $resourceType) {
                              if ($node instanceof $className) $newProperties[200]['{DAV:}resourcetype']->add($resourceType);
                          }
                          break;
  
                  }
  
                  // If we were unable to find the property, we will list it as 404.
                  if (!$allProperties && !isset($newProperties[200][$prop])) $newProperties[404][$prop] = null;
  
              }
  
              $this->broadcastEvent('afterGetProperties',array(trim($myPath,'/'),&$newProperties, $node));
  
              $newProperties['href'] = trim($myPath,'/');
  
              // Its is a WebDAV recommendation to add a trailing slash to collectionnames.
              // Apple's iCal also requires a trailing slash for principals (rfc 3744), though this is non-standard.
              if ($myPath!='' && isset($newProperties[200]['{DAV:}resourcetype'])) {
                  $rt = $newProperties[200]['{DAV:}resourcetype'];
                  if ($rt->is('{DAV:}collection') || $rt->is('{DAV:}principal')) {
                      $newProperties['href'] .='/';
                  }
              }
  
              // If the resourcetype property was manually added to the requested property list,
              // we will remove it again.
              if ($removeRT) unset($newProperties[200]['{DAV:}resourcetype']);
  
              $returnPropertyList[] = $newProperties;
  
          }
  
          return $returnPropertyList;
  
      }
  
      /**
       * This method is invoked by sub-systems creating a new file.
       *
       * Currently this is done by HTTP PUT and HTTP LOCK (in the Locks_Plugin).
       * It was important to get this done through a centralized function,
       * allowing plugins to intercept this using the beforeCreateFile event.
       *
       * This method will return true if the file was actually created
       *
       * @param string   $uri
       * @param resource $data
       * @param string   $etag
       * @return bool
       */
      public function createFile($uri,$data, &$etag = null) {
6d9380f96   Cédric Dupont   Update sources OC...
1614
          list($dir,$name) = URLUtil::splitPath($uri);
03e52840d   Kload   Init
1615
1616
1617
1618
  
          if (!$this->broadcastEvent('beforeBind',array($uri))) return false;
  
          $parent = $this->tree->getNodeForPath($dir);
6d9380f96   Cédric Dupont   Update sources OC...
1619
1620
          if (!$parent instanceof ICollection) {
              throw new Exception\Conflict('Files can only be created as children of collections');
03e52840d   Kload   Init
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
          }
  
          if (!$this->broadcastEvent('beforeCreateFile',array($uri, &$data, $parent))) return false;
  
          $etag = $parent->createFile($name,$data);
          $this->tree->markDirty($dir . '/' . $name);
  
          $this->broadcastEvent('afterBind',array($uri));
          $this->broadcastEvent('afterCreateFile',array($uri, $parent));
  
          return true;
      }
  
      /**
       * This method is invoked by sub-systems creating a new directory.
       *
       * @param string $uri
       * @return void
       */
      public function createDirectory($uri) {
  
          $this->createCollection($uri,array('{DAV:}collection'),array());
  
      }
  
      /**
       * Use this method to create a new collection
       *
       * The {DAV:}resourcetype is specified using the resourceType array.
       * At the very least it must contain {DAV:}collection.
       *
       * The properties array can contain a list of additional properties.
       *
       * @param string $uri The new uri
       * @param array $resourceType The resourceType(s)
       * @param array $properties A list of properties
       * @return array|null
       */
      public function createCollection($uri, array $resourceType, array $properties) {
6d9380f96   Cédric Dupont   Update sources OC...
1660
          list($parentUri,$newName) = URLUtil::splitPath($uri);
03e52840d   Kload   Init
1661
1662
1663
  
          // Making sure {DAV:}collection was specified as resourceType
          if (!in_array('{DAV:}collection', $resourceType)) {
6d9380f96   Cédric Dupont   Update sources OC...
1664
              throw new Exception\InvalidResourceType('The resourceType for this collection must at least include {DAV:}collection');
03e52840d   Kload   Init
1665
1666
1667
1668
1669
1670
1671
          }
  
  
          // Making sure the parent exists
          try {
  
              $parent = $this->tree->getNodeForPath($parentUri);
6d9380f96   Cédric Dupont   Update sources OC...
1672
          } catch (Exception\NotFound $e) {
03e52840d   Kload   Init
1673

6d9380f96   Cédric Dupont   Update sources OC...
1674
              throw new Exception\Conflict('Parent node does not exist');
03e52840d   Kload   Init
1675
1676
1677
1678
  
          }
  
          // Making sure the parent is a collection
6d9380f96   Cédric Dupont   Update sources OC...
1679
1680
          if (!$parent instanceof ICollection) {
              throw new Exception\Conflict('Parent node is not a collection');
03e52840d   Kload   Init
1681
1682
1683
1684
1685
1686
1687
1688
1689
          }
  
  
  
          // Making sure the child does not already exist
          try {
              $parent->getChild($newName);
  
              // If we got here.. it means there's already a node on that url, and we need to throw a 405
6d9380f96   Cédric Dupont   Update sources OC...
1690
              throw new Exception\MethodNotAllowed('The resource you tried to create already exists');
03e52840d   Kload   Init
1691

6d9380f96   Cédric Dupont   Update sources OC...
1692
          } catch (Exception\NotFound $e) {
03e52840d   Kload   Init
1693
1694
1695
1696
1697
1698
1699
1700
1701
              // This is correct
          }
  
  
          if (!$this->broadcastEvent('beforeBind',array($uri))) return;
  
          // There are 2 modes of operation. The standard collection
          // creates the directory, and then updates properties
          // the extended collection can create it directly.
6d9380f96   Cédric Dupont   Update sources OC...
1702
          if ($parent instanceof IExtendedCollection) {
03e52840d   Kload   Init
1703
1704
1705
1706
1707
1708
1709
  
              $parent->createExtendedCollection($newName, $resourceType, $properties);
  
          } else {
  
              // No special resourcetypes are supported
              if (count($resourceType)>1) {
6d9380f96   Cédric Dupont   Update sources OC...
1710
                  throw new Exception\InvalidResourceType('The {DAV:}resourcetype you specified is not supported here.');
03e52840d   Kload   Init
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
              }
  
              $parent->createDirectory($newName);
              $rollBack = false;
              $exception = null;
              $errorResult = null;
  
              if (count($properties)>0) {
  
                  try {
  
                      $errorResult = $this->updateProperties($uri, $properties);
                      if (!isset($errorResult[200])) {
                          $rollBack = true;
                      }
6d9380f96   Cédric Dupont   Update sources OC...
1726
                  } catch (Exception $e) {
03e52840d   Kload   Init
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
  
                      $rollBack = true;
                      $exception = $e;
  
                  }
  
              }
  
              if ($rollBack) {
                  if (!$this->broadcastEvent('beforeUnbind',array($uri))) return;
                  $this->tree->delete($uri);
  
                  // Re-throwing exception
                  if ($exception) throw $exception;
  
                  return $errorResult;
              }
  
          }
          $this->tree->markDirty($parentUri);
          $this->broadcastEvent('afterBind',array($uri));
  
      }
  
      /**
       * This method updates a resource's properties
       *
       * The properties array must be a list of properties. Array-keys are
       * property names in clarknotation, array-values are it's values.
       * If a property must be deleted, the value should be null.
       *
       * Note that this request should either completely succeed, or
       * completely fail.
       *
       * The response is an array with statuscodes for keys, which in turn
       * contain arrays with propertynames. This response can be used
       * to generate a multistatus body.
       *
       * @param string $uri
       * @param array $properties
       * @return array
       */
      public function updateProperties($uri, array $properties) {
  
          // we'll start by grabbing the node, this will throw the appropriate
          // exceptions if it doesn't.
          $node = $this->tree->getNodeForPath($uri);
  
          $result = array(
              200 => array(),
              403 => array(),
              424 => array(),
          );
          $remainingProperties = $properties;
          $hasError = false;
  
          // Running through all properties to make sure none of them are protected
          if (!$hasError) foreach($properties as $propertyName => $value) {
              if(in_array($propertyName, $this->protectedProperties)) {
                  $result[403][$propertyName] = null;
                  unset($remainingProperties[$propertyName]);
                  $hasError = true;
              }
          }
  
          if (!$hasError) {
              // Allowing plugins to take care of property updating
              $hasError = !$this->broadcastEvent('updateProperties',array(
                  &$remainingProperties,
                  &$result,
                  $node
              ));
          }
6d9380f96   Cédric Dupont   Update sources OC...
1800
          // If the node is not an instance of Sabre\DAV\IProperties, every
03e52840d   Kload   Init
1801
          // property is 403 Forbidden
6d9380f96   Cédric Dupont   Update sources OC...
1802
          if (!$hasError && count($remainingProperties) && !($node instanceof IProperties)) {
03e52840d   Kload   Init
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
              $hasError = true;
              foreach($properties as $propertyName=> $value) {
                  $result[403][$propertyName] = null;
              }
              $remainingProperties = array();
          }
  
          // Only if there were no errors we may attempt to update the resource
          if (!$hasError) {
  
              if (count($remainingProperties)>0) {
  
                  $updateResult = $node->updateProperties($remainingProperties);
  
                  if ($updateResult===true) {
                      // success
                      foreach($remainingProperties as $propertyName=>$value) {
                          $result[200][$propertyName] = null;
                      }
  
                  } elseif ($updateResult===false) {
                      // The node failed to update the properties for an
                      // unknown reason
                      foreach($remainingProperties as $propertyName=>$value) {
                          $result[403][$propertyName] = null;
                      }
  
                  } elseif (is_array($updateResult)) {
  
                      // The node has detailed update information
                      // We need to merge the results with the earlier results.
                      foreach($updateResult as $status => $props) {
                          if (is_array($props)) {
                              if (!isset($result[$status]))
                                  $result[$status] = array();
  
                              $result[$status] = array_merge($result[$status], $updateResult[$status]);
                          }
                      }
  
                  } else {
6d9380f96   Cédric Dupont   Update sources OC...
1844
                      throw new Exception('Invalid result from updateProperties');
03e52840d   Kload   Init
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
                  }
                  $remainingProperties = array();
              }
  
          }
  
          foreach($remainingProperties as $propertyName=>$value) {
              // if there are remaining properties, it must mean
              // there's a dependency failure
              $result[424][$propertyName] = null;
          }
  
          // Removing empty array values
          foreach($result as $status=>$props) {
  
              if (count($props)===0) unset($result[$status]);
  
          }
          $result['href'] = $uri;
          return $result;
  
      }
  
      /**
       * This method checks the main HTTP preconditions.
       *
       * Currently these are:
       *   * If-Match
       *   * If-None-Match
       *   * If-Modified-Since
       *   * If-Unmodified-Since
       *
       * The method will return true if all preconditions are met
       * The method will return false, or throw an exception if preconditions
       * failed. If false is returned the operation should be aborted, and
       * the appropriate HTTP response headers are already set.
       *
       * Normally this method will throw 412 Precondition Failed for failures
       * related to If-None-Match, If-Match and If-Unmodified Since. It will
       * set the status to 304 Not Modified for If-Modified_since.
       *
       * If the $handleAsGET argument is set to true, it will also return 304
       * Not Modified for failure of the If-None-Match precondition. This is the
       * desired behaviour for HTTP GET and HTTP HEAD requests.
       *
       * @param bool $handleAsGET
       * @return bool
       */
      public function checkPreconditions($handleAsGET = false) {
  
          $uri = $this->getRequestUri();
          $node = null;
          $lastMod = null;
          $etag = null;
  
          if ($ifMatch = $this->httpRequest->getHeader('If-Match')) {
  
              // If-Match contains an entity tag. Only if the entity-tag
              // matches we are allowed to make the request succeed.
              // If the entity-tag is '*' we are only allowed to make the
              // request succeed if a resource exists at that url.
              try {
                  $node = $this->tree->getNodeForPath($uri);
6d9380f96   Cédric Dupont   Update sources OC...
1908
1909
              } catch (Exception\NotFound $e) {
                  throw new Exception\PreconditionFailed('An If-Match header was specified and the resource did not exist','If-Match');
03e52840d   Kload   Init
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
              }
  
              // Only need to check entity tags if they are not *
              if ($ifMatch!=='*') {
  
                  // There can be multiple etags
                  $ifMatch = explode(',',$ifMatch);
                  $haveMatch = false;
                  foreach($ifMatch as $ifMatchItem) {
  
                      // Stripping any extra spaces
                      $ifMatchItem = trim($ifMatchItem,' ');
  
                      $etag = $node->getETag();
                      if ($etag===$ifMatchItem) {
                          $haveMatch = true;
                      } else {
                          // Evolution has a bug where it sometimes prepends the "
                          // with a \. This is our workaround.
                          if (str_replace('\\"','"', $ifMatchItem) === $etag) {
                              $haveMatch = true;
                          }
                      }
  
                  }
                  if (!$haveMatch) {
6d9380f96   Cédric Dupont   Update sources OC...
1936
                       throw new Exception\PreconditionFailed('An If-Match header was specified, but none of the specified the ETags matched.','If-Match');
03e52840d   Kload   Init
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
                  }
              }
          }
  
          if ($ifNoneMatch = $this->httpRequest->getHeader('If-None-Match')) {
  
              // The If-None-Match header contains an etag.
              // Only if the ETag does not match the current ETag, the request will succeed
              // The header can also contain *, in which case the request
              // will only succeed if the entity does not exist at all.
              $nodeExists = true;
              if (!$node) {
                  try {
                      $node = $this->tree->getNodeForPath($uri);
6d9380f96   Cédric Dupont   Update sources OC...
1951
                  } catch (Exception\NotFound $e) {
03e52840d   Kload   Init
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
                      $nodeExists = false;
                  }
              }
              if ($nodeExists) {
                  $haveMatch = false;
                  if ($ifNoneMatch==='*') $haveMatch = true;
                  else {
  
                      // There might be multiple etags
                      $ifNoneMatch = explode(',', $ifNoneMatch);
                      $etag = $node->getETag();
  
                      foreach($ifNoneMatch as $ifNoneMatchItem) {
  
                          // Stripping any extra spaces
                          $ifNoneMatchItem = trim($ifNoneMatchItem,' ');
  
                          if ($etag===$ifNoneMatchItem) $haveMatch = true;
  
                      }
  
                  }
  
                  if ($haveMatch) {
                      if ($handleAsGET) {
                          $this->httpResponse->sendStatus(304);
                          return false;
                      } else {
6d9380f96   Cédric Dupont   Update sources OC...
1980
                          throw new Exception\PreconditionFailed('An If-None-Match header was specified, but the ETag matched (or * was specified).','If-None-Match');
03e52840d   Kload   Init
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
                      }
                  }
              }
  
          }
  
          if (!$ifNoneMatch && ($ifModifiedSince = $this->httpRequest->getHeader('If-Modified-Since'))) {
  
              // The If-Modified-Since header contains a date. We
              // will only return the entity if it has been changed since
              // that date. If it hasn't been changed, we return a 304
              // header
              // Note that this header only has to be checked if there was no If-None-Match header
              // as per the HTTP spec.
6d9380f96   Cédric Dupont   Update sources OC...
1995
              $date = HTTP\Util::parseHTTPDate($ifModifiedSince);
03e52840d   Kload   Init
1996
1997
1998
1999
2000
2001
2002
  
              if ($date) {
                  if (is_null($node)) {
                      $node = $this->tree->getNodeForPath($uri);
                  }
                  $lastMod = $node->getLastModified();
                  if ($lastMod) {
6d9380f96   Cédric Dupont   Update sources OC...
2003
                      $lastMod = new \DateTime('@' . $lastMod);
03e52840d   Kload   Init
2004
2005
                      if ($lastMod <= $date) {
                          $this->httpResponse->sendStatus(304);
6d9380f96   Cédric Dupont   Update sources OC...
2006
                          $this->httpResponse->setHeader('Last-Modified', HTTP\Util::toHTTPDate($lastMod));
03e52840d   Kload   Init
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
                          return false;
                      }
                  }
              }
          }
  
          if ($ifUnmodifiedSince = $this->httpRequest->getHeader('If-Unmodified-Since')) {
  
              // The If-Unmodified-Since will allow allow the request if the
              // entity has not changed since the specified date.
6d9380f96   Cédric Dupont   Update sources OC...
2017
              $date = HTTP\Util::parseHTTPDate($ifUnmodifiedSince);
03e52840d   Kload   Init
2018
2019
2020
2021
2022
2023
2024
2025
  
              // We must only check the date if it's valid
              if ($date) {
                  if (is_null($node)) {
                      $node = $this->tree->getNodeForPath($uri);
                  }
                  $lastMod = $node->getLastModified();
                  if ($lastMod) {
6d9380f96   Cédric Dupont   Update sources OC...
2026
                      $lastMod = new \DateTime('@' . $lastMod);
03e52840d   Kload   Init
2027
                      if ($lastMod > $date) {
6d9380f96   Cédric Dupont   Update sources OC...
2028
                          throw new Exception\PreconditionFailed('An If-Unmodified-Since header was specified, but the entity has been changed since the specified date.','If-Unmodified-Since');
03e52840d   Kload   Init
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
                      }
                  }
              }
  
          }
          return true;
  
      }
  
      // }}}
      // {{{ XML Readers & Writers
  
  
      /**
       * Generates a WebDAV propfind response body based on a list of nodes.
       *
       * If 'strip404s' is set to true, all 404 responses will be removed.
       *
       * @param array $fileProperties The list with nodes
       * @param bool strip404s
       * @return string
       */
      public function generateMultiStatus(array $fileProperties, $strip404s = false) {
6d9380f96   Cédric Dupont   Update sources OC...
2052
          $dom = new \DOMDocument('1.0','utf-8');
03e52840d   Kload   Init
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
          //$dom->formatOutput = true;
          $multiStatus = $dom->createElement('d:multistatus');
          $dom->appendChild($multiStatus);
  
          // Adding in default namespaces
          foreach($this->xmlNamespaces as $namespace=>$prefix) {
  
              $multiStatus->setAttribute('xmlns:' . $prefix,$namespace);
  
          }
  
          foreach($fileProperties as $entry) {
  
              $href = $entry['href'];
              unset($entry['href']);
  
              if ($strip404s && isset($entry[404])) {
                  unset($entry[404]);
              }
6d9380f96   Cédric Dupont   Update sources OC...
2072
              $response = new Property\Response($href,$entry);
03e52840d   Kload   Init
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
              $response->serialize($this,$multiStatus);
  
          }
  
          return $dom->saveXML();
  
      }
  
      /**
       * This method parses a PropPatch request
       *
       * PropPatch changes the properties for a resource. This method
       * returns a list of properties.
       *
       * The keys in the returned array contain the property name (e.g.: {DAV:}displayname,
       * and the value contains the property value. If a property is to be removed the value
       * will be null.
       *
       * @param string $body xml body
       * @return array list of properties in need of updating or deletion
       */
      public function parsePropPatchRequest($body) {
  
          //We'll need to change the DAV namespace declaration to something else in order to make it parsable
6d9380f96   Cédric Dupont   Update sources OC...
2097
          $dom = XMLUtil::loadDOMDocument($body);
03e52840d   Kload   Init
2098
2099
2100
2101
2102
2103
  
          $newProperties = array();
  
          foreach($dom->firstChild->childNodes as $child) {
  
              if ($child->nodeType !== XML_ELEMENT_NODE) continue;
6d9380f96   Cédric Dupont   Update sources OC...
2104
              $operation = XMLUtil::toClarkNotation($child);
03e52840d   Kload   Init
2105
2106
  
              if ($operation!=='{DAV:}set' && $operation!=='{DAV:}remove') continue;
6d9380f96   Cédric Dupont   Update sources OC...
2107
              $innerProperties = XMLUtil::parseProperties($child, $this->propertyMap);
03e52840d   Kload   Init
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
  
              foreach($innerProperties as $propertyName=>$propertyValue) {
  
                  if ($operation==='{DAV:}remove') {
                      $propertyValue = null;
                  }
  
                  $newProperties[$propertyName] = $propertyValue;
  
              }
  
          }
  
          return $newProperties;
  
      }
  
      /**
       * This method parses the PROPFIND request and returns its information
       *
       * This will either be a list of properties, or an empty array; in which case
       * an {DAV:}allprop was requested.
       *
       * @param string $body
       * @return array
       */
      public function parsePropFindRequest($body) {
  
          // If the propfind body was empty, it means IE is requesting 'all' properties
          if (!$body) return array();
6d9380f96   Cédric Dupont   Update sources OC...
2138
          $dom = XMLUtil::loadDOMDocument($body);
03e52840d   Kload   Init
2139
          $elem = $dom->getElementsByTagNameNS('urn:DAV','propfind')->item(0);
6d9380f96   Cédric Dupont   Update sources OC...
2140
          return array_keys(XMLUtil::parseProperties($elem));
03e52840d   Kload   Init
2141
2142
2143
2144
2145
2146
  
      }
  
      // }}}
  
  }