-
Notifications
You must be signed in to change notification settings - Fork 27
/
Client.php
2031 lines (1744 loc) · 70.1 KB
/
Client.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 Jackalope\Transport\Jackrabbit;
use DOMDocument;
use Jackalope\FactoryInterface;
use Jackalope\Lock\Lock;
use Jackalope\Node;
use Jackalope\NodeType\NodeTypeManager;
use Jackalope\NotImplementedException;
use Jackalope\Property;
use Jackalope\Query\Query;
use Jackalope\Transport\BaseTransport;
use Jackalope\Transport\NodeTypeCndManagementInterface;
use Jackalope\Transport\PermissionInterface;
use Jackalope\Transport\QueryInterface as QueryTransport;
use Jackalope\Transport\VersioningInterface;
use Jackalope\Transport\WritingInterface;
use PHPCR\CredentialsInterface;
use PHPCR\ItemExistsException;
use PHPCR\ItemNotFoundException;
use PHPCR\LoginException;
use PHPCR\Observation\EventFilterInterface;
use PHPCR\PathNotFoundException;
use PHPCR\PropertyType;
use PHPCR\Query\InvalidQueryException;
use PHPCR\Query\QueryInterface;
use PHPCR\RepositoryException;
use PHPCR\RepositoryInterface;
use PHPCR\SessionInterface;
use PHPCR\SimpleCredentials;
use PHPCR\UnsupportedRepositoryOperationException;
use PHPCR\Util\PathHelper;
use PHPCR\Util\ValueConverter;
use PHPCR\ValueFormatException;
use PHPCR\Version\LabelExistsVersionException;
/**
* Connection to one Jackrabbit server.
*
* This class handles the communication between Jackalope and Jackrabbit over
* Davex. Once the login method has been called, the workspace is set and can
* not be changed anymore.
*
* We make one exception to the rule that nothing may be cached in the
* transport: Repository descriptors are considered immutable and cached
* (because they are also used in startup to check the backend version is
* compatible).
*
* @license http://www.apache.org/licenses Apache License Version 2.0, January 2004
* @license http://opensource.org/licenses/MIT MIT License
* @author Christian Stocker <chregu@liip.ch>
* @author David Buchmann <david@liip.ch>
* @author Tobias Ebnöther <ebi@liip.ch>
* @author Roland Schilter <roland.schilter@liip.ch>
* @author Uwe Jäger <uwej711@googlemail.com>
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
* @author Daniel Barsotti <daniel.barsotti@liip.ch>
* @author Markus Schmucker <markus.sr@gmx.net>
*/
class Client extends BaseTransport implements JackrabbitClientInterface
{
/**
* Minimal version requirement for the Jackrabbit backend server.
*/
public const VERSION = '2.3.6';
/**
* Minimal version of the Jackrabbit backend server known to support
* storing unicode symbols outside of UTF-8 basic multilingual plane.
*
* Note: We are sure which exact version of Jackrabbit introduced support
* for full UTF-8 symbols. This is the lowest version known to work.
*/
public const UTF8_SUPPORT_MINIMAL_VERSION = '2.18.0';
/**
* Description of the namspace to be used for communication with the server.
*
* @var string
*/
public const NS_DCR = 'http://www.day.com/jcr/webdav/1.0';
/**
* Identifier of the used namespace.
*
* @var string
*/
public const NS_DAV = 'DAV:';
/**
* Value of the <timeout> tag for infinite timeout (since jackrabbit 2.4).
*/
public const JCR_INFINITE = 'Infinite';
/**
* Jackrabbit 2.3.6+2.3.7 return this weird number to say its an infinite lock
* This has been fixed in 2.4.
*/
public const JCR_INFINITE_LOCK_TIMEOUT = 2147483;
/**
* The path to request to get the Jackrabbit event journal.
*/
public const JCR_JOURNAL_PATH = '?type=journal';
/**
* The factory to instantiate objects.
*
* @var FactoryInterface
*/
protected $factory;
/** @var ValueConverter */
protected $valueConverter;
/**
* Server url including protocol.
*
* i.e http://localhost:8080/server/
* constructor ensures the trailing slash /
*
* @var string
*/
protected $server;
/**
* Workspace name the transport is bound to.
*
* Set once login() has been executed and may not be changed later on.
*
* @var string
*/
protected $workspace;
/**
* Identifier of the workspace including the used protocol and server name.
*
* "$server/$workspace" without trailing slash
*
* @var string
*/
protected $workspaceUri;
/**
* Root node path with server domain without trailing slash.
*
* "$server/$workspace/jcr%3aroot
* (make sure you never hardcode the jcr%3aroot, its ugly)
*
* @todo apparently, jackrabbit handles the root node by name - it is invisible everywhere for the api,
* but needed when talking to the backend... could that name change?
*
* @var string
*/
protected $workspaceUriRoot;
/**
* Set of credentials necessary to connect to the server.
*
* Set once login() has been executed and may not be changed later on.
*
* @var SimpleCredentials
*/
protected $credentials;
/**
* The cURL resource handle.
*
* @var curl
*/
protected $curl;
/**
* A list of additional HTTP headers to be sent on each request.
*
* @var string[]
*/
protected $defaultHeaders = [];
/**
* @var bool Send Expect: 100-continue header
*/
protected $sendExpect = false;
/**
* @var \Jackalope\NodeType\NodeTypeXmlConverter
*/
protected $typeXmlConverter;
/**
* @var NodeTypeManager
*/
protected $nodeTypeManager;
/**
* Check if an initial PROPFIND should be send to check if repository exists
* This is according to the JCR specifications and set to true by default.
*
* @see setCheckLoginOnServer
*
* @var bool
*/
protected $checkLoginOnServer = true;
/**
* Cached result of the repository descriptors.
*
* This is our exception to the rule that nothing may be cached in transport.
*
* @var string[] as returned by getRepositoryDescriptors
*/
protected $descriptors;
protected $jsopBody = [];
protected $userData;
/**
* Global curl-options used in each request.
*
* @var array
*/
private $curlOptions = [];
/**
* Version of the Jackrabbit server as declared in the configuration.
*
* @var string|null
*/
private $version;
/**
* Create a transport pointing to a server url.
*
* @param FactoryInterface $factory the object factory
* @param string $serverUri location of the server
*/
public function __construct(FactoryInterface $factory, $serverUri)
{
$this->factory = $factory;
$this->valueConverter = $this->factory->get('PHPCR\Util\ValueConverter');
// append a slash if not there
if ('/' !== substr($serverUri, -1)) {
$serverUri .= '/';
}
$this->server = $serverUri;
}
/**
* Tidies up the current cUrl connection.
*/
public function __destruct()
{
$this->logout();
}
public function addDefaultHeader($header)
{
$this->defaultHeaders[] = $header;
}
public function sendExpect($send = true)
{
$this->sendExpect = $send;
}
public function forceHttpVersion10($forceHttpVersion10 = true)
{
if ($forceHttpVersion10) {
$this->addCurlOptions([CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0]);
} else {
unset($this->curlOptions[CURLOPT_HTTP_VERSION]);
}
}
public function addCurlOptions(array $options)
{
return $this->curlOptions += $options;
}
/**
* Makes sure there is an open curl connection.
*
* @return Request The Request
*/
protected function getRequest($method, $uri, $addWorkspacePathToUri = true)
{
$uri = (array) $uri;
$curl = $this->getCurl();
if ($addWorkspacePathToUri) {
foreach ($uri as $key => $row) {
$uri[$key] = $this->addWorkspacePathToUri($row);
}
}
/** @var Request $request */
$request = $this->factory->get('Transport\\Jackrabbit\\Request', [$this, $curl, $method, $uri]);
$request->setCredentials($this->credentials);
if (null !== $this->userData) {
$request->addUserData($this->userData);
}
foreach ($this->defaultHeaders as $header) {
$request->addHeader($header);
}
if (!$this->sendExpect) {
$request->addHeader('Expect:');
}
$request->addCurlOptions($this->curlOptions);
return $request;
}
protected function getCurl()
{
if (is_null($this->curl)) {
// lazy init curl
$this->curl = new curl();
} elseif (false === $this->curl) {
// but do not re-connect, rather report the error if trying to access a closed connection
throw new \LogicException('Tried to start a request on a closed transport.');
}
return $this->curl;
}
public function getWorkspaceUri()
{
return $this->workspaceUri;
}
// CoreInterface //
public function login(CredentialsInterface $credentials = null, $workspaceName = null)
{
if ($this->credentials) {
throw new RepositoryException(
'Do not call login twice. Rather instantiate a new Transport object '.
'to log in as different user or for a different workspace.'
);
}
if (!$credentials instanceof SimpleCredentials) {
$hint = is_null($credentials)
? 'jackalope-jackrabbit does not support "null" credentials'
: 'Only SimpleCredentials are supported. Unkown credentials type: '.get_class($credentials);
throw new LoginException($hint);
}
$this->credentials = $credentials;
if (!$workspaceName) {
$request = $this->getRequest(Request::PROPFIND, $this->server);
$request->setBody($this->buildPropfindRequest(['dcr:workspaceName']));
$dom = $request->executeDom();
$answer = $dom->getElementsByTagNameNS(self::NS_DCR, 'workspaceName');
$workspaceName = $answer->item(0)->textContent;
}
$this->workspace = $workspaceName;
$this->workspaceUri = $this->server.$workspaceName;
$this->workspaceUriRoot = $this->workspaceUri.'/jcr:root';
if (!$this->checkLoginOnServer) {
return $workspaceName;
}
$request = $this->getRequest(Request::PROPFIND, $this->workspaceUri);
$request->setBody($this->buildPropfindRequest(['D:workspace', 'dcr:workspaceName']));
$dom = $request->executeDom();
$set = $dom->getElementsByTagNameNS(self::NS_DCR, 'workspaceName');
if (1 != $set->length) {
throw new RepositoryException('Unexpected answer from server: '.$dom->saveXML());
}
if ($set->item(0)->textContent != $this->workspace) {
throw new RepositoryException('Wrong workspace in answer from server: '.$dom->saveXML());
}
return $workspaceName;
}
public function logout()
{
if (!empty($this->curl)) {
$this->curl->close();
}
$this->curl = false;
}
public function setCheckLoginOnServer($bool)
{
$this->checkLoginOnServer = $bool;
}
public function getRepositoryDescriptors()
{
if (null == $this->descriptors) {
$request = $this->getRequest(Request::REPORT, $this->server);
$request->setBody($this->buildReportRequest('dcr:repositorydescriptors'));
$dom = $request->executeDom();
if ('repositorydescriptors-report' != $dom->firstChild->localName
|| self::NS_DCR != $dom->firstChild->namespaceURI
) {
throw new RepositoryException('Error talking to the backend. '.$dom->saveXML());
}
$descs = $dom->getElementsByTagNameNS(self::NS_DCR, 'descriptor');
$this->descriptors = [];
foreach ($descs as $desc) {
$name = $desc->getElementsByTagNameNS(self::NS_DCR, 'descriptorkey')->item(0)->textContent;
$values = [];
$valuenodes = $desc->getElementsByTagNameNS(self::NS_DCR, 'descriptorvalue');
foreach ($valuenodes as $value) {
$values[] = $value->textContent;
}
if (1 == $valuenodes->length) {
// there was one type and one value => this is a single value property
// TODO: is this the correct assumption? or should the backend tell us specifically?
$this->descriptors[$name] = $values[0];
} else {
$this->descriptors[$name] = $values;
}
}
// Supported by Jackrabbit, but not supported by this client
$this->descriptors[RepositoryInterface::NODE_TYPE_MANAGEMENT_SAME_NAME_SIBLINGS_SUPPORTED] = false;
$this->descriptors[RepositoryInterface::QUERY_CANCEL_SUPPORTED] = false;
if (!isset($this->descriptors['jcr.repository.version'])) {
throw new UnsupportedRepositoryOperationException("The backend at {$this->server} does not provide the jcr.repository.version descriptor");
}
if (!version_compare(self::VERSION, $this->descriptors['jcr.repository.version'], '<=')) {
throw new UnsupportedRepositoryOperationException("The backend at {$this->server} is an unsupported version of jackrabbit: \"".
$this->descriptors['jcr.repository.version'].
'". Need at least "'.self::VERSION.'"');
}
if ($this->version) {
// Sanity check if the configured version has the same major and minor number as the version reported by the backend.
$serverVersion = implode('.', array_slice(explode('.', $this->descriptors['jcr.repository.version']), 0, 2));
$configuredVersion = implode('.', array_slice(explode('.', $this->version), 0, 2));
if (!version_compare($serverVersion, $configuredVersion, '==')) {
trigger_error(
sprintf(
'Version mismatch between configured version %s and version %s reported by the backend at %s.',
$this->version,
$this->descriptors['jcr.repository.version'],
$this->server
),
E_USER_NOTICE
);
}
}
}
return $this->descriptors;
}
public function getAccessibleWorkspaceNames()
{
$request = $this->getRequest(Request::PROPFIND, $this->server);
$request->setBody($this->buildPropfindRequest(['D:workspace']));
$request->setDepth(1);
$dom = $request->executeDom();
$workspaces = [];
foreach ($dom->getElementsByTagNameNS(self::NS_DAV, 'workspace') as $value) {
if (!empty($value->nodeValue)) {
$workspaces[] = substr(trim($value->nodeValue), strlen($this->server), -1);
}
}
return array_unique($workspaces);
}
public function getNode($path)
{
$path = $this->encodeAndValidatePathForDavex($path);
$path .= '.'.$this->getFetchDepth().'.json';
$request = $this->getRequest(Request::GET, $path);
try {
return $request->executeJson();
} catch (PathNotFoundException $e) {
throw new ItemNotFoundException($e->getMessage(), $e->getCode(), $e);
}
}
public function getNodes($paths, $query = ':include')
{
if (0 == count($paths)) {
return [];
}
if (1 == count($paths)) {
$url = array_shift($paths);
try {
return [$url => $this->getNode($url)];
} catch (ItemNotFoundException $e) {
return [];
}
}
$body = [];
$url = '/.'.$this->getFetchDepth().'.json';
foreach ($paths as $path) {
$body[] = http_build_query([$query => $path]);
}
$body = implode('&', $body);
$request = $this->getRequest(Request::POST, $url);
$request->setBody($body);
$request->setContentType('application/x-www-form-urlencoded; charset=utf-8');
try {
$data = $request->executeJson();
return (array) $data->nodes;
} catch (PathNotFoundException $e) {
throw new ItemNotFoundException($e->getMessage(), $e->getCode(), $e);
}
}
public function getNodesByIdentifier($identifiers)
{
// OPTIMIZE get paths for UUID's via a single query
// or get the data directly
// return $this->getNodes($identifiers, ':id');
$paths = [];
foreach ($identifiers as $key => $identifier) {
try {
$paths[$key] = $this->getNodePathForIdentifier($identifier);
} catch (ItemNotFoundException $e) {
// ignore
}
}
return $this->getNodes($paths);
}
public function getNodeByIdentifier($uuid)
{
// OPTIMIZE get nodes directly by uuid from backend. needs implementation on jackrabbit
$path = $this->getNodePathForIdentifier($uuid);
$data = $this->getNode($path);
$data->{':jcr:path'} = $path;
return $data;
}
public function getNodePathForIdentifier($uuid, $workspace = null)
{
if (null !== $workspace && $workspace != $this->workspace) {
$client = new Client($this->factory, $this->server);
$client->login($this->credentials, $workspace);
return $client->getNodePathForIdentifier($uuid);
}
$request = $this->getRequest(Request::REPORT, $this->workspaceUri);
$request->setBody($this->buildLocateRequest($uuid));
$dom = $request->executeDom();
/* answer looks like
<D:multistatus xmlns:D="DAV:">
<D:response>
<D:href>http://localhost:8080/server/tests/jcr%3aroot/tests_level1_access_base/idExample/</D:href>
</D:response>
</D:multistatus>
*/
$set = $dom->getElementsByTagNameNS(self::NS_DAV, 'href');
if (1 != $set->length) {
throw new RepositoryException('Unexpected answer from server: '.$dom->saveXML());
}
$fullPath = $set->item(0)->textContent;
if (strncmp($this->workspaceUriRoot, $fullPath, strlen($this->workspaceUri))) {
throw new RepositoryException(
"Server answered a path that is not in the current workspace: uuid=$uuid, path=$fullPath, workspace=".
$this->workspaceUriRoot
);
}
return $this->stripServerRootFromUri(substr(urldecode($fullPath), 0, -1));
}
public function getProperty($path)
{
throw new NotImplementedException();
/*
* TODO: implement
* jackrabbit: instead of fetching the node, we could make Transport provide it with a
* GET /server/tests/jcr%3aroot/tests_level1_access_base/multiValueProperty/jcr%3auuid
* (davex getItem uses json, which is not applicable to properties)
*/
}
public function getBinaryStream($path)
{
$path = $this->encodeAndValidatePathForDavex($path);
$request = $this->getRequest(Request::GET, $path);
$curl = $request->execute(true);
switch (strtolower($curl->getHeader('Content-Type'))) {
case 'text/xml; charset=utf-8':
case 'text/xml;charset=utf-8':
return $this->decodeBinaryDom($curl->getResponse());
case 'jcr-value/binary;charset=utf-8':
case 'jcr-value/binary; charset=utf-8':
// TODO: OPTIMIZE stream handling!
$stream = fopen('php://memory', 'rwb+');
fwrite($stream, $curl->getResponse());
rewind($stream);
return $stream;
}
throw new RepositoryException('Unknown encoding of binary data: '.$curl->getHeader('Content-Type'));
}
/**
* parse the multivalue binary response (a list of base64 encoded values).
*
* <dcr:values xmlns:dcr="http://www.day.com/jcr/webdav/1.0">
* <dcr:value dcr:type="Binary">aDEuIENoYXB0ZXIgMSBUaXRsZQoKKiBmb28KKiBiYXIKKiogZm9vMgoqKiBmb28zCiogZm9vMAoKfHwgaGVhZGVyIHx8IGJhciB8fAp8IGggfCBqIHwKCntjb2RlfQpoZWxsbyB3b3JsZAp7Y29kZX0KCiMgZm9vCg==</dcr:value>
* <dcr:value dcr:type="Binary">aDEuIENoYXB0ZXIgMSBUaXRsZQoKKiBmb28KKiBiYXIKKiogZm9vMgoqKiBmb28zCiogZm9vMAoKfHwgaGVhZGVyIHx8IGJhciB8fAp8IGggfCBqIHwKCntjb2RlfQpoZWxsbyB3b3JsZAp7Y29kZX0KCiMgZm9vCg==</dcr:value>
* </dcr:values>
*
* @param string $xml the xml as returned by jackrabbit
*
* @return array of stream resources
*
* @throws RepositoryException if the xml is invalid or any value is not of type binary
*/
private function decodeBinaryDom($xml)
{
$dom = new \DOMDocument();
if (!$dom->loadXML($xml)) {
throw new RepositoryException("Failed to load xml data:\n\n$xml");
}
$ret = [];
foreach ($dom->getElementsByTagNameNS(self::NS_DCR, 'values') as $node) {
foreach ($node->getElementsByTagNameNS(self::NS_DCR, 'value') as $value) {
if (PropertyType::TYPENAME_BINARY != $value->getAttributeNS(self::NS_DCR, 'type')) {
throw new RepositoryException('Expected binary value but got '.$value->getAttributeNS(self::NS_DCR, 'type'));
}
// TODO: OPTIMIZE stream handling!
$stream = fopen('php://memory', 'rwb+');
fwrite($stream, base64_decode($value->textContent));
rewind($stream);
$ret[] = $stream;
}
}
return $ret;
}
public function getReferences($path, $name = null)
{
return $this->getNodeReferences($path, $name);
}
public function getWeakReferences($path, $name = null)
{
return $this->getNodeReferences($path, $name, true);
}
/**
* @param string $path the path for which we need the references
* @param string $name the name of the referencing properties or null for all
* @param bool $weak_reference whether to get weak or strong references
*
* @return array list of paths to nodes that reference $path
*/
protected function getNodeReferences($path, $name = null, $weak_reference = false)
{
$path = $this->encodeAndValidatePathForDavex($path);
$identifier = $weak_reference ? 'weakreferences' : 'references';
$request = $this->getRequest(Request::PROPFIND, $path);
$request->setBody($this->buildPropfindRequest(['dcr:'.$identifier]));
$request->setDepth(0);
$dom = $request->executeDom();
$references = [];
foreach ($dom->getElementsByTagNameNS(self::NS_DCR, $identifier) as $node) {
foreach ($node->getElementsByTagNameNS(self::NS_DAV, 'href') as $ref) {
$refpath = str_replace($this->workspaceUriRoot, '', urldecode($ref->textContent));
$refpath = $this->removeTrailingSlash($refpath);
if (null === $name || PathHelper::getNodeName($refpath) === $name) {
$references[] = $refpath;
}
}
}
return $references;
}
/**
* Remove the trailing slash if present. Used for backend responses when
* jackrabbit is sloppy.
*
* @param string $path a path with potentially a trailing slash
*
* @return string the path guaranteed to not have a trailing slash
*/
private function removeTrailingSlash($path)
{
if (strlen($path) <= 1) {
return '/';
}
if ('/' !== $path[strlen($path) - 1]) {
// no trailing slash
return $path;
}
return substr($path, 0, strlen($path) - 1);
}
// VersioningInterface //
public function addVersionLabel($versionPath, $label, $moveLabel)
{
$versionPath = $this->encodeAndValidatePathForDavex($versionPath);
$action = 'add';
if ($moveLabel) {
$action = 'set';
}
$body = '<D:label xmlns:D="DAV:"><D:'.$action.'><D:label-name>'.$label.'</D:label-name></D:'.$action.'></D:label>';
$request = $this->getRequest(Request::LABEL, $versionPath);
$request->setBody($body);
try {
$request->execute(); // errors are checked in request
} catch (HTTPErrorException $e) {
if (409 == $e->getCode()) {
throw new LabelExistsVersionException($e->getMessage());
} else {
throw new RepositoryException($e->getMessage());
}
}
return;
}
public function removeVersionLabel($versionPath, $label)
{
$versionPath = $this->encodeAndValidatePathForDavex($versionPath);
$body = '<D:label xmlns:D="DAV:"><D:remove><D:label-name>'.$label.'</D:label-name></D:remove></D:label>';
$request = $this->getRequest(Request::LABEL, $versionPath);
$request->setBody($body);
$request->execute();
return;
}
public function checkinItem($path)
{
$path = $this->encodeAndValidatePathForDavex($path);
try {
$request = $this->getRequest(Request::CHECKIN, $path);
$curl = $request->execute(true);
if ($curl->getHeader('Location')) {
return $this->removeTrailingSlash(
$this->stripServerRootFromUri(urldecode($curl->getHeader('Location')))
);
}
} catch (HTTPErrorException $e) {
if (405 == $e->getCode()) {
throw new UnsupportedRepositoryOperationException();
}
throw new RepositoryException($e->getMessage());
}
throw new RepositoryException();
}
public function checkoutItem($path)
{
$path = $this->encodeAndValidatePathForDavex($path);
try {
$request = $this->getRequest(Request::CHECKOUT, $path);
$request->execute();
} catch (HTTPErrorException $e) {
if (405 == $e->getCode()) {
// TODO: when checking out a non-versionable node, we get here too. in that case the exception is very wrong
throw new UnsupportedRepositoryOperationException($e->getMessage());
}
throw new RepositoryException($e->getMessage());
}
return;
}
public function restoreItem($removeExisting, $versionPath, $path)
{
$path = $this->encodeAndValidatePathForDavex($path);
$body =
'<D:update xmlns:D="DAV:">
<D:version>
<D:href>'.$this->addWorkspacePathToUri($versionPath).'</D:href>
</D:version>
';
if ($removeExisting) {
$body .= '<dcr:removeexisting xmlns:dcr="http://www.day.com/jcr/webdav/1.0" />';
}
$body .= '</D:update>';
$request = $this->getRequest(Request::UPDATE, $path);
$request->setBody($body);
$request->execute(); // errors are checked in request
}
public function removeVersion($versionPath, $versionName)
{
$path = $this->encodeAndValidatePathForDavex($versionPath.'/'.$versionName);
$request = $this->getRequest(Request::DELETE, $path);
$resp = $request->execute();
return $resp;
}
// QueryTransport //
public function query(Query $query)
{
// TODO handle bind variables
$querystring = $query->getStatement();
$limit = $query->getLimit();
$offset = $query->getOffset();
$language = $query->getLanguage();
switch ($language) {
case QueryInterface::JCR_JQOM:
// for JQOM, fall through to SQL2
case QueryInterface::JCR_SQL2:
$ns = '';
$langElement = 'JCR-SQL2';
break;
case QueryInterface::XPATH:
$langElement = 'dcr:xpath';
$ns = 'xmlns:dcr="http://www.day.com/jcr/webdav/1.0"';
break;
case QueryInterface::SQL:
$langElement = 'dcr:sql';
$ns = 'xmlns:dcr="http://www.day.com/jcr/webdav/1.0"';
break;
default:
// this should be impossible as we check on creation already
throw new InvalidQueryException("Unsupported query language: $language");
}
$body = '<D:searchrequest '.$ns.' xmlns:D="DAV:"><'.$langElement.'><![CDATA['.$querystring.']]></'.$langElement.'>';
if (null !== $limit || null !== $offset) {
$body .= '<D:limit>';
if (null !== $limit) {
$body .= '<D:nresults>'.(int) $limit.'</D:nresults>';
}
if (null !== $offset) {
$body .= '<offset>'.(int) $offset.'</offset>';
}
$body .= '</D:limit>';
}
$body .= '</D:searchrequest>';
$path = $this->addWorkspacePathToUri('/');
$request = $this->getRequest(Request::SEARCH, $path);
$request->setBody($body);
$rawData = $request->execute();
$dom = new \DOMDocument();
$dom->loadXML($rawData);
$domXpath = new \DOMXPath($dom);
$rows = [];
foreach ($domXpath->query('D:response') as $row) {
$columns = [];
foreach ($row->getElementsByTagName('column') as $column) {
$sets = [];
foreach ($column->childNodes as $childNode) {
if ('dcr:value' == $childNode->tagName) {
$value = $this->getDcrValue($childNode);
// TODO if this bug is fixed, spaces may be urlencoded instead of the escape sequence: https://issues.apache.org/jira/browse/JCR-2997
// the following line fails for nodes with "_x0020 " in their name, changing that part to " x0020_"
// other characters like < and > are urlencoded, which seems to be handled by dom already.
if (is_string($value)) {
$value = str_replace('_x0020_', ' ', $value);
}
} else {
$value = $childNode->nodeValue;
}
$sets[$childNode->tagName] = $value;
}
if (!isset($sets['dcr:value'])) {
$sets['dcr:value'] = null;
}
$columns[] = $sets;
}
$rows[] = $columns;
}
return $rows;
}
public function getSupportedQueryLanguages()
{
return [
QueryInterface::JCR_SQL2,
QueryInterface::JCR_JQOM,
QueryInterface::XPATH,
QueryInterface::SQL,
];
}
/**
* Get the value of a dcr:value node in the right format specified by the
* dcr type.
*
* This uses PropertyType but takes into account the special case that
* boolean false is encoded as string "false" which is otherwise true in php.
*
* <dcr:value dcr:type="Boolean">false</dcr:value>
*
* @param \DOMElement $node a dcr:value xml element
*
* @return mixed the node value converted to the specified type
*/
private function getDcrValue(\DOMElement $node)
{
$type = $node->getAttribute('dcr:type');
if (PropertyType::TYPENAME_BOOLEAN == $type && 'false' == $node->nodeValue) {
return false;
}
return $this->valueConverter->convertType($node->nodeValue, PropertyType::valueFromName($type));
}
// WritingInterface //
public function deleteNodes(array $operations)
{
// Reverse sort the batch; work-around for problem with
// deleting same-name siblings. Not guaranteed to work
// across multiple calls to deleteNodes().
usort($operations, function ($a, $b) {
$aParts = [];
$bParts = [];
$regex = '/^(.+?)(?:\[(\d+)])?$/';
preg_match($regex, $a->srcPath, $aParts);
preg_match($regex, $b->srcPath, $bParts);
$aPath = $aParts[1];
$bPath = $bParts[1];
if ($aPath != $bPath) {
return strcmp($bPath, $aPath);
} else {
$aIndex = isset($aParts[2]) ? $aParts[2] : 1;
$bIndex = isset($bParts[2]) ? $bParts[2] : 1;
return $bIndex - $aIndex;
}
});
foreach ($operations as $operation) {
$this->deleteItem($operation->srcPath);
}
}
public function deleteProperties(array $operations)
{
foreach ($operations as $operation) {
$this->deleteItem($operation->srcPath);
}
}
public function deleteNodeImmediately($path)
{