-
Notifications
You must be signed in to change notification settings - Fork 41
/
Client.php
2155 lines (1884 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
/**
* Copyright (c) 2016 AlexaCRM.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace AlexaCRM\CRMToolkit;
use AlexaCRM\CRMToolkit\Auth\Authentication;
use AlexaCRM\CRMToolkit\Auth\Federation;
use AlexaCRM\CRMToolkit\Auth\OnlineFederation;
use AlexaCRM\CRMToolkit\Entity\EntityReference;
use BadMethodCallException;
use DOMDocument;
use DOMElement;
use DOMNode;
use DOMNodeList;
use AlexaCRM\CRMToolkit\Entity\MetadataCollection;
use Exception;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use SimpleXMLElement;
use stdClass;
/**
* This class creates and manages SOAP connections to a Microsoft Dynamics CRM server
*/
class Client extends AbstractClient {
/**
* Object of authentication class
*
* @var Authentication
*/
private $authentication;
/**
* Object of settings class
*
* @var Settings
*/
public $settings;
/**
* @var SoapActions
*/
private $soapActions;
/**
* @ignore
*/
private $organizationDOM;
/**
* @ignore
*/
private $organizationSecurityPolicy;
/* Security Details */
private $security = array();
/* Cached Discovery data */
private $discoveryDOM;
private $discoverySecurityPolicy;
/**
* Connection timeout for CURLOPT_TIMEOUT
*
* @var integer $connectorTimeout time in seconds for waiting the response from Dynamics CRM web service
*/
protected static $connectorTimeout = 300;
/**
* Maximum record to retrieve
*
* @var int
*/
protected static $maximumRecords = self::MAX_CRM_RECORDS;
/**
* Volatile entity cache
*
* @var Entity[]
*/
protected static $entityCache = [];
/**
* Stores a map of LogicalName => {Key,...} associations for cached records
*
* @var array
*/
protected static $entityCacheRefs = [];
/**
* @var CacheInterface
*/
public $cache;
/**
* @var LoggerInterface
*/
public $logger;
/**
* Create a new instance of the AlexaCRM\CRMToolkit\AlexaSDK
*
* @param Settings $settings
* @param CacheInterface $cache
* @param LoggerInterface $logger
*
* @throws Exception
*/
function __construct( Settings $settings, CacheInterface $cache = null, LoggerInterface $logger = null ) {
try {
// Create settings object
$this->settings = $settings;
// Inject CacheInterface implementation
$this->cache = $cache;
if ( !( $this->cache instanceof CacheInterface ) ) {
// Provide a dummy cache if no cache supplied
$this->cache = new NullCache();
}
// Inject LoggerInterface implementation
$this->logger = $logger;
if ( !( $this->logger instanceof LoggerInterface ) ) {
// Provide a dummy logger if no logger supplied.
$this->logger = new NullLogger();
}
/* If either mandatory parameter is NULL, throw an Exception */
if ( !$this->checkConnectionSettings() ) {
switch ( $this->settings->authMode ) {
case "OnlineFederation":
throw new BadMethodCallException( get_class( $this ) . ' constructor requires Username and Password' );
case "Federation":
throw new BadMethodCallException( get_class( $this ) . ' constructor requires the Discovery URI, Username and Password' );
}
}
/* Create authentication class to connect to CRM Online or Internet facing deployment via ADFS */
switch ( $this->settings->authMode ) {
case "OnlineFederation":
$this->authentication = new OnlineFederation( $this->settings, $this );
break;
case "Federation":
$this->settings->loginUrl = $this->getFederationSecurityURI( 'organization' );
$this->authentication = new Federation( $this->settings, $this );
break;
}
$this->soapActions = new SoapActions( $this );
if ( !$this->settings->hasOrganizationData() ) {
if ( $this->settings->useDiscovery ) {
$organizationDetails = $this->retrieveOrganization( $this->settings->serverUrl );
} else {
$organizationDetails = $this->retrieveOrganizationNoDiscovery();
}
$this->settings->organizationId = $organizationDetails['OrganizationId'];
$this->settings->organizationName = $organizationDetails['FriendlyName'];
$this->settings->organizationUniqueName = $organizationDetails['UniqueName'];
$this->settings->organizationVersion = $organizationDetails['OrganizationVersion'];
}
/* Initialize the entity metadata instance */
MetadataCollection::instance( $this );
} catch ( Exception $e ) {
$this->logger->critical( 'Exception during instantiation of the CRM Toolkit.', [ 'exception' => $e ] );
throw $e;
}
}
public function __get( $name ) {
switch ( strtolower( $name ) ) {
case "organizationversion":
return $this->settings->organizationVersion;
case "settings":
return $this->settings;
}
}
/**
* Return the Authentication Mode used by the Discovery service
*
* @return mixed string if one auth type, array if there is multiple authentication types
* @throws Exception
* @ignore
*/
protected function getDiscoveryAuthenticationMode() {
try {
/* If it's set, return the details from the Security array */
if ( isset( $this->settings->authMode ) ) {
return $this->settings->authMode;
}
/* Get the Discovery DOM */
$discoveryDOM = $this->getDiscoveryDOM();
/* Get the Security Policy for the Organization Service from the WSDL */
$this->discoverySecurityPolicy = $this->findSecurityPolicy( $discoveryDOM, 'DiscoveryService' );
/* Check the Authentication node existence */
if ( $this->discoverySecurityPolicy->getElementsByTagName( 'Authentication' )->length == 0 ) {
throw new Exception( 'Could not find Authentication tag in provided Discovery Security policy XML' );
}
/* Find the Authentication type used */
$authMode = array();
if ( $this->discoverySecurityPolicy->getElementsByTagName( 'Authentication' )->length > 1 ) {
foreach ( $this->discoverySecurityPolicy->getElementsByTagName( 'Authentication' ) as $authentication ) {
array_push( $authMode, $authentication->textContent );
}
} else {
array_push( $authMode, $this->discoverySecurityPolicy->getElementsByTagName( 'Authentication' )->item( 0 )->textContent );
}
/* Return authType array */
return $authMode;
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while finding DiscoveryService authentication mode', [ 'exception' => $e ] );
throw $e;
}
}
/**
* Fetch and flatten the Discovery Service WSDL as a DOM
*
* @ignore
*/
public function getDiscoveryDOM() {
try {
/* If it's already been fetched, use the one we have */
if ( $this->discoveryDOM != null ) {
return $this->discoveryDOM;
}
$importXML = $this->retrieveWsdl( $this->settings->discoveryUrl . '?wsdl' );
$discoveryDOM = new DOMDocument();
$discoveryDOM->loadXML( $importXML );
/* Flatten the WSDL and include all the Imports */
$this->mergeWSDLImports( $discoveryDOM );
/* Cache the DOM in the current object */
$this->discoveryDOM = $discoveryDOM;
return $discoveryDOM;
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while retrieving DiscoveryService WSDL', [ 'exception' => $e ] );
throw $e;
}
}
/**
* Return the Authentication Address used by the Discovery service
*
* @ignore
*/
protected function getDiscoveryAuthenticationAddress() {
try {
/* If it's set, return the details from the Security array */
if ( isset( $this->security['discovery_authuri'] ) ) {
return $this->security['discovery_authuri'];
}
/* If we don't already have a Security Policy, get it */
if ( $this->discoverySecurityPolicy == null ) {
/* Get the Discovery DOM */
$discoveryDOM = $this->getDiscoveryDOM();
/* Get the Security Policy for the Organization Service from the WSDL */
$this->discoverySecurityPolicy = $this->findSecurityPolicy( $discoveryDOM, 'DiscoveryService' );
}
$authAddress = $this->getSecurityAddress( $this->discoverySecurityPolicy, $this->security['discovery_authmode'] );
return $authAddress;
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while finding DiscoveryService authentication address', [ 'exception' => $e ] );
throw $e;
}
}
/**
* Return the Authentication Address used by the Organization service
*
* @ignore
*/
public function getOrganizationAuthenticationAddress() {
try {
/* If it's set, return the details from the Security array */
if ( isset( $this->security['organization_authuri'] ) ) {
return $this->security['organization_authuri'];
}
/* If we don't already have a Security Policy, get it */
if ( $this->organizationSecurityPolicy == null ) {
/* Get the Organization DOM */
$organizationDOM = $this->getOrganizationDOM();
/* Get the Security Policy for the Organization Service from the WSDL */
$this->organizationSecurityPolicy = $this->findSecurityPolicy( $organizationDOM, 'OrganizationService' );
}
/* Find the Authentication type used */
$this->security['organization_authuri'] = $this->getSecurityAddress( $this->organizationSecurityPolicy, 'Federation' );
return $this->security['organization_authuri'];
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while finding OrganizationService security endpoint', [ 'exception' => $e ] );
throw $e;
}
}
/**
* Search for the security address
*
* @param DOMNode $securityPolicyNode
* @param string $authMode
*
* @return string
* @throws Exception
*/
protected function getSecurityAddress( DOMNode $securityPolicyNode, $authMode ) {
if ( $authMode === 'OnlineFederation' ) {
$tokenElementName = 'SignedSupportingTokens';
} elseif ( $authMode === 'Federation' ) {
$tokenElementName = 'EndorsingSupportingTokens';
} else {
throw new \InvalidArgumentException( 'Authentication mode "' . $authMode . '" is not supported' );
}
try {
$securityURL = null;
/* Find the SignedSupportingTokens tag */
if ( $securityPolicyNode->getElementsByTagName( $tokenElementName )->length == 0 ) {
throw new Exception( 'Could not find ' . $tokenElementName . ' tag in provided security policy XML' );
}
$estNode = $securityPolicyNode->getElementsByTagName( $tokenElementName )->item( 0 );
/* Find the Policy tag */
if ( $estNode->getElementsByTagName( 'Policy' )->length == 0 ) {
throw new Exception( 'Could not find ' . $tokenElementName . '/Policy tag in provided security policy XML' );
}
$estPolicyNode = $estNode->getElementsByTagName( 'Policy' )->item( 0 );
/* Find the IssuedToken tag */
if ( $estPolicyNode->getElementsByTagName( 'IssuedToken' )->length == 0 ) {
throw new Exception( 'Could not find ' . $tokenElementName . '/Policy/IssuedToken tag in provided security policy XML' );
}
$issuedTokenNode = $estPolicyNode->getElementsByTagName( 'IssuedToken' )->item( 0 );
/* Find the Issuer tag */
if ( $issuedTokenNode->getElementsByTagName( 'Issuer' )->length == 0 ) {
throw new Exception( 'Could not find ' . $tokenElementName . '/Policy/IssuedToken/Issuer tag in provided security policy XML' );
}
$issuerNode = $issuedTokenNode->getElementsByTagName( 'Issuer' )->item( 0 );
/* Find the Metadata tag */
if ( $issuerNode->getElementsByTagName( 'Metadata' )->length == 0 ) {
throw new Exception( 'Could not find ' . $tokenElementName . '/Policy/IssuedToken/Issuer/Metadata tag in provided security policy XML' );
}
$metadataNode = $issuerNode->getElementsByTagName( 'Metadata' )->item( 0 );
/* Find the Address tag */
if ( $metadataNode->getElementsByTagName( 'Address' )->length == 0 ) {
throw new Exception( 'Could not find ' . $tokenElementName . '/Policy/IssuedToken/Issuer/Metadata/.../Address tag in provided security policy XML' );
}
$addressNode = $metadataNode->getElementsByTagName( 'Address' )->item( 0 );
/* Get the URI */
$securityURL = $addressNode->textContent;
if ( $securityURL == null ) {
throw new Exception( 'Could not find Security URL in provided security policy WSDL' );
}
return $securityURL;
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while retrieving the security endpoint', [ 'exception' => $e, 'authMode' => $authMode ] );
throw $e;
}
}
/**
* Search a WSDL XML DOM for "import" tags and import the files into
* one large DOM for the entire WSDL structure
*
* @ignore
*/
protected function mergeWSDLImports( DOMNode &$wsdlDOM, $continued = false, DOMDocument &$newRootDocument = null ) {
try {
static $rootNode = null;
static $rootDocument = null;
/* If this is an external call, find the "root" definitions node */
if ( !$continued ) {
$rootNode = $wsdlDOM->getElementsByTagName( 'definitions' )->item( 0 );
$rootDocument = $wsdlDOM;
}
if ( $newRootDocument == null ) {
$newRootDocument = $rootDocument;
}
$nodesToRemove = [];
/* Loop through the Child nodes of the provided DOM */
foreach ( $wsdlDOM->childNodes as $childNode ) {
/**
* @var DOMElement $childNode
*/
/* If this child is an IMPORT node, get the referenced WSDL, and remove the Import */
if ( $childNode->localName == 'import' ) {
/* Get the location of the imported WSDL */
$importURI = null;
if ( $childNode->hasAttribute( 'location' ) ) {
$importURI = $childNode->getAttribute( 'location' );
} else if ( $childNode->hasAttribute( 'schemaLocation' ) ) {
$importURI = $childNode->getAttribute( 'schemaLocation' );
}
if ( is_null( $importURI ) ) {
continue; // import URI wasn't found - no import performed then
}
$importXML = $this->retrieveWsdl( $importURI );
$importDOM = new DOMDocument();
$importDOM->loadXML( $importXML );
/* Find the "Definitions" on this imported node */
$importDefinitions = $importDOM->getElementsByTagName( 'definitions' )->item( 0 );
/* If we have "Definitions", import them one by one - Otherwise, just import at this level */
if ( $importDefinitions != null ) {
/* Add all the attributes (namespace definitions) to the root definitions node */
foreach ( $importDefinitions->attributes as $attribute ) {
/* Don't copy the "TargetNamespace" attribute */
if ( $attribute->name != 'targetNamespace' ) {
$rootNode->setAttributeNode( $attribute );
}
}
$this->mergeWSDLImports( $importDefinitions, true, $importDOM );
foreach ( $importDefinitions->childNodes as $importNode ) {
$importNode = $newRootDocument->importNode( $importNode, true );
$wsdlDOM->insertBefore( $importNode, $childNode );
}
} else {
$importNode = $newRootDocument->importNode( $importDOM->firstChild, true );
$wsdlDOM->insertBefore( $importNode, $childNode );
}
$nodesToRemove[] = $childNode;
} else {
// preserving the node
if ( $childNode->hasChildNodes() ) {
$this->mergeWSDLImports( $childNode, true );
}
}
}
/* Actually remove the nodes (not done in the loop, as it messes up the ForEach pointer!) */
foreach ( $nodesToRemove as $node ) {
$wsdlDOM->removeChild( $node );
}
return $wsdlDOM;
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while merging WSDL imports', [ 'exception' => $e ] );
throw $e;
}
}
/**
* Parse the results of a RetrieveEntity into a usable PHP object
*
* @ignore
*/
protected function parseRetrieveEntityResponse( $soapResponse ) {
try {
/* Load the XML into a DOMDocument */
$soapResponseDOM = new DOMDocument();
$soapResponseDOM->loadXML( $soapResponse );
/* Find the ExecuteResult node with Type b:RetrieveRecordChangeHistoryResponse */
$executeResultNode = null;
foreach ( $soapResponseDOM->getElementsByTagName( 'ExecuteResult' ) as $node ) {
if ( $node->hasAttributeNS( 'http://www.w3.org/2001/XMLSchema-instance', 'type' ) && self::stripNS( $node->getAttributeNS( 'http://www.w3.org/2001/XMLSchema-instance', 'type' ) ) == 'RetrieveEntityResponse' ) {
$executeResultNode = $node;
break;
}
}
unset( $node );
if ( $executeResultNode == null ) {
throw new Exception( 'Could not find ExecuteResult for RetrieveEntityResponse in XML provided' );
}
/* Find the Value node with Type d:AlexaCRM\CRMToolkit\Entity\EntityMetadata */
$entityMetadataNode = null;
foreach ( $executeResultNode->getElementsByTagName( 'value' ) as $node ) {
if ( $node->hasAttributeNS( 'http://www.w3.org/2001/XMLSchema-instance', 'type' ) && self::stripNS( $node->getAttributeNS( 'http://www.w3.org/2001/XMLSchema-instance', 'type' ) ) == 'EntityMetadata' ) {
$entityMetadataNode = $node;
break;
}
}
if ( $entityMetadataNode == null ) {
throw new Exception( 'Could not find returned EntityMetadata in XML provided' );
}
/* Assemble a simpleXML class for the details to return */
$nodeXML = $entityMetadataNode->ownerDocument->saveXML( $entityMetadataNode );
// remove XML namespaces
$nodeXMLWithoutNS = preg_replace( '/(<)([a-z]:)/', '<', preg_replace( '/(<\/)([a-z]:)/', '</', $nodeXML ) );
$nodeXMLWithoutNS = preg_replace( '~([\s"])[a-z]:([a-zA-Z]+)~', '$1$2', $nodeXMLWithoutNS );
$entityMetadataElement = simplexml_load_string( $nodeXMLWithoutNS );
if ( !$entityMetadataElement ) {
throw new Exception( 'Unable to load metadata simple_xml_class' );
}
/* Return the SimpleXML object */
return $entityMetadataElement;
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while parsing RetrieveEntity response', [ 'exception' => $e, 'response' => $soapResponse ] );
throw $e;
}
}
/**
* Parse the results of a RetrieveMultipleRequest into a usable PHP object
*
* @param string $soapResponse
*
* @return SimpleXMLElement[]
*
* @throws Exception
*/
protected function parseRetrieveAllEntitiesResponse( $soapResponse ) {
try {
/* Load the XML into a DOMDocument */
$soapResponseDOM = new DOMDocument();
$soapResponseDOM->loadXML( $soapResponse );
/**
* Find the RetrieveMultipleResponse
*
* @var $retrieveMultipleResponseNode DOMElement
*/
$retrieveMultipleResponseNode = null;
foreach ( $soapResponseDOM->getElementsByTagName( 'ExecuteResponse' ) as $node ) {
$retrieveMultipleResponseNode = $node;
break;
}
unset( $node );
if ( $retrieveMultipleResponseNode == null ) {
throw new Exception( 'Could not find ExecuteResponse node in XML provided' );
}
/**
* Find the RetrieveMultipleResult node
*
* @var $retrieveMultipleResultNode DOMElement
*/
$retrieveMultipleResultNode = null;
foreach ( $retrieveMultipleResponseNode->getElementsByTagName( 'Results' ) as $node ) {
$retrieveMultipleResultNode = $node;
break;
}
unset( $node );
if ( $retrieveMultipleResultNode == null ) {
throw new Exception( 'Could not find ExecuteResult node in XML provided' );
}
/* Assemble an associative array for the details to return */
$responseDataArray = array();
/* Loop through the Entities returned */
foreach ( $retrieveMultipleResultNode->getElementsByTagName( 'EntityMetadata' ) as $entityNode ) {
/**
* @var $entityNode DOMElement
*/
if ( $entityNode->getElementsByTagName( "IsValidForAdvancedFind" )->item( 0 )->textContent != "true" ) {
continue;
}
$nodeXML = $entityNode->ownerDocument->saveXML( $entityNode );
// remove XML namespaces
$nodeXMLWithoutNS = preg_replace( '/(<)([a-z]:)/', '<', preg_replace( '/(<\/)([a-z]:)/', '</', $nodeXML ) );
$nodeXMLWithoutNS = preg_replace( '~([\s"])[a-z]:([a-zA-Z]+)~', '$1$2', $nodeXMLWithoutNS );
$entityMetadataElement = simplexml_load_string( $nodeXMLWithoutNS );
array_push( $responseDataArray, $entityMetadataElement );
}
return $responseDataArray;
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while parsing RetrieveAllEntities response', [ 'exception' => $e, 'response' => $soapResponse ] );
throw $e;
}
}
/**
* Get the SOAP Endpoint for the Federation Security service
*
* @ignore
*
* @param string $service Lower-case service name (organization, discovery)
*
* @return null
* @throws Exception
*/
public function getFederationSecurityURI( $service ) {
try {
$securityEndpointKey = $service . '_authendpoint';
/* If it's set, return the details from the Security array */
if ( isset( $this->security[ $securityEndpointKey ] ) ) {
return $this->security[ $securityEndpointKey ];
}
if ( $service === 'organization' ) {
$authUri = $this->getOrganizationAuthenticationAddress();
} elseif ( $service === 'discovery' ) {
$authUri = $this->getDiscoveryAuthenticationAddress();
} else {
$authUri = $this->security[ $service . '_authuri' ];
}
// Hard-code the usernamemixed token issuance endpoint as the only supported endpoint.
$authEndpoint = preg_replace( '~^https?://(.*?)/.*$~', 'https://$1/adfs/services/trust/13/usernamemixed', $authUri );
$this->security[ $securityEndpointKey ] = $authEndpoint;
return $authEndpoint;
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while finding Federation security endpoint', [ 'exception' => $e ] );
throw $e;
}
}
/**
* Search a Microsoft Dynamics CRM 2011 WSDL for the Security Policy for a given Service
*
* @ignore
*
* @param DOMDocument $wsdlDocument
* @param string $serviceName
*
* @return DOMElement
* @throws Exception
*/
protected function findSecurityPolicy( DOMDocument $wsdlDocument, $serviceName ) {
try {
/* Find the selected Service definition from the WSDL */
$selectedServiceNode = null;
foreach ( $wsdlDocument->getElementsByTagName( 'service' ) as $serviceNode ) {
if ( $serviceNode->hasAttribute( 'name' ) && $serviceNode->getAttribute( 'name' ) == $serviceName ) {
$selectedServiceNode = $serviceNode;
break;
}
}
if ( $selectedServiceNode == null ) {
throw new Exception( 'Could not find definition of Service <' . $serviceName . '> in provided WSDL' );
}
/* Now find the Binding for the Service */
$bindingName = null;
foreach ( $selectedServiceNode->getElementsByTagName( 'port' ) as $portNode ) {
if ( $portNode->hasAttribute( 'name' ) ) {
$bindingName = $portNode->getAttribute( 'name' );
break;
}
}
if ( $bindingName == null ) {
throw new Exception( 'Could not find binding for Service <' . $serviceName . '> in provided WSDL' );
}
/* Find the Binding definition from the WSDL */
$bindingNode = null;
foreach ( $wsdlDocument->getElementsByTagName( 'binding' ) as $bindingNode ) {
if ( $bindingNode->hasAttribute( 'name' ) && $bindingNode->getAttribute( 'name' ) == $bindingName ) {
break;
}
}
if ( $bindingNode == null ) {
throw new Exception( 'Could not find definition of Binding <' . $bindingName . '> in provided WSDL' );
}
/* Find the Policy Reference */
$policyReferenceURI = null;
foreach ( $bindingNode->getElementsByTagName( 'PolicyReference' ) as $policyReferenceNode ) {
if ( $policyReferenceNode->hasAttribute( 'URI' ) ) {
/* Strip the leading # from the PolicyReferenceURI to get the ID */
$policyReferenceURI = substr( $policyReferenceNode->getAttribute( 'URI' ), 1 );
break;
}
}
if ( $policyReferenceURI == null ) {
throw new Exception( 'Could not find Policy Reference for Binding <' . $bindingName . '> in provided WSDL' );
}
/**
* Find the Security Policy from the WSDL
*
* @var DOMElement $securityPolicyNode
*/
$securityPolicyNode = null;
foreach ( $wsdlDocument->getElementsByTagName( 'Policy' ) as $policyNode ) {
if ( $policyNode->hasAttribute( 'wsu:Id' ) && $policyNode->getAttribute( 'wsu:Id' ) == $policyReferenceURI ) {
$securityPolicyNode = $policyNode;
break;
}
}
if ( $securityPolicyNode == null ) {
throw new Exception( 'Could not find Policy with ID <' . $policyReferenceURI . '> in provided WSDL' );
}
/* Return the selected node */
return $securityPolicyNode;
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while finding security policy', [ 'exception' => $e, 'wsdl' => $wsdlDocument->saveXML(), 'service' => $serviceName ] );
throw $e;
}
}
/**
* Fetch and flatten the Organization Service WSDL as a DOM
*
* @ignore
*/
public function getOrganizationDOM() {
try {
/* If it's already been fetched, use the one we have */
if ( $this->organizationDOM != null ) {
return $this->organizationDOM;
}
if ( $this->settings->organizationUrl == null ) {
throw new Exception( 'Cannot get Organization DOM before determining Organization URI' );
}
$importXML = $this->retrieveWsdl( $this->settings->organizationUrl . '?wsdl' );
$organizationDOM = new DOMDocument();
$organizationDOM->loadXML( $importXML );
/* Flatten the WSDL and include all the Imports */
$this->mergeWSDLImports( $organizationDOM );
/* Cache the DOM in the current object */
$this->organizationDOM = $organizationDOM;
return $organizationDOM;
} catch ( Exception $e ) {
$this->logger->error( 'Caught exception while retrieving OrganizationService WSDL', [ 'exception' => $e ] );
throw $e;
}
}
/**
* Send a RetrieveEntity request to the Dynamics CRM 2011 server and return the results as a structured Object
*
* @param String $entityType the LogicalName of the Entity to be retrieved (Incident, Account etc.)
* @param String $entityId the internal Id of the Entity to be retrieved (without enclosing brackets)
* @param array $entityFilters array listing all fields to be fetched, or null to get all columns
* @param Boolean $showUnpublished
*
* @return stdClass a PHP Object containing all the data retrieved.
*/
public function retrieveEntity( $entityType, $entityId = null, $entityFilters = null, $showUnpublished = false ) {
/* Get the raw XML data */
$rawSoapResponse = $this->retrieveEntityRaw( $entityType, $entityId, $entityFilters, $showUnpublished );
/* Parse the raw XML data into an Object */
$soapData = $this->parseRetrieveEntityResponse( $rawSoapResponse );
/* Return the structured object */
return $soapData;
}
/**
* Send a RetrieveEntity request to the Dynamics CRM server and return the results as raw XML
* This is particularly useful when debugging the responses from the server
*
* @param string $entityType the LogicalName of the Entity to be retrieved (Incident, Account etc.)
*
* @return string the raw XML returned by the server, including all SOAP Envelope, Header and Body data.
*/
public function retrieveEntityRaw( $entityType, $entityId = null, $entityFilters = null, $showUnpublished = false ) {
/* Generate the XML for the Body of a RetrieveEntity request */
$executeNode = SoapRequestsGenerator::generateRetrieveEntityRequest( $entityType, $entityId, $entityFilters, $showUnpublished );
return $this->attemptSoapResponse( 'organization', function() use ( $executeNode ) {
return $this->generateSoapRequest( 'organization', 'Execute', $executeNode );
} );
}
/**
* Send a RetrieveMultipleEntities request to the Dynamics CRM server
* and return the results as a structured Object
* Each Entity returned is processed into an appropriate AlexaCRM\CRMToolkit\AlexaSDK_Entity object
*
* @param string $entityType logical name of entities to retrieve
* @param boolean $allPages indicates if the query should be resent until all possible data is retrieved
* @param string $pagingCookie if multiple pages are returned, send the paging cookie to get pages 2 and onwards. Use NULL to get the first page. Ignored if $allPages is specified.
* @param integer $limitCount maximum number of records to be returned per page
* @param boolean $simpleMode indicates if we should just use stdClass, instead of creating Entities
*
* @return stdClass a PHP Object containing all the data retrieved.
*/
public function retrieveMultipleEntities( $entityType, $allPages = true, $pagingCookie = null, $limitCount = null, $pageNumber = null, $simpleMode = false ) {
$queryXML = new DOMDocument();
$fetch = $queryXML->appendChild( $queryXML->createElement( 'fetch' ) );
$fetch->setAttribute( 'version', '1.0' );
$fetch->setAttribute( 'output-format', 'xml-platform' );
$fetch->setAttribute( 'mapping', 'logical' );
$fetch->setAttribute( 'distinct', 'false' );
$entity = $fetch->appendChild( $queryXML->createElement( 'entity' ) );
$entity->setAttribute( 'name', $entityType );
$entity->appendChild( $queryXML->createElement( 'all-attributes' ) );
$order = $entity->appendChild( $queryXML->createElement( 'order' ) );
$order->setAttribute( 'attribute', MetadataCollection::instance( $this )->getEntityDefinition( $entityType )->primaryNameAttribute );
$order->setAttribute( 'descending', 'false' );
$queryXML->saveXML( $fetch );
return $this->retrieveMultiple( $queryXML->C14N(), $allPages, $pagingCookie, $limitCount, $pageNumber, $simpleMode );
}
/**
* Send a Retrieve request to the Dynamics CRM 2011 server and return the results as raw XML
* This function is typically used just after creating something (where you get the ID back
* as the return value), as it is more efficient to use RetrieveMultiple to search directly if
* you don't already have the ID.
* This is particularly useful when debugging the responses from the server
*
* @param Entity $entity the Entity to retrieve - must have an ID specified
* @param array $columnSet array listing all fields to be fetched, or null to get all fields
*
* @return string the raw XML returned by the server, including all SOAP Envelope, Header and Body data.
* @throws Exception
*/
public function retrieveRaw( Entity $entity, $columnSet = null ) {
/* Determine the Type & ID of the Entity */
$entityType = $entity->LogicalName;
/* Check if entity have and ID */
if ( $entity->ID != self::EmptyGUID ) {
$entityId = $entity->ID;
$executeNode = SoapRequestsGenerator::generateRetrieveRequest( $entityType, $entityId, $columnSet );
$action = "Retrieve";
} else if ( $entity->keyAttributes ) {
$executeNode = SoapRequestsGenerator::generateExecuteRetrieveRequest( $entityType, $entity->keyAttributes, $columnSet );
$action = "Execute";
} else {
/* Only allow "Retrieve" for an Entity with an ID */
throw new Exception( 'Cannot Retrieve an Entity without an ID or KeyAttributes.' );
}
return $this->attemptSoapResponse( 'organization', function() use ( $action, $executeNode ) {
return $this->generateSoapRequest( 'organization', $action, $executeNode );
} );
}
/**
* Returns an organizations list using Discovery service.
* Deprecated due to Discovery service deprecation since April 21, 2021.
*
* @return array
* @throws InvalidSecurityException
* @deprecated
*/
public function retrieveOrganizations() {
/* Generate a Soap Request for the Retrieve Organization Request method of the Discovery Service */
$executeNode = SoapRequestsGenerator::generateRetrieveOrganizationRequest();
$discoveryData = $this->attemptSoapResponse( 'discovery', function() use ( $executeNode ) {
return $this->generateSoapRequest( 'discovery', 'Execute', $executeNode );
} );
$organizationDetails = array();
$discoveryDOM = new DOMDocument();
$discoveryDOM->loadXML( $discoveryData );
if ( $discoveryDOM->getElementsByTagName( 'OrganizationDetail' )->length > 0 ) {
foreach ( $discoveryDOM->getElementsByTagName( 'OrganizationDetail' ) as $organizationNode ) {
$organization = array();
foreach ( $organizationNode->getElementsByTagName( 'Endpoints' )->item( 0 )->getElementsByTagName( 'KeyValuePairOfEndpointTypestringztYlk6OT' ) as $endpointDOM ) {
$organization["Endpoints"][ $endpointDOM->getElementsByTagName( 'key' )->item( 0 )->textContent ] = $endpointDOM->getElementsByTagName( 'value' )->item( 0 )->textContent;
}
if ( $organizationNode->getElementsByTagName( 'FriendlyName' )->length > 0 ) {
$organization["FriendlyName"] = $organizationNode->getElementsByTagName( 'FriendlyName' )->item( 0 )->textContent;
}
if ( $organizationNode->getElementsByTagName( 'OrganizationId' )->length > 0 ) {
$organization["OrganizationId"] = $organizationNode->getElementsByTagName( 'OrganizationId' )->item( 0 )->textContent;
}
if ( $organizationNode->getElementsByTagName( 'OrganizationVersion' )->length > 0 ) {
$organization["OrganizationVersion"] = $organizationNode->getElementsByTagName( 'OrganizationVersion' )->item( 0 )->textContent;
}
if ( $organizationNode->getElementsByTagName( 'State' )->length > 0 ) {
$organization["State"] = $organizationNode->getElementsByTagName( 'State' )->item( 0 )->textContent;
}
if ( $organizationNode->getElementsByTagName( 'UniqueName' )->length > 0 ) {
$organization["UniqueName"] = $organizationNode->getElementsByTagName( 'UniqueName' )->item( 0 )->textContent;
}
if ( $organizationNode->getElementsByTagName( 'UrlName' )->length > 0 ) {
$organization["UrlName"] = $organizationNode->getElementsByTagName( 'UrlName' )->item( 0 )->textContent;
}
array_push( $organizationDetails, $organization );
}
}
return $organizationDetails;
}
/**
* Retrieve organization using Discovery service.
* Deprecated due to Discovery service deprecation since April 21, 2021.
*
* @param $webApplicationUrl
*
* @return mixed|null
* @throws InvalidSecurityException
* @deprecated
*/
public function retrieveOrganization( $webApplicationUrl ) {
$organizationDetails = null;
$parsedUrl = parse_url( $webApplicationUrl );
$organizations = $this->retrieveOrganizations();
foreach ( $organizations as $organization ) {
if ( substr_count( $organization["Endpoints"]["WebApplication"], $parsedUrl["host"] ) ) {
$organizationDetails = $organization;
}
}
return $organizationDetails;
}
/**
* Retrieve organization data using RetrieveCurrentOrganizationRequest.
*
* @return array
* @throws InvalidSecurityException
*/
public function retrieveOrganizationNoDiscovery() {
$organization = null;
$parameters = array(
array(
'key' => 'AccessType',
'value' => 'Default',
'type' => 'EndpointAccessType'
)
);
try {
/* Generate the XML for the Body of a Execute Action request */
$executeActionNode = SoapRequestsGenerator::generateExecuteActionRequest( 'RetrieveCurrentOrganization', $parameters, null );
$this->logger->debug( 'Executing Execute request', ['request' => $executeActionNode->C14N() ] );
$soapResponse = $this->attemptSoapResponse( 'organization', function() use ( $executeActionNode ) {
return $this->generateSoapRequest( 'organization', 'Execute', $executeActionNode );
} );
$this->logger->debug( 'Finished executing Execute request', [ 'response' => $soapResponse ] );
/* Load the XML into a DOMDocument */
$soapResponseDOM = new DOMDocument();
$soapResponseDOM->loadXML( $soapResponse );
/* Find the UpdateResponse */
$executeResultNode = null;
foreach ( $soapResponseDOM->getElementsByTagName( 'ExecuteResult' ) as $node ) {
$executeResultNode = $node;
break;
}
unset( $node );
if ( $executeResultNode == null ) {
throw new Exception( 'Could not find ExecuteResult node in XML returned from Server' );
}
$keyValueNode = $executeResultNode->getElementsByTagName( 'KeyValuePairOfstringanyType' );
if ( $keyValueNode == null ) {
throw new Exception( 'Could not find KeyValuePairOfstringanyType node in XML returned from Server' );
}
$organizationNode = $keyValueNode->item( 0 )->getElementsByTagName( 'value' )->item( 0 );
if ( $organizationNode == null ) {
throw new Exception( 'Could not find OrganizationDetails node in XML returned from Server' );
}