forked from jackalope/jackalope
/
Client.php
executable file
·1499 lines (1352 loc) · 54.3 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
/**
* Class to handle the communication between Jackalope and Jackrabbit via Davex.
*
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License Version 2.0, January 2004
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @package jackalope
* @subpackage transport
*/
namespace Jackalope\Transport\Davex;
use PHPCR\PropertyType;
use Jackalope\Transport\curl;
use Jackalope\TransactionalTransportInterface;
use Jackalope\NotImplementedException;
use DOMDocument;
use Jackalope\NodeType\NodeTypeManager;
/**
* Connection to one Jackrabbit server.
*
* Once the login method has been called, the workspace is set and can not be changed anymore.
*
* @package jackalope
* @subpackage transport
*/
class Client implements TransactionalTransportInterface
{
/**
* Description of the namspace to be used for communication with the server.
* @var string
*/
const NS_DCR = 'http://www.day.com/jcr/webdav/1.0';
/**
* Identifier of the used namespace.
* @var string
*/
const NS_DAV = 'DAV:';
/**
* Representation of a XML string header.
*
* @todo TODO: seems not to be used anymore.
*
* @var string
*/
const REGISTERED_NAMESPACES =
'<?xml version="1.0" encoding="UTF-8"?>< xmlns:dcr="http://www.day.com/jcr/webdav/1.0"/>';
/**
* The factory to instantiate objects
* @var Factory
*/
protected $factory;
/**
* 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
* @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 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 or else.
* @var \PHPCR\CredentialsInterface
*/
protected $credentials;
/**
* The cURL resource handle
* @var curl
*/
protected $curl = null;
/**
* A list of additional HTTP headers to be sent on each request
* @var array[]string
*/
protected $defaultHeaders = array();
/**
* @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;
/**
* The transaction token received by a LOCKing request
*
* Is FALSE while no transaction running.
* @var string|FALSE
*/
protected $transactionToken = false;
/**
* Create a transport pointing to a server url.
*
* @param object $factory an object factory implementing "get" as described in \Jackalope\Factory.
* @param serverUri location of the server
*/
public function __construct($factory, $serverUri)
{
$this->factory = $factory;
// append a slash if not there
if ('/' !== substr($serverUri, -1)) {
$serverUri .= '/';
}
$this->server = $serverUri;
}
/**
* Tidies up the current cUrl connection.
*/
public function __destruct()
{
if ($this->curl) {
$this->curl->close();
}
}
/**
* Add a HTTP header which is sent on each Request
*/
public function addDefaultHeader($header)
{
$this->defaultHeaders[] = $header;
}
/**
* If you want to send the "Expect: 100-continue" header on larger
* PUT and POST requests, set this to true
* Disabled by default
*
* @param bool $send
*/
public function sendExpect($send = true)
{
$this->sendExpect = $send;
}
/**
* Opens a cURL session if not yet one open.
*
* @return Jackalope\Transport\Davex\Request The Request
*/
protected function getRequest($method, $uri)
{
if (!is_array($uri)) {
$uri = array($uri => $uri);
}
if (is_null($this->curl)) {
// lazy init curl
$this->curl = new curl();
} else if ($this->curl === false) {
// 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 ($method for ".var_export($uri,true).")");
}
foreach ($uri as $key => $row) {
$uri[$key] = $this->addWorkspacePathToUri($row);
}
$request = $this->factory->get('Transport\Davex\Request', array($this->curl, $method, $uri));
$request->setCredentials($this->credentials);
foreach ($this->defaultHeaders as $header) {
$request->addHeader($header);
}
if (!$this->sendExpect) {
$request->addHeader("Expect:");
}
return $request;
}
/**
* Set this transport to a specific credential and a workspace.
*
* This can only be called once. To connect to another workspace or with
* another credential, use a fresh instance of transport.
*
* @param \PHPCR\CredentialsInterface $credentials A set of attributes to be used to login per example.
* @param string $workspaceName The workspace name for this transport.
* @return boolean True on success, exceptions on failure.
*
* @throws \PHPCR\LoginException if authentication or authorization (for the specified workspace) fails
* @throws \PHPCR\NoSuchWorkspaceException if the specified workspaceName is not recognized
* @throws \PHPCR\RepositoryException if another error occurs
*/
public function login(\PHPCR\CredentialsInterface $credentials, $workspaceName)
{
if ($this->credentials) {
throw new \PHPCR\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 \PHPCR\SimpleCredentials) {
throw new \PHPCR\LoginException('Unkown Credentials Type: '.get_class($credentials));
}
$this->credentials = $credentials;
$this->workspace = $workspaceName;
$this->workspaceUri = $this->server . $workspaceName;
$this->workspaceUriRoot = $this->workspaceUri . "/jcr:root";
if (!$this->checkLoginOnServer ) {
return true;
}
$request = $this->getRequest(Request::PROPFIND, $this->workspaceUri);
$request->setBody($this->buildPropfindRequest(array('D:workspace', 'dcr:workspaceName')));
$dom = $request->executeDom();
$set = $dom->getElementsByTagNameNS(self::NS_DCR, 'workspaceName');
if ($set->length != 1) {
throw new \PHPCR\RepositoryException('Unexpected answer from server: '.$dom->saveXML());
}
if ($set->item(0)->textContent != $this->workspace) {
throw new \PHPCR\RepositoryException('Wrong workspace in answer from server: '.$dom->saveXML());
}
return true;
}
/**
* Releases all resources associated with this Session.
*
* This method should be called when a Session is no longer needed.
*
* @return void
*/
public function logout()
{
$this->curl->close();
$this->curl = false;
}
/**
* Change the way Jackalope works when getting a session
* By default, it sends a PROPFIND to the server, to see if the repository exists
* You can disable that with setting it to false, then an error only occurs later
* if the repository doesn't exits
*
* @return void
*/
public function setCheckLoginOnServer($bool)
{
$this->checkLoginOnServer = $bool;
}
/**
* Get the repository descriptors from the jackrabbit server
* This happens without login or accessing a specific workspace.
*
* @return Array with name => Value for the descriptors
* @throws \PHPCR\RepositoryException if error occurs
*/
public function getRepositoryDescriptors()
{
$request = $this->getRequest(Request::REPORT, $this->server);
$request->setBody($this->buildReportRequest('dcr:repositorydescriptors'));
$dom = $request->executeDom();
if ($dom->firstChild->localName != 'repositorydescriptors-report'
|| $dom->firstChild->namespaceURI != self::NS_DCR
) {
throw new \PHPCR\RepositoryException('Error talking to the backend. '.$dom->saveXML());
}
$descs = $dom->getElementsByTagNameNS(self::NS_DCR, 'descriptor');
$descriptors = array();
foreach ($descs as $desc) {
$values = array();
foreach ($desc->getElementsByTagNameNS(self::NS_DCR, 'descriptorvalue') as $value) {
$values[] = $value->textContent;
}
if ($desc->childNodes->length == 2) {
//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?
$descriptors[$desc->firstChild->textContent] = $values[0];
} else {
$descriptors[$desc->firstChild->textContent] = $values;
}
}
return $descriptors;
}
/**
* Creates a new Workspace with the specified name. The new workspace is
* empty, meaning it contains only root node.
*
* If srcWorkspace is given:
* Creates a new Workspace with the specified name initialized with a
* clone of the content of the workspace srcWorkspace. Semantically,
* this method is equivalent to creating a new workspace and manually
* cloning srcWorkspace to it; however, this method may assist some
* implementations in optimizing subsequent Node.update and Node.merge
* calls between the new workspace and its source.
*
* The new workspace can be accessed through a login specifying its name.
*
* @param string $name A String, the name of the new workspace.
* @param string $srcWorkspace The name of the workspace from which the new workspace is to be cloned.
* @return void
* @throws \PHPCR\AccessDeniedException if the session through which this Workspace object was acquired does not have sufficient access to create the new workspace.
* @throws \PHPCR\UnsupportedRepositoryOperationException if the repository does not support the creation of workspaces.
* @throws \PHPCR\NoSuchWorkspaceException if $srcWorkspace does not exist.
* @throws \PHPCR\RepositoryException if another error occurs.
* @api
*/
public function createWorkspace($name, $srcWorkspace = null)
{
throw new \Jackalope\NotImplementedException();
}
/**
* Returns the accessible workspace names
*
* @return array Set of workspaces to work on.
*/
public function getAccessibleWorkspaceNames()
{
$request = $this->getRequest(Request::PROPFIND, $this->server);
$request->setBody($this->buildPropfindRequest(array('D:workspace')));
$request->setDepth(1);
$dom = $request->executeDom();
$workspaces = array();
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);
}
/**
* Get the node from an absolute path
*
* @param string $path Absolute path to the node.
* @return array associative array for the node (decoded from json with associative = true)
*
* @throws \PHPCR\ItemNotFoundException If the item at path was not found
* @throws \PHPCR\RepositoryException if not logged in
*/
public function getNode($path)
{
$path = $this->encodePathForDavex($path);
$path .= '.0.json';
$request = $this->getRequest(Request::GET, $path);
$request->setTransactionId($this->transactionToken);
try {
return $request->executeJson();
} catch (\PHPCR\PathNotFoundException $e) {
throw new \PHPCR\ItemNotFoundException($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Get the nodes from an array of absolute paths
*
* @param array $path Absolute paths to the nodes.
* @return array associative array for the node (decoded from json with associative = true)
*
* @throws \PHPCR\RepositoryException if not logged in
*/
public function getNodes($paths)
{
if (count($paths) == 0) {
return array();
}
$url = array_shift($paths);
if (count($paths) == 0) {
try {
return array($url => $this->getNode($url));
} catch (\PHPCR\ItemNotFoundException $e) {
return array();
}
}
$body = array();
$url = $this->encodePathForDavex($url).".0.json";
foreach ($paths as $path) {
$body[] = http_build_query(array(":get"=>$path));
}
$body = implode("&",$body);
$request = $this->getRequest(Request::POST, $url);
$request->setBody($body);
$request->setContentType('application/x-www-form-urlencoded');
$request->setTransactionId($this->transactionToken);
try {
$data = $request->executeJson();
return $data->nodes;
} catch (\PHPCR\PathNotFoundException $e) {
throw new \PHPCR\ItemNotFoundException($e->getMessage(), $e->getCode(), $e);
} catch (\PHPCR\RepositoryException $e) {
if ($e->getMessage() == 'HTTP 403: Prefix must not be empty (org.apache.jackrabbit.spi.commons.conversion.IllegalNameException)') {
throw new \PHPCR\UnsupportedRepositoryOperationException("Jackalope currently needs a patched jackrabbit for Session->getNodes() to work. Until our patches make it into the official distribution, see https://github.com/jackalope/jackrabbit/blob/2.2-jackalope/README.jackalope.patches.md for details and downloads.");
}
throw $e;
}
}
/**
* Get the property stored at an absolute path.
*
* Same format as getNode with just one property.
*
* @return array associative array with the property value.
*/
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)
*/
}
/**
* Retrieves a binary value resp. multiple values
*
* @param $path the path to the binary property
*
* @return mixed decoded stream or array of streams
*/
public function getBinaryStream($path)
{
$path = $this->encodePathForDavex($path);
$request = $this->getRequest(Request::GET, $path);
$request->setTransactionId($this->transactionToken);
$curl = $request->execute(true);
switch($curl->getHeader('Content-Type')) {
case 'text/xml; charset=utf-8':
return $this->decodeBinaryDom($curl->getResponse());
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 \PHPCR\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 \PHPCR\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 \PHPCR\RepositoryException("Failed to load xml data:\n\n$xml");
}
$ret = array();
foreach ($dom->getElementsByTagNameNS(self::NS_DCR, 'values') as $node) {
foreach ($node->getElementsByTagNameNS(self::NS_DCR, 'value') as $value) {
if ($value->getAttributeNS(self::NS_DCR, 'type') != \PHPCR\PropertyType::TYPENAME_BINARY) {
throw new \PHPCR\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;
}
/**
* Returns the path of all accessible REFERENCE properties in the workspace that point to the node
*
* @param string $path
* @param string $name name of referring REFERENCE properties to be returned; if null then all referring REFERENCEs are returned
* @return array
*/
public function getReferences($path, $name = null)
{
return $this->getNodeReferences($path, $name);
}
/**
* Returns the path of all accessible WEAKREFERENCE properties in the workspace that point to the node
*
* @param string $path
* @param string $name name of referring WEAKREFERENCE properties to be returned; if null then all referring WEAKREFERENCEs are returned
* @return array
*/
public function getWeakReferences($path, $name = null)
{
return $this->getNodeReferences($path, $name, true);
}
/**
* Returns the path of all accessible reference properties in the workspace that point to the node.
* If $weak_reference is false (default) only the REFERENCE properties are returned, if it is true, only WEAKREFERENCEs.
* @param string $path
* @param string $name name of referring WEAKREFERENCE properties to be returned; if null then all referring WEAKREFERENCEs are returned
* @param boolean $weak_reference If true return only WEAKREFERENCEs, otherwise only REFERENCEs
* @return array
*/
protected function getNodeReferences($path, $name = null, $weak_reference = false)
{
$path = $this->encodePathForDavex($path);
$identifier = $weak_reference ? 'weakreferences' : 'references';
$request = $this->getRequest(Request::PROPFIND, $path);
$request->setTransactionId($this->transactionToken);
$request->setBody($this->buildPropfindRequest(array('dcr:'.$identifier)));
$request->setDepth(0);
$dom = $request->executeDom();
$references = array();
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));
if ($name === null || basename($refpath) === $name) {
$references[] = str_replace($this->workspaceUriRoot, '', urldecode($ref->textContent));
}
}
}
return $references;
}
/**
* Check-in item at path.
*
* @param string $path
* @return string path to the new version
*
* @throws PHPCR\UnsupportedRepositoryOperationException
* @throws PHPCR\RepositoryException
*/
public function checkinItem($path)
{
$path = $this->encodePathForDavex($path);
try {
$request = $this->getRequest(Request::CHECKIN, $path);
$request->setTransactionId($this->transactionToken);
$curl = $request->execute(true);
if ($curl->getHeader("Location")) {
return $this->stripServerRootFromUri(urldecode($curl->getHeader("Location")));
}
} catch (\Jackalope\Transport\Davex\HTTPErrorException $e) {
if ($e->getCode() == 405) {
throw new \PHPCR\UnsupportedRepositoryOperationException();
}
throw new \PHPCR\RepositoryException($e->getMessage());
}
// TODO: not sure what this means
throw new \PHPCR\RepositoryException();
}
/**
* Check-out item at path.
*
* @param string $path
* @return void
*
* @throws PHPCR\UnsupportedRepositoryOperationException
* @throws PHPCR\RepositoryException
*/
public function checkoutItem($path)
{
$path = $this->encodePathForDavex($path);
try {
$request = $this->getRequest(Request::CHECKOUT, $path);
$request->setTransactionId($this->transactionToken);
$request->execute();
} catch (\Jackalope\Transport\Davex\HTTPErrorException $e) {
if ($e->getCode() == 405) {
// TODO: when checking out a non-versionable node, we get here too. in that case the exception is very wrong
throw new \PHPCR\UnsupportedRepositoryOperationException($e->getMessage());
}
throw new \PHPCR\RepositoryException($e->getMessage());
}
return;
}
public function restoreItem($removeExisting, $versionPath, $path)
{
$path = $this->encodePathForDavex($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->setTransactionId($this->transactionToken);
$request->execute(); // errors are checked in request
}
public function getVersionHistory($path)
{
$path = $this->encodePathForDavex($path);
$request = $this->getRequest(Request::GET, $path."/jcr:versionHistory");
$request->setTransactionId($this->transactionToken);
$resp = $request->execute();
return $resp;
}
public function query(\PHPCR\Query\QueryInterface $query)
{
$querystring = $query->getStatementSql2();
$limit = $query->getLimit();
$offset = $query->getOffset();
$body ='<D:searchrequest xmlns:D="DAV:"><JCR-SQL2><![CDATA['.$querystring.']]></JCR-SQL2>';
if (null !== $limit || null !== $limit) {
$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->setTransactionId($this->transactionToken);
$request->setBody($body);
$rawData = $request->execute();
$dom = new \DOMDocument();
$dom->loadXML($rawData);
$rows = array();
foreach ($dom->getElementsByTagName('response') as $row) {
$columns = array();
foreach ($row->getElementsByTagName('column') as $column) {
$sets = array();
foreach ($column->childNodes as $childNode) {
$sets[$childNode->tagName] = $childNode->nodeValue;
}
// 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.
$sets['dcr:value'] = str_replace('_x0020_', ' ', $sets['dcr:value']);
$columns[] = $sets;
}
$rows[] = $columns;
}
return $rows;
}
/**
* Deletes a node and the whole subtree under it
*
* @param string $path Absolute path to the node
* @return bool true on success
*
* @throws \PHPCR\RepositoryException if not logged in
*/
public function deleteNode($path)
{
$path = $this->encodePathForDavex($path);
$request = $this->getRequest(Request::DELETE, $path);
$request->setTransactionId($this->transactionToken);
$request->execute();
return true;
}
/**
* Deletes a property
*
* @param string $path Absolute path to identify a special item.
* @return bool true on success
*
* @throws \PHPCR\RepositoryException if not logged in
*/
public function deleteProperty($path)
{
return $this->deleteNode($path);
}
/**
* Copies a Node from src to dst
*
* @param string $srcAbsPath Absolute source path to the node
* @param string $dstAbsPath Absolute destination path (must include the new node name)
* @param string $srcWorkspace The source workspace where the node can be found or null for current
* @return void
*
* @link http://www.ietf.org/rfc/rfc2518.txt
* @see \Jackalope\Workspace::copy
*/
public function copyNode($srcAbsPath, $dstAbsPath, $srcWorkspace = null)
{
$srcAbsPath = $this->encodePathForDavex($srcAbsPath);
$dstAbsPath = $this->encodePathForDavex($dstAbsPath);
if ($srcWorkspace) {
$srcAbsPath = $this->server . $srcAbsPath;
}
$request = $this->getRequest(Request::COPY, $srcAbsPath);
$request->setDepth(Request::INFINITY);
$request->addHeader('Destination: '.$this->addWorkspacePathToUri($dstAbsPath));
$request->setTransactionId($this->transactionToken);
$request->execute();
}
/**
* Moves a node from src to dst
*
* @param string $srcAbsPath Absolute source path to the node
* @param string $dstAbsPath Absolute destination path (must NOT include the new node name)
* @return void
*
* @link http://www.ietf.org/rfc/rfc2518.txt
*/
public function moveNode($srcAbsPath, $dstAbsPath)
{
$srcAbsPath = $this->encodePathForDavex($srcAbsPath);
$dstAbsPath = $this->encodePathForDavex($dstAbsPath);
$request = $this->getRequest(Request::MOVE, $srcAbsPath);
$request->setDepth(Request::INFINITY);
$request->addHeader('Destination: '.$this->addWorkspacePathToUri($dstAbsPath));
$request->setTransactionId($this->transactionToken);
$request->execute();
}
public function cloneFrom($srcWorkspace, $srcAbsPath, $destAbsPath, $removeExisting)
{
throw new NotImplementedException();
}
/**
* Recursively store a node and its children to the given absolute path.
*
* The basename of the path is the name of the node
*
* @param NodeInterface $node
*
* @return bool true on success
*
* @throws \PHPCR\RepositoryException if not logged in
*/
public function storeNode(\PHPCR\NodeInterface $node)
{
$path = $node->getPath();
$path = $this->encodePathForDavex($path);
$buffer = array();
$body = '<?xml version="1.0" encoding="UTF-8"?>';
$body .= $this->createNodeMarkup($path, $node->getProperties(), $node->getNodes(), $buffer);
$request = $this->getRequest(Request::MKCOL, $path);
$request->setBody($body);
$request->setTransactionId($this->transactionToken);
$request->execute();
// store single-valued multivalue properties separately
foreach ($buffer as $path => $body) {
$request = $this->getRequest(Request::PUT, $path);
$request->setBody($body);
$request->setTransactionId($this->transactionToken);
$request->execute();
}
return true;
}
/**
* create the node markup and a list of value dispatches for multivalue properties
*
* this is a recursive function.
*
* @param string $path path to the current node, basename is the name of the node
* @param array $properties of this node
* @param array $children nodes of this node
* @param array $buffer list of xml strings to set multivalue properties
*/
protected function createNodeMarkup($path, $properties, $children, array &$buffer)
{
$body = '<sv:node xmlns:sv="http://www.jcp.org/jcr/sv/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0" sv:name="'.basename($path).'">';
foreach ($properties as $name => $property) {
$type = \PHPCR\PropertyType::nameFromValue($property->getType());
$nativeValue = $property->getValueForStorage();
$valueBody = '';
// handle multivalue properties
if (is_array($nativeValue)) {
// multivalue properties with many rows can be inlined
if (count($nativeValue) > 1 || $name === 'jcr:mixinTypes') {
foreach ($nativeValue as $value) {
$valueBody .= '<sv:value>'.$this->propertyToXmlString($value, $type).'</sv:value>';
}
} else {
// multivalue properties with just one value have to be saved separately to transmit the multivalue info
$buffer[$path.'/'.$name] = '<?xml version="1.0" encoding="UTF-8"?><dcr:values xmlns:dcr="http://www.day.com/jcr/webdav/1.0">'.
'<dcr:value dcr:type="'.$type.'">'.$this->propertyToXmlString(reset($nativeValue), $type).'</dcr:value>'.
'</dcr:values>';
continue;
}
} else {
// handle single value properties
$valueBody = '<sv:value>'.$this->propertyToXmlString($nativeValue, $type).'</sv:value>';
}
$body .= '<sv:property sv:name="'.$name.'" sv:type="'.$type.'">'.$valueBody.'</sv:property>';
}
foreach ($children as $name => $node) {
$body .= $this->createNodeMarkup($path.'/'.$name, $node->getProperties(), $node->getNodes(), $buffer);
}
return $body . '</sv:node>';
}
/**
* Stores a property to the given absolute path
*
* @param string $path Absolute path to identify a specific property.
* @param \PHPCR\PropertyInterface
* @return bool true on success
*
* @throws \PHPCR\RepositoryException if not logged in
*/
public function storeProperty(\PHPCR\PropertyInterface $property)
{
$path = $property->getPath();
$path = $this->encodePathForDavex($path);
$typeid = $property->getType();
$type = PropertyType::nameFromValue($typeid);
$nativeValue = $property->getValueForStorage();
$request = $this->getRequest(Request::PUT, $path);
if ($property->getName() === 'jcr:mixinTypes') {
$uri = $this->addWorkspacePathToUri(dirname($path) === '\\' ? '/' : dirname($path));
$request->setUri($uri);
$request->setMethod(Request::PROPPATCH);
$body = '<?xml version="1.0" encoding="UTF-8"?>'.
'<D:propertyupdate xmlns:D="DAV:">'.
'<D:set>'.
'<D:prop>'.
'<dcr:mixinnodetypes xmlns:dcr="http://www.day.com/jcr/webdav/1.0">';
foreach ($nativeValue as $value) {
$body .= '<dcr:nodetype><dcr:nodetypename>'.$value.'</dcr:nodetypename></dcr:nodetype>';
}
$body .= '</dcr:mixinnodetypes>'.
'</D:prop>'.
'</D:set>'.
'</D:propertyupdate>';
} elseif (is_array($nativeValue)) {
$body = '<?xml version="1.0" encoding="UTF-8"?>'.
'<jcr:values xmlns:jcr="http://www.day.com/jcr/webdav/1.0">';
foreach ($nativeValue as $value) {
$body .= '<jcr:value jcr:type="'.$type.'">'.$this->propertyToXmlString($value, $type).'</jcr:value>';
}
$body .= '</jcr:values>';
} else {
$body = $this->propertyToRawString($nativeValue, $type);
$request->setContentType('jcr-value/'.strtolower($type));
}
$request->setBody($body);
$request->setTransactionId($this->transactionToken);
$request->execute();
return true;
}
/**
* This method is used when building an XML of the properties
*
* @param $value
* @param $type
* @return mixed|string
*/
protected function propertyToXmlString($value, $type)
{
switch ($type) {
case \PHPCR\PropertyType::TYPENAME_BOOLEAN:
return $value ? 'true' : 'false';
case \PHPCR\PropertyType::TYPENAME_DATE:
return PropertyType::convertType($value, PropertyType::STRING);
case \PHPCR\PropertyType::TYPENAME_BINARY:
return base64_encode(stream_get_contents($value));
case \PHPCR\PropertyType::TYPENAME_UNDEFINED:
case \PHPCR\PropertyType::TYPENAME_STRING:
case \PHPCR\PropertyType::TYPENAME_URI:
$value = str_replace(']]>',']]]]><![CDATA[>',$value);
return '<![CDATA['.$value.']]>';
}
return $value;
}
/**
* This method is used to directly set a property
*
* @param $value
* @param $type
* @return mixed|string
*/
protected function propertyToRawString($value, $type)
{
switch ($type) {
case \PHPCR\PropertyType::TYPENAME_BINARY:
$ret = stream_get_contents($value);