/
Client.php
2639 lines (2268 loc) · 94.6 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\DoctrineDBAL;
use PHPCR\LoginException;
use PHPCR\NodeType\NodeDefinitionInterface;
use PHPCR\NodeType\NodeTypeExistsException;
use PHPCR\NodeType\PropertyDefinitionInterface;
use PHPCR\RepositoryInterface;
use PHPCR\NamespaceRegistryInterface;
use PHPCR\CredentialsInterface;
use PHPCR\PropertyType;
use PHPCR\Query\QOM\QueryObjectModelInterface;
use PHPCR\Query\QOM\SelectorInterface;
use PHPCR\Query\QueryInterface;
use PHPCR\RepositoryException;
use PHPCR\NamespaceException;
use PHPCR\NoSuchWorkspaceException;
use PHPCR\ItemExistsException;
use PHPCR\ItemNotFoundException;
use PHPCR\ReferentialIntegrityException;
use PHPCR\SimpleCredentials;
use PHPCR\PathNotFoundException;
use PHPCR\Query\InvalidQueryException;
use PHPCR\NodeType\ConstraintViolationException;
use PHPCR\Util\QOM\Sql2ToQomQueryConverter;
use PHPCR\Util\ValueConverter;
use PHPCR\Util\UUIDHelper;
use PHPCR\Util\PathHelper;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\PDOConnection;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Jackalope\Node;
use Jackalope\Property;
use Jackalope\Query\Query;
use Jackalope\Transport\MoveNodeOperation;
use Jackalope\Transport\BaseTransport;
use Jackalope\Transport\QueryInterface as QueryTransport;
use Jackalope\Transport\WritingInterface;
use Jackalope\Transport\WorkspaceManagementInterface;
use Jackalope\Transport\NodeTypeManagementInterface;
use Jackalope\Transport\TransactionInterface;
use Jackalope\Transport\StandardNodeTypes;
use Jackalope\Transport\DoctrineDBAL\Query\QOMWalker;
use Jackalope\NodeType\NodeTypeManager;
use Jackalope\NodeType\NodeTypeDefinition;
use Jackalope\FactoryInterface;
use Jackalope\NotImplementedException;
use Jackalope\NodeType\NodeProcessor;
/**
* Class to handle the communication between Jackalope and RDBMS via Doctrine DBAL.
*
* @license http://www.apache.org/licenses Apache License Version 2.0, January 2004
* @license http://opensource.org/licenses/MIT MIT License
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
*/
class Client extends BaseTransport implements QueryTransport, WritingInterface, WorkspaceManagementInterface, NodeTypeManagementInterface, TransactionInterface
{
/**
* SQlite can only handle a maximum of 999 parameters inside an IN statement
* see https://github.com/jackalope/jackalope-doctrine-dbal/pull/149/files#diff-a3a0165ed79ca1ba3513ec5ecd59ec56R707
*/
const SQLITE_MAXIMUM_IN_PARAM_COUNT = 999;
/**
* The factory to instantiate objects
* @var FactoryInterface
*/
protected $factory;
/**
* @var ValueConverter
*/
protected $valueConverter;
/**
* @var Connection
*/
private $conn;
/**
* @var \Closure
*/
private $uuidGenerator;
/**
* @var bool
*/
private $loggedIn = false;
/**
* @var SimpleCredentials
*/
private $credentials;
/**
* @var string
*/
protected $workspaceName;
/**
* @var array
*/
private $nodeIdentifiers = array();
/**
* @var NodeTypeManager
*/
private $nodeTypeManager;
/**
* @var bool
*/
protected $inTransaction = false;
/**
* Check if an initial request on login 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
*/
private $checkLoginOnServer = true;
/**
* Using an ArrayObject here so that we can pass this into the NodeProcessor by reference more elegantly
*
* @var null|\ArrayObject
*/
protected $namespaces;
/**
* @var null|array The namespaces at initial state when making changes to the namespaces, in case of rollback.
*/
private $originalNamespaces;
/**
* The core namespaces defined in JCR
*
* @var array
*/
private $coreNamespaces = array(
NamespaceRegistryInterface::PREFIX_EMPTY => NamespaceRegistryInterface::NAMESPACE_EMPTY,
NamespaceRegistryInterface::PREFIX_JCR => NamespaceRegistryInterface::NAMESPACE_JCR,
NamespaceRegistryInterface::PREFIX_NT => NamespaceRegistryInterface::NAMESPACE_NT,
NamespaceRegistryInterface::PREFIX_MIX => NamespaceRegistryInterface::NAMESPACE_MIX,
NamespaceRegistryInterface::PREFIX_XML => NamespaceRegistryInterface::NAMESPACE_XML,
NamespaceRegistryInterface::PREFIX_SV => NamespaceRegistryInterface::NAMESPACE_SV,
);
/**
* @var string|null
*/
private $sequenceNodeName;
/**
* @var string|null
*/
private $sequenceTypeName;
/**
* @var array
*/
private $referencesToUpdate = array();
/**
* @var array
*/
private $referenceTables = array(
PropertyType::REFERENCE => 'phpcr_nodes_references',
PropertyType::WEAKREFERENCE => 'phpcr_nodes_weakreferences',
);
/**
* @var array
*/
private $referencesToDelete = array();
/**
* @var boolean
*/
private $connectionInitialized = false;
/**
* @var NodeProcessor
*/
private $nodeProcessor;
/**
* @param FactoryInterface $factory
* @param Connection $conn
*/
public function __construct(FactoryInterface $factory, Connection $conn)
{
$this->factory = $factory;
$this->valueConverter = $this->factory->get('PHPCR\Util\ValueConverter');
$this->conn = $conn;
}
/**
* @TODO: move to "SqlitePlatform" and rename to "registerExtraFunctions"?
*
* @param PDOConnection $sqliteConnection
*
* @return Client
*/
private function registerSqliteFunctions(PDOConnection $sqliteConnection)
{
$sqliteConnection->sqliteCreateFunction('EXTRACTVALUE', function ($string, $expression) {
if (null === $string) {
return null;
}
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->loadXML($string);
$xpath = new \DOMXPath($dom);
$list = $xpath->evaluate($expression);
if (!is_object($list)) {
return $list;
}
// @TODO: don't know if there are expressions returning more then one row
if ($list->length > 0) {
// @TODO: why it can happen that we do not have a type? https://github.com/phpcr/phpcr-api-tests/pull/132
$type = is_object($list->item(0)->parentNode->attributes->getNamedItem('type'))
? $list->item(0)->parentNode->attributes->getNamedItem('type')->value
: null;
$content = $list->item(0)->textContent;
switch ($type) {
case 'long':
return (int) $content;
break;
case 'double':
return (double) $content;
break;
default:
return $content;
}
}
// @TODO: don't know if return value is right
return null;
}, 2);
$sqliteConnection->sqliteCreateFunction('CONCAT', function () {
return implode('', func_get_args());
});
return $this;
}
/**
* @return Connection
*/
public function getConnection()
{
$this->initConnection();
return $this->conn;
}
/**
* Set the UUID generator to use. If not set, the phpcr-utils UUIDHelper
* will be used.
*
* @param callable $generator
*/
public function setUuidGenerator(\Closure $generator)
{
$this->uuidGenerator = $generator;
}
/**
* @return callable a uuid generator function.
*/
protected function getUuidGenerator()
{
if (!$this->uuidGenerator) {
$this->uuidGenerator = function () {
return UUIDHelper::generateUUID();
};
}
return $this->uuidGenerator;
}
/**
* @return string a universally unique id.
*/
protected function generateUuid()
{
// php 5.3 compatibility, no direct execution of this function.
$g = $this->getUuidGenerator();
return $g();
}
/**
* {@inheritDoc}
*
*/
public function createWorkspace($name, $srcWorkspace = null)
{
if (null !== $srcWorkspace) {
throw new NotImplementedException('Creating workspace as clone of existing workspace not supported');
}
if ($this->workspaceExists($name)) {
throw new RepositoryException("Workspace '$name' already exists");
}
try {
$this->getConnection()->insert('phpcr_workspaces', array('name' => $name));
} catch (\Exception $e) {
throw new RepositoryException("Couldn't create Workspace '$name': ".$e->getMessage(), 0, $e);
}
$this->getConnection()->insert('phpcr_nodes', array(
'path' => '/',
'parent' => '',
'workspace_name'=> $name,
'identifier' => $this->generateUuid(),
'type' => 'nt:unstructured',
'local_name' => '',
'namespace' => '',
'props' => '<?xml version="1.0" encoding="UTF-8"?>
<sv:node xmlns:mix="http://www.jcp.org/jcr/mix/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:sv="http://www.jcp.org/jcr/sv/1.0" xmlns:rep="internal" />',
// TODO compute proper value
'depth' => 0,
));
}
/**
* {@inheritDoc}
*/
public function deleteWorkspace($name)
{
if (!$this->workspaceExists($name)) {
throw new RepositoryException("Workspace '$name' cannot be
deleted as it does not exist");
}
try {
$this->getConnection()->delete('phpcr_workspaces', array('name' => $name));
} catch (\Exception $e) {
throw new RepositoryException("Couldn't delete workspace '$name': "
.$e->getMessage(), 0, $e);
}
try {
$this->getConnection()->delete('phpcr_nodes', array('workspace_name'=>
$name));
} catch (\Exception $e) {
throw new RepositoryException("Couldn't delete nodes in workspace
'$name': ".$e->getMessage(), 0, $e);
}
try {
$this->getConnection()->delete('phpcr_binarydata', array('workspace_name'=>
$name));
} catch (\Exception $e) {
throw new RepositoryException("Couldn't delete binary data in
workspace '$name': ".$e->getMessage(), 0, $e);
}
}
/**
* {@inheritDoc}
*/
public function login(CredentialsInterface $credentials = null, $workspaceName = null)
{
$this->credentials = $credentials;
$this->workspaceName = $workspaceName ?: 'default';
if (!$this->checkLoginOnServer) {
return $this->workspaceName;
}
if (!$this->workspaceExists($this->workspaceName)) {
if ('default' !== $this->workspaceName) {
throw new NoSuchWorkspaceException("Requested workspace: '{$this->workspaceName}'");
}
// create default workspace if it not exists
$this->createWorkspace($this->workspaceName);
}
$this->loggedIn = true;
return $this->workspaceName;
}
/**
* {@inheritDoc}
*/
public function logout()
{
if ($this->loggedIn) {
$this->loggedIn = false;
$this->conn->close();
$this->conn = null;
}
}
/**
* Configure whether to check if we are logged in before doing a request.
*
* Will improve error reporting at the cost of some round trips.
*/
public function setCheckLoginOnServer($bool)
{
$this->checkLoginOnServer = $bool;
}
protected function workspaceExists($workspaceName)
{
try {
$query = 'SELECT 1 FROM phpcr_workspaces WHERE name = ?';
$result = $this->getConnection()->fetchColumn($query, array($workspaceName));
} catch (\Exception $e) {
if ($e instanceof DBALException || $e instanceof \PDOException) {
if (1045 == $e->getCode()) {
throw new LoginException('Access denied with your credentials: '.$e->getMessage());
}
if ('42S02' == $e->getCode()) {
throw new RepositoryException('You did not properly set up the database for the repository. See README.md for more information. Message from backend: '.$e->getMessage());
}
throw new RepositoryException('Unexpected error talking to the backend: '.$e->getMessage(), 0, $e);
}
throw $e;
}
return $result;
}
/**
* Ensure that we are currently logged in, executing the login in case we
* did lazy login.
*
* @throws RepositoryException if this transport is not logged in.
*/
protected function assertLoggedIn()
{
if (!$this->loggedIn) {
if (!$this->checkLoginOnServer && $this->workspaceName) {
$this->checkLoginOnServer = true;
if ($this->login($this->credentials, $this->workspaceName)) {
return;
}
}
throw new RepositoryException('You need to be logged in for this operation');
}
}
/**
* {@inheritDoc}
*/
public function getRepositoryDescriptors()
{
return array(
RepositoryInterface::IDENTIFIER_STABILITY => RepositoryInterface::IDENTIFIER_STABILITY_INDEFINITE_DURATION,
RepositoryInterface::REP_NAME_DESC => 'jackalope_doctrine_dbal',
RepositoryInterface::REP_VENDOR_DESC => 'Jackalope Community',
RepositoryInterface::REP_VENDOR_URL_DESC => 'http://github.com/jackalope',
RepositoryInterface::REP_VERSION_DESC => '1.1.0-DEV',
RepositoryInterface::SPEC_NAME_DESC => 'Content Repository for PHP',
RepositoryInterface::SPEC_VERSION_DESC => '2.1',
RepositoryInterface::NODE_TYPE_MANAGEMENT_AUTOCREATED_DEFINITIONS_SUPPORTED => true,
RepositoryInterface::NODE_TYPE_MANAGEMENT_INHERITANCE => RepositoryInterface::NODE_TYPE_MANAGEMENT_INHERITANCE_SINGLE,
RepositoryInterface::NODE_TYPE_MANAGEMENT_MULTIPLE_BINARY_PROPERTIES_SUPPORTED => true,
RepositoryInterface::NODE_TYPE_MANAGEMENT_MULTIVALUED_PROPERTIES_SUPPORTED => true,
RepositoryInterface::NODE_TYPE_MANAGEMENT_ORDERABLE_CHILD_NODES_SUPPORTED => true,
RepositoryInterface::NODE_TYPE_MANAGEMENT_OVERRIDES_SUPPORTED => false,
RepositoryInterface::NODE_TYPE_MANAGEMENT_PRIMARY_ITEM_NAME_SUPPORTED => true,
RepositoryInterface::NODE_TYPE_MANAGEMENT_PROPERTY_TYPES => true,
RepositoryInterface::NODE_TYPE_MANAGEMENT_RESIDUAL_DEFINITIONS_SUPPORTED => false,
RepositoryInterface::NODE_TYPE_MANAGEMENT_SAME_NAME_SIBLINGS_SUPPORTED => false,
RepositoryInterface::NODE_TYPE_MANAGEMENT_UPDATE_IN_USE_SUPPORTED => false,
RepositoryInterface::NODE_TYPE_MANAGEMENT_VALUE_CONSTRAINTS_SUPPORTED => false,
RepositoryInterface::OPTION_ACCESS_CONTROL_SUPPORTED => false,
RepositoryInterface::OPTION_ACTIVITIES_SUPPORTED => false,
RepositoryInterface::OPTION_BASELINES_SUPPORTED => false,
RepositoryInterface::OPTION_JOURNALED_OBSERVATION_SUPPORTED => false,
RepositoryInterface::OPTION_LIFECYCLE_SUPPORTED => false,
RepositoryInterface::OPTION_LOCKING_SUPPORTED => false,
RepositoryInterface::OPTION_NODE_AND_PROPERTY_WITH_SAME_NAME_SUPPORTED => true,
RepositoryInterface::OPTION_NODE_TYPE_MANAGEMENT_SUPPORTED => true,
RepositoryInterface::OPTION_OBSERVATION_SUPPORTED => false,
RepositoryInterface::OPTION_RETENTION_SUPPORTED => false,
RepositoryInterface::OPTION_SHAREABLE_NODES_SUPPORTED => false,
RepositoryInterface::OPTION_SIMPLE_VERSIONING_SUPPORTED => false,
RepositoryInterface::OPTION_TRANSACTIONS_SUPPORTED => true,
RepositoryInterface::OPTION_UNFILED_CONTENT_SUPPORTED => true,
RepositoryInterface::OPTION_UPDATE_MIXIN_NODETYPES_SUPPORTED => true,
RepositoryInterface::OPTION_UPDATE_PRIMARY_NODETYPE_SUPPORTED => true,
RepositoryInterface::OPTION_VERSIONING_SUPPORTED => false,
RepositoryInterface::OPTION_WORKSPACE_MANAGEMENT_SUPPORTED => true,
RepositoryInterface::OPTION_XML_EXPORT_SUPPORTED => true,
RepositoryInterface::OPTION_XML_IMPORT_SUPPORTED => true,
RepositoryInterface::QUERY_FULL_TEXT_SEARCH_SUPPORTED => true,
RepositoryInterface::QUERY_CANCEL_SUPPORTED => false,
RepositoryInterface::QUERY_JOINS => RepositoryInterface::QUERY_JOINS_NONE,
RepositoryInterface::QUERY_LANGUAGES => array(QueryInterface::JCR_SQL2, QueryInterface::JCR_JQOM),
RepositoryInterface::QUERY_STORED_QUERIES_SUPPORTED => false,
RepositoryInterface::WRITE_SUPPORTED => true,
);
}
/**
* Get the registered namespace prefixes
*
* @return array
*/
private function getNamespacePrefixes()
{
return array_keys($this->getNamespaces());
}
/**
* {@inheritDoc}
*/
public function getNamespaces()
{
return (array) $this->getNamespacesObject();
}
/**
* Return the namespaces of the current session as a referenceable ArrayObject.
*
* @return \ArrayObject
*/
protected function getNamespacesObject()
{
if (null === $this->namespaces) {
$query = 'SELECT prefix, uri FROM phpcr_namespaces';
$result = $this->getConnection()->query($query);
$namespaces = (array) $result->fetchAll(\PDO::FETCH_KEY_PAIR);
$namespaces += $this->coreNamespaces;
$this->setNamespaces($namespaces);
}
return $this->namespaces;
}
/**
* Set the namespaces property to an \ArrayObject instance
*
* @param array|\ArrayObject $namespaces
*/
protected function setNamespaces($namespaces)
{
if ($this->namespaces instanceof \ArrayObject) {
$this->namespaces->exchangeArray($namespaces);
} else {
$this->namespaces = new \ArrayObject($namespaces);
}
}
/**
* Executes an UPDATE on DBAL while ensuring that we never try to send more than 999 parameters to SQLite
*
* @param $query
* @param array $params
* @throws DBALException
*/
private function executeChunkedUpdate($query, array $params)
{
$types = array(Connection::PARAM_INT_ARRAY);
if ($this->getConnection()->getDatabasePlatform() instanceof SqlitePlatform) {
foreach (array_chunk($params, self::SQLITE_MAXIMUM_IN_PARAM_COUNT) as $chunk) {
$this->getConnection()->executeUpdate($query, array($chunk), $types);
}
} else {
$this->getConnection()->executeUpdate($query, array($params), $types);
}
}
/**
* {@inheritDoc}
*/
public function copyNode($srcAbsPath, $dstAbsPath, $srcWorkspace = null)
{
$this->assertLoggedIn();
if (null !== $srcWorkspace && !$this->workspaceExists($srcWorkspace)) {
throw new NoSuchWorkspaceException("Source workspace '$srcWorkspace' does not exist.");
}
$srcWorkspace = $srcWorkspace ?: $this->workspaceName;
PathHelper::assertValidAbsolutePath($dstAbsPath, true, true, $this->getNamespacePrefixes());
$srcNodeId = $this->getSystemIdForNodePath($srcAbsPath, $srcWorkspace);
if (!$srcNodeId) {
throw new PathNotFoundException("Source path '$srcAbsPath' not found");
}
if ($this->getSystemIdForNodePath($dstAbsPath)) {
throw new ItemExistsException("Cannot copy to destination path '$dstAbsPath' that already exists.");
}
if (!$this->getSystemIdForNodePath(PathHelper::getParentPath($dstAbsPath))) {
throw new PathNotFoundException("Parent of the destination path '" . $dstAbsPath . "' has to exist.");
}
// Algorithm:
// 1. Select all nodes with path $srcAbsPath."%" and iterate them
// 2. create a new node with path $dstAbsPath + leftovers, with a new uuid. Save old => new uuid
// 3. copy all properties from old node to new node
// 4. if a reference is in the properties, either update the uuid based on the map if its inside the copied graph or keep it.
// 5. "May drop mixin types"
$query = 'SELECT * FROM phpcr_nodes WHERE path LIKE ? AND workspace_name = ?';
$stmt = $this->getConnection()->executeQuery($query, array($srcAbsPath . '%', $srcWorkspace));
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$uuidMap = array();
$resultSetUuids = array();
// first iterate and build up an array of all the UUIDs in the result set
foreach ($rows as $row) {
$resultSetUuids[$row['identifier']] = $row['path'];
}
// array of references to remap within the copied tree
$referenceElsToRemap = array();
// array references that will need updating in the database
$referencesToUpdate = array();
foreach ($rows as $row) {
$newPath = str_replace($srcAbsPath, $dstAbsPath, $row['path']);
$stringDom = new \DOMDocument('1.0', 'UTF-8');
$stringDom->loadXML($row['props']);
$numericalDom = null;
if ($row['numerical_props']) {
$numericalDom = new \DOMDocument('1.0', 'UTF-8');
$numericalDom->loadXML($row['numerical_props']);
}
$propsData = array(
'stringDom' => $stringDom,
'numericalDom' => $numericalDom,
'references' => array(),
);
$xpath = new \DOMXpath($stringDom);
$referenceEls = $xpath->query('.//sv:property[@sv:type="reference" or @sv:type="Reference" or @sv:type="weakreference" or @sv:type="WeakReference"]');
$references = array();
foreach ($referenceEls as $referenceEl) {
$propName = $referenceEl->getAttribute('sv:name');
$values = array();
foreach ($xpath->query('./sv:value', $referenceEl) as $valueEl) {
$values[] = $valueEl->nodeValue;
}
$references[$propName] = array(
'type' => PropertyType::valueFromName($referenceEl->getAttribute('sv:type')),
'values' => $values,
);
if (isset($resultSetUuids[$referenceEl->nodeValue])) {
$referenceElsToRemap[] = array($referenceEl, $newPath, $row['type'], $propsData);
}
}
$originalUuid = $row['identifier'];
// when copying a node, the copy is always a new node. set $isNewNode to true
$newNodeId = $this->syncNode(null, $newPath, $row['type'], true, array(), $propsData);
if ($references) {
$referencesToUpdate[$newNodeId] = array(
'path' => $row['path'],
'properties' => $references,
);
}
$newUuid = $this->nodeIdentifiers[$newPath];
$uuidMap[$originalUuid] = $newUuid;
$query = 'INSERT INTO phpcr_binarydata (node_id, property_name, workspace_name, idx, data)'.
' SELECT ?, b.property_name, ?, b.idx, b.data FROM phpcr_binarydata b WHERE b.node_id = ?';
try {
$this->getConnection()->executeUpdate($query, array($newNodeId, $this->workspaceName, $row['id']));
} catch (DBALException $e) {
throw new RepositoryException("Unexpected exception while copying node from $srcAbsPath to $dstAbsPath", $e->getCode(), $e);
}
}
foreach ($referenceElsToRemap as $data) {
list($referenceEl, $newPath, $type, $propsData) = $data;
$referenceEl->nodeValue = $uuidMap[$referenceEl->nodeValue];
$this->syncNode($this->nodeIdentifiers[$newPath], $newPath, $type, false, array(), $propsData);
}
$this->syncReferences($referencesToUpdate);
}
/**
* @param string $path
*
* @return array
*/
private function getJcrName($path)
{
$name = implode('', array_slice(explode('/', $path), -1, 1));
if (($aliasLength = strpos($name, ':')) !== false) {
$alias = substr($name, 0, $aliasLength);
$name = substr($name, $aliasLength + 1);
} else {
$alias = '';
}
$namespaces = $this->getNamespaces();
if (!isset($namespaces[$alias])) {
throw new NamespaceException('the namespace ' . $alias . ' was not registered.');
}
return array($namespaces[$alias], $name);
}
/**
* Actually write the node into the database
*
* @param string $uuid node uuid
* @param string $path absolute path of the node
* @param string $type node type name
* @param boolean $isNewNode new nodes to insert (true) or existing node to update (false)
* @param Property[] $props
* @param array $propsData
*
* @return boolean|string
*
* @throws ItemExistsException
* @throws RepositoryException
*/
private function syncNode($uuid, $path, $type, $isNewNode, $props = array(), $propsData = array())
{
// TODO: Not sure if there are always ALL props in $props, should we grab the online data here?
// TODO: PERFORMANCE Binary data is handled very inefficiently here, UPSERT will really be necessary here as well as lazy handling
if (!$propsData) {
$propsData = $this->propsToXML($props);
}
if (null === $uuid) {
$uuid = $this->generateUuid();
}
if ($isNewNode) {
list($namespace, $localName) = $this->getJcrName($path);
$qb = $this->getConnection()->createQueryBuilder();
$qb->select(':identifier, :type, :path, :local_name, :namespace, :parent, :workspace_name, :props, :numerical_props, :depth, COALESCE(MAX(n.sort_order), 0) + 1')
->from('phpcr_nodes', 'n')
->where('n.parent = :parent_a');
$sql = $qb->getSql();
try {
$insert = "INSERT INTO phpcr_nodes (identifier, type, path, local_name, namespace, parent, workspace_name, props, numerical_props, depth, sort_order) " . $sql;
$this->getConnection()->executeUpdate($insert, $data = array(
'identifier' => $uuid,
'type' => $type,
'path' => $path,
'local_name' => $localName,
'namespace' => $namespace,
'parent' => PathHelper::getParentPath($path),
'workspace_name' => $this->workspaceName,
'props' => $propsData['stringDom']->saveXML(),
'numerical_props' => $propsData['numericalDom'] ? $propsData['numericalDom']->saveXML() : null,
'depth' => PathHelper::getPathDepth($path),
'parent_a' => PathHelper::getParentPath($path),
));
} catch (\Exception $e) {
if ($e instanceof \PDOException || $e instanceof DBALException) {
if (strpos($e->getMessage(), "SQLSTATE[23") !== false) {
throw new ItemExistsException('Item ' . $path . ' already exists in the database');
} else {
throw new RepositoryException('Unknown database error while inserting item ' . $path . ': '.$e->getMessage(), 0, $e);
}
} else {
throw $e;
}
}
$nodeId = $this->getConnection()->lastInsertId($this->sequenceNodeName);
} else {
$nodeId = $this->getSystemIdForNodePath($path);
if (!$nodeId) {
throw new RepositoryException("nodeId for $path not found");
}
$this->getConnection()->update('phpcr_nodes', array(
'props' => $propsData['stringDom']->saveXML(),
'numerical_props' => $propsData['numericalDom'] ? $propsData['numericalDom']->saveXML() : null,
),
array('id' => $nodeId)
);
}
$this->nodeIdentifiers[$path] = $uuid;
if (!empty($propsData['binaryData'])) {
$this->syncBinaryData($nodeId, $propsData['binaryData']);
}
$this->referencesToUpdate[$nodeId] = array('path' => $path, 'properties' => $propsData['references']);
return $nodeId;
}
private function syncBinaryData($nodeId, $binaryData)
{
foreach ($binaryData as $propertyName => $binaryValues) {
foreach ($binaryValues as $idx => $data) {
// TODO verify in which cases we can just update
$params = array(
'node_id' => $nodeId,
'property_name' => $propertyName,
'workspace_name' => $this->workspaceName,
);
$this->getConnection()->delete('phpcr_binarydata', $params);
$params['idx'] = $idx;
$params['data'] = $data;
$types = array(
\PDO::PARAM_INT,
\PDO::PARAM_STR,
\PDO::PARAM_STR,
\PDO::PARAM_INT,
\PDO::PARAM_LOB
);
$this->getConnection()->insert('phpcr_binarydata', $params, $types);
}
}
}
private function syncReferences(array $referencesToUpdate)
{
if ($referencesToUpdate) {
// do not update references that are going to be deleted anyways
$toUpdate = array_diff(array_keys($referencesToUpdate), array_keys($this->referencesToDelete));
try {
foreach ($this->referenceTables as $table) {
$query = "DELETE FROM $table WHERE source_id IN (?)";
$this->executeChunkedUpdate($query, $toUpdate);
}
} catch (DBALException $e) {
throw new RepositoryException('Unexpected exception while cleaning up after saving', $e->getCode(), $e);
}
$updates = array();
foreach ($toUpdate as $nodeId) {
$references = $referencesToUpdate[$nodeId];
foreach ($references['properties'] as $name => $data) {
foreach ($data['values'] as $value) {
$targetId = $this->getSystemIdForNodeUuid($value);
if (false === $targetId) {
if (PropertyType::REFERENCE === $data['type']) {
throw new ReferentialIntegrityException(sprintf(
'Trying to store reference to non-existant node with path "%s" in node "%s" "%s"',
$value, $references['path'], $name
));
}
continue;
}
$key = $targetId . '-' . $nodeId . '-' . $name;
// it is valid to have multiple references to the same node in a multivalue
// but it is not desired to store duplicates in the database
$updates[$key] = array(
'type' => $data['type'],
'data' => array(
'source_id' => $nodeId,
'source_property_name' => $name,
'target_id' => $targetId,
),
);
}
}
}
foreach ($updates as $update) {
$this->getConnection()->insert($this->referenceTables[$update['type']], $update['data']);
}
}
// TODO on RDBMS that support deferred FKs we could skip this step
if ($this->referencesToDelete) {
$params = array_keys($this->referencesToDelete);
// remove all PropertyType::REFERENCE with a source_id on a deleted node
try {
$query = "DELETE FROM phpcr_nodes_references WHERE source_id IN (?)";
$this->executeChunkedUpdate($query, $params);
} catch (DBALException $e) {
throw new RepositoryException('Unexpected exception while cleaning up deleted nodes', $e->getCode(), $e);
}
// ensure that there are no PropertyType::REFERENCE pointing to nodes that will be deleted
// Note: due to the outer join we cannot filter on workspace_name, but this is ok
// since within a transaction there can never be missing referenced nodes within the current workspace
// make sure the target node is not in the list of nodes being deleted, to allow deletion in same request
$query = 'SELECT DISTINCT r.target_id
FROM phpcr_nodes_references r
LEFT OUTER JOIN phpcr_nodes n ON r.target_id = n.id
WHERE r.target_id IN (?)';
if ($this->getConnection()->getDatabasePlatform() instanceof SqlitePlatform) {
$missingTargets = array();
foreach (array_chunk($params, self::SQLITE_MAXIMUM_IN_PARAM_COUNT) as $chunk) {
$stmt = $this->getConnection()->executeQuery($query, array($chunk), array(Connection::PARAM_INT_ARRAY));
$missingTargets = array_merge($missingTargets, $stmt->fetchAll(\PDO::FETCH_COLUMN));
}
} else {
$stmt = $this->getConnection()->executeQuery($query, array($params), array(Connection::PARAM_INT_ARRAY));
$missingTargets = $stmt->fetchAll(\PDO::FETCH_COLUMN);
}
if ($missingTargets) {
$paths = array();
foreach ($missingTargets as $id) {
if (isset($this->referencesToDelete[$id])) {
$paths[] = $this->referencesToDelete[$id];
}
}
throw new ReferentialIntegrityException("Cannot delete '".implode("', '", $paths)."': A reference points to this node or a subnode");
}
// clean up all references
try {
foreach ($this->referenceTables as $table) {
$query = "DELETE FROM $table WHERE target_id IN (?)";
$this->executeChunkedUpdate($query, $params);
}
} catch (DBALException $e) {
throw new RepositoryException('Unexpected exception while cleaning up deleted nodes', $e->getCode(), $e);
}
}
}
/**
* Convert the node XML to stdClass node representation containing all properties
*
* @param string $xml
*
* @return \stdClass
*/
protected function xmlToProps($xml)
{
$data = new \stdClass();
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->loadXML($xml);
foreach ($dom->getElementsByTagNameNS('http://www.jcp.org/jcr/sv/1.0', 'property') as $propertyNode) {
$this->mapPropertyFromElement($propertyNode, $data);
}
return $data;
}
/**
* Convert the node XML to stdClass node representation containing only the given properties
*
* @param string $xml
* @param array $propertyNames
*
* @return \stdClass
*/
protected function xmlToColumns($xml, $propertyNames)
{
$data = new \stdClass;
$dom = new \DOMDocument('1.0');
$dom->loadXml($xml);
$dom->formatOutput=true;
$xpath = new \DOMXPath($dom);
$columns = array();
$propertyEls = array();