forked from sabre-io/dav
/
Server.php
1688 lines (1359 loc) · 53.4 KB
/
Server.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
95
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
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
474
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
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
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
821
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Sabre\DAV;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Sabre\Event\EventEmitter;
use Sabre\HTTP;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
use Sabre\HTTP\URLUtil;
use Sabre\Uri;
/**
* Main DAV server class
*
* @copyright Copyright (C) fruux GmbH (https://fruux.com/)
* @author Evert Pot (http://evertpot.com/)
* @license http://sabre.io/license/ Modified BSD License
*/
class Server extends EventEmitter implements LoggerAwareInterface {
use LoggerAwareTrait;
/**
* 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;
/**
* XML namespace for all SabreDAV related elements
*/
const NS_SABREDAV = 'http://sabredav.org/ns';
/**
* The tree object
*
* @var Tree
*/
public $tree;
/**
* The base uri
*
* @var string
*/
protected $baseUri = null;
/**
* httpResponse
*
* @var HTTP\Response
*/
public $httpResponse;
/**
* httpRequest
*
* @var HTTP\Request
*/
public $httpRequest;
/**
* PHP HTTP Sapi
*
* @var HTTP\Sapi
*/
public $sapi;
/**
* The list of plugins
*
* @var array
*/
protected $plugins = [];
/**
* This property will be filled with a unique string that describes the
* transaction. This is useful for performance measuring and logging
* purposes.
*
* By default it will just fill it with a lowercased HTTP method name, but
* plugins override this. For example, the WebDAV-Sync sync-collection
* report will set this to 'report-sync-collection'.
*
* @var string
*/
public $transactionType;
/**
* This is a list of properties that are always server-controlled, and
* must not get modified with PROPPATCH.
*
* Plugins may add to this list.
*
* @var string[]
*/
public $protectedProperties = [
// 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',
// RFC3253
'{DAV:}supported-method-set',
'{DAV:}supported-report-set',
// RFC6578
'{DAV:}sync-token',
// calendarserver.org extensions
'{http://calendarserver.org/ns/}ctag',
// sabredav extensions
'{http://sabredav.org/ns}sync-token',
];
/**
* 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 automatically added for nodes
* implementing Sabre\DAV\ICollection.
*
* @var array
*/
public $resourceTypeMapping = [
'Sabre\\DAV\\ICollection' => '{DAV:}collection',
];
/**
* This property allows the usage of Depth: infinity on PROPFIND requests.
*
* By default Depth: infinity is treated as Depth: 1. Allowing Depth:
* infinity is potentially risky, as it allows a single client to do a full
* index of the webdav server, which is an easy DoS attack vector.
*
* Only turn this on if you know what you're doing.
*
* @var bool
*/
public $enablePropfindDepthInfinity = false;
/**
* Reference to the XML utility object.
*
* @var Xml\Service
*/
public $xml;
/**
* 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 $exposeVersion = true;
/**
* Sets up the server
*
* 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\Tree and use the node as the root.
*
* If nothing is passed, a Sabre\DAV\SimpleCollection is created in
* a Sabre\DAV\Tree.
*
* If an array is passed, we automatically create a root node, and use
* the nodes in the array as top-level children.
*
* @param Tree|INode|array|null $treeOrNode The tree object
*/
function __construct($treeOrNode = null) {
if ($treeOrNode instanceof Tree) {
$this->tree = $treeOrNode;
} elseif ($treeOrNode instanceof INode) {
$this->tree = new Tree($treeOrNode);
} 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) {
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');
}
}
$root = new SimpleCollection('root', $treeOrNode);
$this->tree = new Tree($root);
} elseif (is_null($treeOrNode)) {
$root = new SimpleCollection('root');
$this->tree = new Tree($root);
} else {
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');
}
$this->xml = new Xml\Service();
$this->sapi = new HTTP\Sapi();
$this->httpResponse = new HTTP\Response();
$this->httpRequest = $this->sapi->getRequest();
$this->addPlugin(new CorePlugin());
}
/**
* Starts the DAV Server
*
* @return void
*/
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->setHTTPVersion($this->httpRequest->getHTTPVersion());
// Setting the base url
$this->httpRequest->setBaseUrl($this->getBaseUri());
$this->invokeMethod($this->httpRequest, $this->httpResponse);
} catch (\Exception $e) {
try {
$this->emit('exception', [$e]);
} catch (\Exception $ignore) {
}
$DOM = new \DOMDocument('1.0', 'utf-8');
$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');
};
if (self::$exposeVersion) {
$error->appendChild($DOM->createElement('s:sabredav-version', $h(Version::VERSION)));
}
$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 ($this->debugExceptions) {
$previous = $e;
while ($previous = $previous->getPrevious()) {
$xPrevious = $DOM->createElement('s:previous-exception');
$xPrevious->appendChild($DOM->createElement('s:exception', $h(get_class($previous))));
$xPrevious->appendChild($DOM->createElement('s:message', $h($previous->getMessage())));
$xPrevious->appendChild($DOM->createElement('s:file', $h($previous->getFile())));
$xPrevious->appendChild($DOM->createElement('s:line', $h($previous->getLine())));
$xPrevious->appendChild($DOM->createElement('s:code', $h($previous->getCode())));
$xPrevious->appendChild($DOM->createElement('s:stacktrace', $h($previous->getTraceAsString())));
$error->appendChild($xPrevious);
}
}
if ($e instanceof Exception) {
$httpCode = $e->getHTTPCode();
$e->serialize($this, $error);
$headers = $e->getHTTPHeaders($this);
} else {
$httpCode = 500;
$headers = [];
}
$headers['Content-Type'] = 'application/xml; charset=utf-8';
$this->httpResponse->setStatus($httpCode);
$this->httpResponse->setHeaders($headers);
$this->httpResponse->setBody($DOM->saveXML());
$this->sapi->sendResponse($this->httpResponse);
}
}
/**
* Sets the base server uri
*
* @param string $uri
* @return void
*/
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
*/
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
*/
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.
$decodedUri = URLUtil::decodePath($uri);
// A simple sanity check:
if (substr($decodedUri, strlen($decodedUri) - strlen($pathInfo)) === $pathInfo) {
$baseUri = substr($decodedUri, 0, strlen($decodedUri) - strlen($pathInfo));
return rtrim($baseUri, '/') . '/';
}
throw new Exception('The REQUEST_URI (' . $uri . ') did not end with the contents of PATH_INFO (' . $pathInfo . '). This server might be misconfigured.');
}
// The last fallback is that we're just going to assume the server root.
return '/';
}
/**
* Adds a plugin to the server
*
* For more information, console the documentation of Sabre\DAV\ServerPlugin
*
* @param ServerPlugin $plugin
* @return void
*/
function addPlugin(ServerPlugin $plugin) {
$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
* @return ServerPlugin
*/
function getPlugin($name) {
if (isset($this->plugins[$name]))
return $this->plugins[$name];
return null;
}
/**
* Returns all plugins
*
* @return array
*/
function getPlugins() {
return $this->plugins;
}
/**
* Returns the PSR-3 logger object.
*
* @return LoggerInterface
*/
function getLogger() {
if (!$this->logger) {
$this->logger = new NullLogger();
}
return $this->logger;
}
/**
* Handles a http request, and execute a method based on its name
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param bool $sendResponse Whether to send the HTTP response to the DAV client.
* @return void
*/
function invokeMethod(RequestInterface $request, ResponseInterface $response, $sendResponse = true) {
$method = $request->getMethod();
if (!$this->emit('beforeMethod:' . $method, [$request, $response])) return;
if (!$this->emit('beforeMethod', [$request, $response])) return;
if (self::$exposeVersion) {
$response->setHeader('X-Sabre-Version', Version::VERSION);
}
$this->transactionType = strtolower($method);
if (!$this->checkPreconditions($request, $response)) {
$this->sapi->sendResponse($response);
return;
}
if ($this->emit('method:' . $method, [$request, $response])) {
if ($this->emit('method', [$request, $response])) {
$exMessage = "There was no plugin in the system that was willing to handle this " . $method . " method.";
if ($method === "GET") {
$exMessage .= " Enable the Browser plugin to get a better result here.";
}
// Unsupported method
throw new Exception\NotImplemented($exMessage);
}
}
if (!$this->emit('afterMethod:' . $method, [$request, $response])) return;
if (!$this->emit('afterMethod', [$request, $response])) return;
if ($response->getStatus() === null) {
throw new Exception('No subsystem set a valid HTTP status code. Something must have interrupted the request without providing further detail.');
}
if ($sendResponse) {
$this->sapi->sendResponse($response);
$this->emit('afterResponse', [$request, $response]);
}
}
// {{{ HTTP/WebDAV protocol helpers
/**
* Returns an array with all the supported HTTP methods for a specific uri.
*
* @param string $path
* @return array
*/
function getAllowedMethods($path) {
$methods = [
'OPTIONS',
'GET',
'HEAD',
'DELETE',
'PROPFIND',
'PUT',
'PROPPATCH',
'COPY',
'MOVE',
'REPORT'
];
// The MKCOL is only allowed on an unmapped uri
try {
$this->tree->getNodeForPath($path);
} catch (Exception\NotFound $e) {
$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($path));
array_unique($methods);
return $methods;
}
/**
* Gets the uri for the request, keeping the base uri into consideration
*
* @return string
*/
function getRequestUri() {
return $this->calculateUri($this->httpRequest->getUrl());
}
/**
* Turns a URI such as the REQUEST_URI into a local path.
*
* This method:
* * strips off the base path
* * normalizes the path
* * uri-decodes the path
*
* @param string $uri
* @throws Exception\Forbidden A permission denied exception is thrown whenever there was an attempt to supply a uri outside of the base uri
* @return string
*/
function calculateUri($uri) {
if ($uri[0] != '/' && strpos($uri, '://')) {
$uri = parse_url($uri, PHP_URL_PATH);
}
$uri = Uri\normalize(str_replace('//', '/', $uri));
$baseUri = Uri\normalize($this->getBaseUri());
if (strpos($uri, $baseUri) === 0) {
return trim(URLUtil::decodePath(substr($uri, strlen($baseUri))), '/');
// A special case, if the baseUri was accessed without a trailing
// slash, we'll accept it as well.
} elseif ($uri . '/' === $baseUri) {
return '';
} else {
throw new Exception\Forbidden('Requested uri (' . $uri . ') is out of base uri (' . $this->getBaseUri() . ')');
}
}
/**
* Returns the HTTP depth header
*
* 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
* 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
*/
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
*/
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 [
$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:
* [
* '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
*/
function getHTTPPrefer() {
$result = [
// can be true or false
'respond-async' => false,
// Could be set to 'representation' or 'minimal'.
'return' => null,
// Used as a timeout, is usually a number.
'wait' => null,
// can be 'strict' or 'lenient'.
'handling' => false,
];
if ($prefer = $this->httpRequest->getHeader('Prefer')) {
$result = array_merge(
$result,
HTTP\parsePrefer($prefer)
);
} elseif ($this->httpRequest->getHeader('Brief') == 't') {
$result['return'] = 'minimal';
}
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)
*
* @param RequestInterface $request
* @throws Exception\BadRequest upon missing or broken request headers
* @throws Exception\UnsupportedMediaType when trying to copy into a
* non-collection.
* @throws Exception\PreconditionFailed If overwrite is set to false, but
* the destination exists.
* @throws Exception\Forbidden when source and destination paths are
* identical.
* @throws Exception\Conflict When trying to copy a node into its own
* subtree.
* @return array
*/
function getCopyAndMoveInfo(RequestInterface $request) {
// Collecting the relevant HTTP headers
if (!$request->getHeader('Destination')) throw new Exception\BadRequest('The destination header was not supplied');
$destination = $this->calculateUri($request->getHeader('Destination'));
$overwrite = $request->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
else throw new Exception\BadRequest('The HTTP Overwrite header should be either T or F');
list($destinationDir) = URLUtil::splitPath($destination);
try {
$destinationParent = $this->tree->getNodeForPath($destinationDir);
if (!($destinationParent instanceof ICollection)) throw new Exception\UnsupportedMediaType('The destination node is not a collection');
} catch (Exception\NotFound $e) {
// If the destination parent node is not found, we throw a 409
throw new Exception\Conflict('The destination node is not found');
}
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
if (!$overwrite) throw new Exception\PreconditionFailed('The destination node already exists, and the overwrite header is set to false', 'Overwrite');
} catch (Exception\NotFound $e) {
// Destination didn't exist, we're all good
$destinationNode = false;
}
$requestPath = $request->getPath();
if ($destination === $requestPath) {
throw new Exception\Forbidden('Source and destination uri are identical.');
}
if (substr($destination, 0, strlen($requestPath) + 1) === $requestPath . '/') {
throw new Exception\Conflict('The destination may not be part of the same subtree as the source path.');
}
// These are the three relevant properties we need to return
return [
'destination' => $destination,
'destinationExists' => !!$destinationNode,
'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.
*
* Please note though that any problems related to retrieving properties,
* such as permission issues will just result in an empty array being
* returned.
*
* @param string $path
* @param array $propertyNames
* @return array
*/
function getProperties($path, $propertyNames) {
$result = $this->getPropertiesForPath($path, $propertyNames, 0);
if (isset($result[0][200])) {
return $result[0][200];
} else {
return [];
}
}
/**
* 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
*/
function getPropertiesForChildren($path, $propertyNames) {
$result = [];
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
*/
function getHTTPHeaders($path) {
$propertyMap = [
'{DAV:}getcontenttype' => 'Content-Type',
'{DAV:}getcontentlength' => 'Content-Length',
'{DAV:}getlastmodified' => 'Last-Modified',
'{DAV:}getetag' => 'ETag',
];
$properties = $this->getProperties($path, array_keys($propertyMap));
$headers = [];
foreach ($propertyMap as $property => $header) {
if (!isset($properties[$property])) continue;
if (is_scalar($properties[$property])) {
$headers[$header] = $properties[$property];
// GetLastModified gets special cased
} elseif ($properties[$property] instanceof Xml\Property\GetLastModified) {
$headers[$header] = HTTP\Util::toHTTPDate($properties[$property]->getTime());
}
}
return $headers;
}
/**
* Small helper to support PROPFIND with DEPTH_INFINITY.
*
* @param PropFind $propFind
* @param array $yieldFirst
* @return \Iterator
*/
private function generatePathNodes(PropFind $propFind, array $yieldFirst = null) {
if ($yieldFirst !== null) {
yield $yieldFirst;
}
$newDepth = $propFind->getDepth();
$path = $propFind->getPath();
if ($newDepth !== self::DEPTH_INFINITY) {
$newDepth--;
}
$propertyNames = $propFind->getRequestedProperties();
$propFindType = !empty($propertyNames) ? PropFind::NORMAL : PropFind::ALLPROPS;
foreach ($this->tree->getChildren($path) as $childNode) {
if ($path !== '') {
$subPath = $path . '/' . $childNode->getName();
} else {
$subPath = $childNode->getName();
}
$subPropFind = new PropFind($subPath, $propertyNames, $newDepth, $propFindType);
yield [
$subPropFind,
$childNode
];
if (($newDepth === self::DEPTH_INFINITY || $newDepth >= 1) && $childNode instanceof ICollection) {
foreach ($this->generatePathNodes($subPropFind) as $subItem) {
yield $subItem;
}
}
}
}
/**
* 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
*
* @deprecated Use getPropertiesIteratorForPath() instead (as it's more memory efficient)
* @see getPropertiesIteratorForPath()
*/
function getPropertiesForPath($path, $propertyNames = [], $depth = 0) {
return iterator_to_array($this->getPropertiesIteratorForPath($path, $propertyNames, $depth));
}
/**
* 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 \Iterator
*/
function getPropertiesIteratorForPath($path, $propertyNames = [], $depth = 0) {
// The only two options for the depth of a propfind is 0 or 1 - as long as depth infinity is not enabled
if (!$this->enablePropfindDepthInfinity && $depth != 0) $depth = 1;
$path = trim($path, '/');
$propFindType = $propertyNames ? PropFind::NORMAL : PropFind::ALLPROPS;
$propFind = new PropFind($path, (array)$propertyNames, $depth, $propFindType);
$parentNode = $this->tree->getNodeForPath($path);
$propFindRequests = [[
$propFind,
$parentNode
]];
if (($depth > 0 || $depth === self::DEPTH_INFINITY) && $parentNode instanceof ICollection) {
$propFindRequests = $this->generatePathNodes(clone $propFind, current($propFindRequests));
}
foreach ($propFindRequests as $propFindRequest) {
list($propFind, $node) = $propFindRequest;
$r = $this->getPropertiesByNode($propFind, $node);
if ($r) {
$result = $propFind->getResultForMultiStatus();
$result['href'] = $propFind->getPath();
// WebDAV recommends adding a slash to the path, if the path is
// a collection.
// Furthermore, iCal also demands this to be the case for
// principals. This is non-standard, but we support it.
$resourceType = $this->getResourceTypeForNode($node);
if (in_array('{DAV:}collection', $resourceType) || in_array('{DAV:}principal', $resourceType)) {
$result['href'] .= '/';
}
yield $result;
}
}
}