-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathDynamicsCRM2011_Connector.class.php
2571 lines (2371 loc) · 121 KB
/
DynamicsCRM2011_Connector.class.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
/**
* DynamicsCRM2011_Connector.class.php
*
* This file defines the DynamicsCRM2011_Connector class that can be used to access
* the Microsoft Dynamics 2011 system through SOAP calls from PHP.
*
* @author Nick Price
* @version $Revision: 1.7 $
* @package DynamicsCRM2011
*
* ChangeLog
* $Log: DynamicsCRM2011Connector.class.php,v $
* Revision 1.7 2012/02/28 18:34:32 nick.price
* Added error handling for Soap Errors
*
* Revision 1.6 2012/02/28 17:39:12 nick.price
* Removed additional debug
*
* Revision 1.5 2012/02/28 17:37:21 nick.price
* Added RetrieveEntity functionality to get definition of an Entity
*
* Revision 1.4 2012/02/27 23:53:32 nick.price
* Improved handling consistency of various Key/Value Types
* AliasedValue fields now preserve the Alias, allowing multiple references to the same Entity Type in one query
* Implemented handling of Retrieve function
* Added limitCount to RetrieveMultiple functions
*
* Revision 1.3 2012/02/27 20:55:05 nick.price
* New function to show possible SoapActions
* Refactored to use RetrieveMultiple directly, rather than via an Execute call
*
* Revision 1.2 2012/02/24 10:12:07 nick.price
* Added functionality for retrieving RecordChangeHistory data
*
* Revision 1.1 2012/02/16 16:38:31 nick.price
* Created Connector Class for Microsoft Dynamics CRM 2011
*
*/
/**
* This class creates and manages SOAP connections to a Microsoft Dynamics CRM 2011 server
*
* Authentication requirements are all handled automatically - although only
* Federation security is current supported, and an Exception is generated if
* any other security method is detected on the server.
*
* The goal of this class is to make it as simple as possible to use SOAP data fetched
* directly from the Dynamics CRM server, without having to manually generate long stretches
* of XML to be converted into SOAP calls.
*
* Additionally, the returned data can be parsed in such a way that it can be used as
* simple PHP Objects, rather than complex XML to be parsed.
*/
class DynamicsCRM2011_Connector extends DynamicsCRM2011 {
/* Organization Details */
private $discoveryURI;
private $organizationUniqueName;
private $organizationURI;
/* Security Details */
private $security = Array();
private $callerId = NULL;
/* Cached Discovery data */
private $discoveryDOM;
private $discoverySoapActions;
private $discoveryExecuteAction;
private $discoverySecurityPolicy;
/* Cached Organization data */
private $organizationDOM;
private $organizationSoapActions;
private $organizationCreateAction;
private $organizationDeleteAction;
private $organizationExecuteAction;
private $organizationRetrieveAction;
private $organizationRetrieveMultipleAction;
private $organizationUpdateAction;
private $organizationSecurityPolicy;
private $organizationSecurityToken;
/* Cached Entity Definitions */
private $cachedEntityDefintions = Array();
/* Connection Details */
protected static $connectorTimeout = 600;
protected static $maximumRecords = self::MAX_CRM_RECORDS;
/**
* Create a new instance of the DynamicsCRM2011Connector
*
* This function is automatically called when a new instance is created.
* At a minimum, you must provide the URL of the DiscoveryService (which can
* be found on the Customizations / Developer Resources section of the Microsoft
* Dynamics CRM 2011 application), and the Unique Name of the Organization to connect
* to. Note that it is often possible to connect to multiple Organizations from a
* single Discovery Service, which is why this parameter is mandatory.
*
* Optionally, you may supply the username & password to login to the server immediately.
*
* @param string $_discoveryURI the URL of the DiscoveryService
* @param string $_organizationUniqueName the Unique Name of the Organization to connect to
* @param string $_username the Username to login with
* @param string $_password the Password of the user
* @param boolean $_debug display debug information when accessing the server - not recommended in Production!
* @return DynamicsCRM2011Connector
*/
function __construct($_discoveryURI, $_organizationUniqueName = NULL, $_username = NULL, $_password = NULL, $_debug = FALSE) {
/* Enable or disable debug mode */
self::$debugMode = $_debug;
/* Check if we're using a cached login */
if (is_array($_discoveryURI)) {
return $this->loadLoginCache($_discoveryURI);
}
/* Store the organization details */
$this->discoveryURI = $_discoveryURI;
$this->organizationUniqueName = $_organizationUniqueName;
/* If either mandatory parameter is NULL, throw an Exception */
if ($this->discoveryURI == NULL || $this->organizationUniqueName == NULL) {
throw new BadMethodCallException(get_class($this).' constructor requires the Discovery URI and Organization Unique Name');
}
/* Store the security details */
$this->security['username'] = $_username;
$this->security['password'] = $_password;
/* Determine the Security used by this Organization */
$this->security['discovery_authmode'] = $this->getDiscoveryAuthenticationMode();
/* Only Federation security is supported */
if ($this->security['discovery_authmode'] != 'Federation') {
throw new UnexpectedValueException(get_class($this).' does not support "'.$this->security['discovery_authmode'].'" authentication mode used by Discovery Service');
}
/* Determine the address to send security requests to */
$this->security['discovery_authuri'] = $this->getDiscoveryAuthenticationAddress();
/* Store the Security Service Endpoint for future use */
$this->security['discovery_authendpoint'] = $this->getFederationSecurityURI('discovery');
/* If we already have all the Discovery Security details, determine the Organization URI */
if ($this->checkSecurity('discovery'))
$this->organizationURI = $this->getOrganizationURI();
}
/**
* Set the Federation Security Details for the Discovery Service
*
* If the constructor was called without the username and password, you must call
* this function to login to the server. Otherwise, all future calls to functions
* to retrieve data will fail.
*
* Note that the current implementation assumes that only one login and password
* is required for both the Discovery and Organization services.
*
* Once the login details are provided, the system will connect to the Discovery service
* and find the URL for the Organization Service for the Organization specified in the
* constructor.
*
* @param string $_username the Username to login with
* @param string $_password the Password of the user
* @return boolean indication as to whether the login details were successfully used to fetch the
* Organization service URL
* @throws Exception if the username or password is missing, or if the system does not use Federation security
*/
public function setDiscoveryFederationSecurity($_username, $_password) {
/* Store the security details */
$this->security['username'] = $_username;
$this->security['password'] = $_password;
/* If either mandatory parameter is NULL, throw an Exception */
if ($this->security['username'] == NULL || $this->security['password'] == NULL) {
throw new BadMethodCallException(get_class($this).' Federation Security requires both a Username & Password');
}
/* Store the Security Service Endpoint for future use */
$this->security['discovery_authendpoint'] = $this->getFederationSecurityURI('discovery');
/* If we already have all the Discovery Security details, determine the Organization URI */
if ($this->checkSecurity('discovery'))
$this->organizationURI = $this->getOrganizationURI();
/* If this failed, return FALSE, otherwise return TRUE */
if ($this->organizationURI == NULL) return FALSE;
return TRUE;
}
/**
* Get the Discovery URL which is currently in use
* @return string the URL of the Discovery Service
*/
public function getDiscoveryURI() {
return $this->discoveryURI;
}
/**
* Get the Organization Unique Name which is currently in use
* @return string the Unique Name of the Organization
*/
public function getOrganization() {
return $this->organizationUniqueName;
}
/**
* Get the maximum records for a query
* @return int the maximum records that will be returned from RetrieveMultiple per page
*/
public static function getMaximumRecords() {
return self::$maximumRecords;
}
/**
* Set the maximum records for a query
* @param int $_maximumRecords the maximum number of records to fetch per page
*/
public static function setMaximumRecords($_maximumRecords) {
if (!is_int($_maximumRecords)) return;
self::$maximumRecords = $_maximumRecords;
}
/**
* Get the connector timeout value
* @return int the maximum time the connector will wait for a response from the CRM in seconds
*/
public static function getConnectorTimeout() {
return self::$connectorTimeout;
}
/**
* Set the connector timeout value
* @param int $_connectorTimeout maximum time the connector will wait for a response from the CRM in seconds
*/
public static function setConnectorTimeout($_connectorTimeout) {
if (!is_int($_connectorTimeout)) return;
self::$connectorTimeout = $_connectorTimeout;
}
/**
* Get the Discovery URL which is currently in use
* @return string the URL of the Organization service
* @throws Exception if the Discovery Service security details have not been set,
* or the Organization Service URL cannot be found for the current Organization
*/
public function getOrganizationURI() {
/* If it's set, return the details from the class instance */
if ($this->organizationURI != NULL) return $this->organizationURI;
/* Check we have the appropriate security details for the Discovery Service */
if ($this->checkSecurity('discovery') == FALSE)
throw new Exception('Cannot determine Organization URI before Discovery Service Security Details are set!');
/* Request a Security Token for the Discovery Service */
$securityToken = $this->requestSecurityToken($this->security['discovery_authendpoint'], $this->discoveryURI, $this->security['username'], $this->security['password']);
/* Determine the Soap Action for the Execute method of the Discovery Service */
$discoveryServiceSoapAction = $this->getDiscoveryExecuteAction();
/* Generate a Soap Request for the Retrieve Organization Request method of the Discovery Service */
$discoverySoapRequest = self::generateSoapRequest($this->discoveryURI, $discoveryServiceSoapAction, $securityToken, self::generateRetrieveOrganizationRequest());
$discovery_data = self::getSoapResponse($this->discoveryURI, $discoverySoapRequest);
/* Parse the returned data to determine the correct EndPoint for the OrganizationService for the selected Organization */
$organizationServiceURI = NULL;
$discoveryDOM = new DOMDocument(); $discoveryDOM->loadXML($discovery_data);
if ($discoveryDOM->getElementsByTagName('OrganizationDetail')->length > 0) {
foreach ($discoveryDOM->getElementsByTagName('OrganizationDetail') as $organizationNode) {
if ($organizationNode->getElementsByTagName('UniqueName')->item(0)->textContent == $this->organizationUniqueName) {
foreach ($organizationNode->getElementsByTagName('Endpoints')->item(0)->getElementsByTagName('KeyValuePairOfEndpointTypestringztYlk6OT') as $endpointDOM) {
if ($endpointDOM->getElementsByTagName('key')->item(0)->textContent == 'OrganizationService') {
$organizationServiceURI = $endpointDOM->getElementsByTagName('value')->item(0)->textContent;
break;
}
}
break;
}
}
} else {
throw new Exception('Error fetching Organization details:'.PHP_EOL.$discovery_data);
return FALSE;
}
if ($organizationServiceURI == NULL) {
throw new Exception('Could not find OrganizationService URI for the Organization <'.$this->organizationUniqueName.'>');
return FALSE;
}
$this->organizationURI = $organizationServiceURI;
$this->cacheOrganizationDetails();
return $organizationServiceURI;
}
/**
* Utility function to get the details of the Organization
* Determines the Authenticaion mode, Authentication URL & Endpoint and SoapAction
* @ignore
*/
private function cacheOrganizationDetails() {
/* Check if this is already done... */
if ($this->organizationSoapActions != NULL) return;
/* Determine the Security used by this Organization */
$this->security['organization_authmode'] = $this->getOrganizationAuthenticationMode();
/* Only Federation security is supported */
if ($this->security['organization_authmode'] != 'Federation') {
throw new UnexpectedValueException(get_class($this).' does not support "'.$this->security['organization_authmode'].'" authentication mode used by Organization Service');
}
/* Determine the address to send security requests to */
$this->security['organization_authuri'] = $this->getOrganizationAuthenticationAddress();
/* Store the Security Service Endpoint for future use */
$this->security['organization_authendpoint'] = $this->getFederationSecurityURI('organization');
/* Determine the Soap Action for the Execute method of the Organization Service */
$organizationExecuteAction = $this->getOrganizationExecuteAction();
}
/**
* Utility function to get the SoapAction for the Discovery Service
* @ignore
*/
private function getDiscoveryExecuteAction() {
/* If it's not cached, update the cache */
if ($this->discoveryExecuteAction == NULL) {
$actions = $this->getAllDiscoverySoapActions();
$this->discoveryExecuteAction = $actions['Execute'];
}
return $this->discoveryExecuteAction;
}
/**
* Utility function to get the SoapAction for the Execute method of the Organization Service
* @ignore
*/
private function getOrganizationExecuteAction() {
/* If it's not cached, update the cache */
if ($this->organizationExecuteAction == NULL) {
$actions = $this->getAllOrganizationSoapActions();
$this->organizationExecuteAction = $actions['Execute'];
}
return $this->organizationExecuteAction;
}
/**
* Utility function to get the SoapAction for the RetrieveMultiple method
* @ignore
*/
private function getOrganizationRetrieveMultipleAction() {
/* If it's not cached, update the cache */
if ($this->organizationRetrieveMultipleAction == NULL) {
$actions = $this->getAllOrganizationSoapActions();
$this->organizationRetrieveMultipleAction = $actions['RetrieveMultiple'];
}
return $this->organizationRetrieveMultipleAction;
}
/**
* Utility function to get the SoapAction for the Retrieve method
* @ignore
*/
private function getOrganizationRetrieveAction() {
/* If it's not cached, update the cache */
if ($this->organizationRetrieveAction == NULL) {
$actions = $this->getAllOrganizationSoapActions();
$this->organizationRetrieveAction = $actions['Retrieve'];
}
return $this->organizationRetrieveAction;
}
/**
* Utility function to get the SoapAction for the Create method
* @ignore
*/
private function getOrganizationCreateAction() {
/* If it's not cached, update the cache */
if ($this->organizationCreateAction == NULL) {
$actions = $this->getAllOrganizationSoapActions();
$this->organizationCreateAction = $actions['Create'];
}
return $this->organizationCreateAction;
}
/**
* Utility function to get the SoapAction for the Delete method
* @ignore
*/
private function getOrganizationDeleteAction() {
/* If it's not cached, update the cache */
if ($this->organizationDeleteAction == NULL) {
$actions = $this->getAllOrganizationSoapActions();
$this->organizationDeleteAction = $actions['Delete'];
}
return $this->organizationDeleteAction;
}
/**
* Utility function to get the SoapAction for the Update method
* @ignore
*/
private function getOrganizationUpdateAction() {
/* If it's not cached, update the cache */
if ($this->organizationUpdateAction == NULL) {
$actions = $this->getAllOrganizationSoapActions();
$this->organizationUpdateAction = $actions['Update'];
}
return $this->organizationUpdateAction;
}
/**
* Utility function to validate the security details for the selected service
* @return boolean indicator showing if the security details are okay
* @ignore
*/
private function checkSecurity($service) {
if ($this->security[$service.'_authmode'] == NULL) return FALSE;
switch ($this->security[$service.'_authmode']) {
case 'Federation':
return $this->checkFederationSecurity($service);
break;
}
return FALSE;
}
/**
* Utility function to validate Federation security details for the selected service
* Checks the Authentication Mode is Federation, and verifies all the necessary data exists
* @return boolean indicator showing if the security details are okay
* @ignore
*/
private function checkFederationSecurity($service) {
if ($this->security[$service.'_authmode'] != 'Federation') return FALSE;
if ($this->security[$service.'_authuri'] == NULL) return FALSE;
if ($this->security[$service.'_authendpoint'] == NULL) return FALSE;
if ($this->security['username'] == NULL || $this->security['password'] == NULL) {
return FALSE;
}
return TRUE;
}
/**
* Utility function to generate the XML for a Retrieve Organization request
* This XML can be sent as a SOAP message to the Discovery Service to determine all Organizations
* available on that service.
* @return DOMNode containing the XML for a RetrieveOrganizationRequest message
* @ignore
*/
protected static function generateRetrieveOrganizationRequest() {
$retrieveOrganizationRequestDOM = new DOMDocument();
$executeNode = $retrieveOrganizationRequestDOM->appendChild($retrieveOrganizationRequestDOM->createElementNS('http://schemas.microsoft.com/xrm/2011/Contracts/Discovery', 'Execute'));
$requestNode = $executeNode->appendChild($retrieveOrganizationRequestDOM->createElement('request'));
$requestNode->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'i:type', 'RetrieveOrganizationsRequest');
$requestNode->appendChild($retrieveOrganizationRequestDOM->createElement('AccessType', 'Default'));
$requestNode->appendChild($retrieveOrganizationRequestDOM->createElement('Release', 'Current'));
return $executeNode;
}
/**
* Get the SOAP Endpoint for the Federation Security service
* @ignore
*/
protected function getFederationSecurityURI($service) {
/* If it's set, return the details from the Security array */
if (isset($this->security[$service.'_authendpoint']))
return $this->security[$service.'_authendpoint'];
/* Fetch the WSDL for the Authentication Service as a parseable DOM Document */
if (self::$debugMode) echo 'Getting WSDL data from: '.$this->security[$service.'_authuri'].PHP_EOL;
$authenticationDOM = new DOMDocument();
@$authenticationDOM->load($this->security[$service.'_authuri']);
/* Flatten the WSDL and include all the Imports */
$this->mergeWSDLImports($authenticationDOM);
// Note: Find the real end-point to use for my security request - for now, we hard-code to Trust13 Username & Password using known values
// See http://code.google.com/p/php-dynamics-crm-2011/issues/detail?id=4
$authEndpoint = self::getTrust13UsernameAddress($authenticationDOM);
return $authEndpoint;
}
/**
* Return the Authentication Mode used by the Discovery service
* @ignore
*/
protected function getDiscoveryAuthenticationMode() {
/* If it's set, return the details from the Security array */
if (isset($this->security['discovery_authmode']))
return $this->security['discovery_authmode'];
/* Get the Discovery DOM */
$discoveryDOM = $this->getDiscoveryDOM();
/* Get the Security Policy for the Organization Service from the WSDL */
$this->discoverySecurityPolicy = self::findSecurityPolicy($discoveryDOM, 'DiscoveryService');
/* Find the Authentication type used */
$authType = $this->discoverySecurityPolicy->getElementsByTagName('Authentication')->item(0)->textContent;
return $authType;
}
/**
* Return the Authentication Mode used by the Organization service
* @ignore
*/
protected function getOrganizationAuthenticationMode() {
/* If it's set, return the details from the Security array */
if (isset($this->security['organization_authmode']))
return $this->security['organization_authmode'];
/* Get the Organization DOM */
$organizationDOM = $this->getOrganizationDOM();
/* Get the Security Policy for the Organization Service from the WSDL */
$this->organizationSecurityPolicy = self::findSecurityPolicy($organizationDOM, 'OrganizationService');
/* Find the Authentication type used */
$authType = $this->organizationSecurityPolicy->getElementsByTagName('Authentication')->item(0)->textContent;
return $authType;
}
/**
* Return the Authentication Address used by the Discovery service
* @ignore
*/
protected function getDiscoveryAuthenticationAddress() {
/* 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 = self::findSecurityPolicy($discoveryDOM, 'DiscoveryService');
}
/* Find the Authentication type used */
$authAddress = self::getFederatedSecurityAddress($this->discoverySecurityPolicy);
return $authAddress;
}
/**
* Return the Authentication Address used by the Organization service
* @ignore
*/
protected function getOrganizationAuthenticationAddress() {
/* 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 = self::findSecurityPolicy($organizationDOM, 'OrganizationService');
}
/* Find the Authentication type used */
$authAddress = self::getFederatedSecurityAddress($this->organizationSecurityPolicy);
return $authAddress;
}
/**
* Fetch and flatten the Discovery Service WSDL as a DOM
* @ignore
*/
protected function getDiscoveryDOM() {
/* If it's already been fetched, use the one we have */
if ($this->discoveryDOM != NULL) return $this->discoveryDOM;
/* Fetch the WSDL for the Discovery Service as a parseable DOM Document */
if (self::$debugMode) echo 'Getting WSDL data from: '.$this->discoveryURI.'?wsdl'.PHP_EOL;
$discoveryDOM = new DOMDocument();
@$discoveryDOM->load($this->discoveryURI.'?wsdl');
/* Flatten the WSDL and include all the Imports */
$this->mergeWSDLImports($discoveryDOM);
/* Cache the DOM in the current object */
$this->discoveryDOM = $discoveryDOM;
return $discoveryDOM;
}
/**
* Fetch and flatten the Organization Service WSDL as a DOM
* @ignore
*/
protected function getOrganizationDOM() {
/* If it's already been fetched, use the one we have */
if ($this->organizationDOM != NULL) return $this->organizationDOM;
if ($this->organizationURI == NULL) {
throw new Exception('Cannot get Organization DOM before determining Organization URI');
}
/* Fetch the WSDL for the Organization Service as a parseable DOM Document */
if (self::$debugMode) echo 'Getting WSDL data from: '.$this->organizationURI.'?wsdl'.PHP_EOL;
$organizationDOM = new DOMDocument();
@$organizationDOM->load($this->organizationURI.'?wsdl');
/* Flatten the WSDL and include all the Imports */
$this->mergeWSDLImports($organizationDOM);
/* Cache the DOM in the current object */
$this->organizationDOM = $organizationDOM;
return $organizationDOM;
}
/**
* Get the Trust Address for the Trust13UsernameMixed authentication method
* @ignore
*/
protected static function getTrust13UsernameAddress(DOMDocument $authenticationDOM) {
return self::getTrustAddress($authenticationDOM, 'UserNameWSTrustBinding_IWSTrust13Async');
}
/**
* Search the WSDL from an ADFS server to find the correct end-point for a
* call to RequestSecurityToken with a given set of parmameters
* @ignore
*/
protected static function getTrustAddress(DOMDocument $authenticationDOM, $trustName) {
/* Search the available Ports on the WSDL */
$trustAuthNode = NULL;
foreach ($authenticationDOM->getElementsByTagName('port') as $portNode) {
if ($portNode->hasAttribute('name') && $portNode->getAttribute('name') == $trustName) {
$trustAuthNode = $portNode;
break;
}
}
if ($trustAuthNode == NULL) {
throw new Exception('Could not find Port for trust type <'.$trustName.'> in provided WSDL');
return FALSE;
}
/* Get the Address from the Port */
$authenticationURI = NULL;
if ($trustAuthNode->getElementsByTagName('address')->length > 0) {
$authenticationURI = $trustAuthNode->getElementsByTagName('address')->item(0)->getAttribute('location');
}
if ($authenticationURI == NULL) {
throw new Exception('Could not find Address for trust type <'.$trustName.'> in provided WSDL');
return FALSE;
}
/* Return the found URI */
return $authenticationURI;
}
/**
* 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) {
static $rootNode = NULL;
static $rootDocument = NULL;
/* If this is an external call, find the "root" defintions node */
if ($continued == false) {
$rootNode = $wsdlDOM->getElementsByTagName('definitions')->item(0);
$rootDocument = $wsdlDOM;
}
if ($newRootDocument == NULL) $newRootDocument = $rootDocument;
//if (self::$debugMode) echo "Processing Node: ".$wsdlDOM->nodeName." which has ".$wsdlDOM->childNodes->length." child nodes".PHP_EOL;
$nodesToRemove = Array();
/* Loop through the Child nodes of the provided DOM */
foreach ($wsdlDOM->childNodes as $childNode) {
//if (self::$debugMode) echo "\tProcessing Child Node: ".$childNode->nodeName." (".$childNode->localName.") which has ".$childNode->childNodes->length." child nodes".PHP_EOL;
/* 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 */
if ($childNode->hasAttribute('location')) {
$importURI = $childNode->getAttribute('location');
} else if ($childNode->hasAttribute('schemaLocation')) {
$importURI = $childNode->getAttribute('schemaLocation');
} else {
$importURI = NULL;
}
/* Only import if we found a URI - otherwise, don't change it! */
if ($importURI != NULL) {
if (self::$debugMode) echo "\tImporting data from: ".$importURI.PHP_EOL;
$importDOM = new DOMDocument();
@$importDOM->load($importURI);
/* 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) {
//if (self::$debugMode) echo "\t\tInserting Child: ".$importNode->C14N(true).PHP_EOL;
$importNode = $newRootDocument->importNode($importNode, true);
$wsdlDOM->insertBefore($importNode, $childNode);
}
} else {
//if (self::$debugMode) echo "\t\tInserting Child: ".$importNode->C14N(true).PHP_EOL;
$importNode = $newRootDocument->importNode($importDOM->firstChild, true);
$wsdlDOM->insertBefore($importNode, $childNode);
}
//if (self::$debugMode) echo "\t\tRemoving Child: ".$childNode->C14N(true).PHP_EOL;
$nodesToRemove[] = $childNode;
}
} else {
//if (self::$debugMode) echo 'Preserving node: '.$childNode->localName.PHP_EOL;
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;
}
/**
* Search a Microsoft Dynamics CRM 2011 WSDL for the Security Policy for a given Service
* @ignore
*/
protected static function findSecurityPolicy(DOMDocument $wsdlDocument, $serviceName) {
/* 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');
return FALSE;
}
/* 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');
return FALSE;
}
/* 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 defintion of Binding <'.$bindingName.'> in provided WSDL');
return FALSE;
}
/* 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');
return FALSE;
}
/* Find the Security Policy from the WSDL */
$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 FALSE;
}
/* Return the selected node */
return $securityPolicyNode;
}
/**
* Search a Microsoft Dynamics CRM 2011 WSDL for all available Operations/SoapActions on a Service
* @ignore
*/
private static function getAllSoapActions(DOMDocument $wsdlDocument, $serviceName) {
/* 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');
return FALSE;
}
/* 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');
return FALSE;
}
/* 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 defintion of Binding <'.$bindingName.'> in provided WSDL');
return FALSE;
}
/* Array to store the list of Operations and SoapActions */
$operationArray = Array();
/* Find the Operations */
foreach ($bindingNode->getElementsByTagName('operation') as $operationNode) {
if ($operationNode->hasAttribute('name')) {
/* Record the Name of this Operation */
$operationName = $operationNode->getAttribute('name');
/* Find the Operation SoapAction from the WSDL */
foreach ($operationNode->getElementsByTagName('operation') as $soap12OperationNode) {
if ($soap12OperationNode->hasAttribute('soapAction')) {
/* Record the SoapAction for this Operation */
$soapAction = $soap12OperationNode->getAttribute('soapAction');
/* Store the soapAction in the Array */
$operationArray[$operationName] = $soapAction;
}
}
unset($soap12OperationNode);
}
}
/* Return the array of available actions */
return $operationArray;
}
/**
* Get all the Operations & corresponding SoapActions for the DiscoveryService
*/
public function getAllDiscoverySoapActions() {
/* If it is not cached, update the cache */
if ($this->discoverySoapActions == NULL) {
$this->discoverySoapActions = self::getAllSoapActions($this->getDiscoveryDOM(), 'DiscoveryService');
}
/* Return the cached value */
return $this->discoverySoapActions;
}
/**
* Get all the Operations & corresponding SoapActions for the OrganizationService
*/
public function getAllOrganizationSoapActions() {
/* If it is not cached, update the cache */
if ($this->organizationSoapActions == NULL) {
$this->organizationSoapActions = self::getAllSoapActions($this->getOrganizationDOM(), 'OrganizationService');
}
/* Return the cached value */
return $this->organizationSoapActions;
}
/**
* Search a Microsoft Dynamics CRM 2011 WSDL for the SoapAction for a given Operation on a Service
* @ignore
* @deprecated No longer required, as we now use getAllSoapActions instead
*/
protected static function findSoapAction(DOMDocument $wsdlDocument, $serviceName, $operationName) {
/* 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');
return FALSE;
}
/* 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');
return FALSE;
}
/* 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 defintion of Binding <'.$bindingName.'> in provided WSDL');
return FALSE;
}
/* Find the Operation Definition */
$serviceOperationNode = NULL;
foreach ($bindingNode->getElementsByTagName('operation') as $operationNode) {
if ($operationNode->hasAttribute('name') && $operationNode->getAttribute('name') == $operationName) {
$serviceOperationNode = $operationNode;
break;
}
}
if ($serviceOperationNode == NULL) {
throw new Exception('Could not find Operation <'.$operationName.'> for Binding <'.$bindingName.'> in provided WSDL');
return FALSE;
}
/* Find the Operation SoapAction from the WSDL */
$soapAction = NULL;
foreach ($serviceOperationNode->getElementsByTagName('operation') as $soap12OperationNode) {
if ($soap12OperationNode->hasAttribute('soapAction')) {
$soapAction = $soap12OperationNode->getAttribute('soapAction');
break;
}
}
if ($soapAction == NULL) {
throw new Exception('Could not find SoapAction for Operation <'.$operationName.'> on Service <'.$serviceName.'> in provided WSDL');
return FALSE;
}
/* Return the selected node */
return $soapAction;
}
/**
* Search a Microsoft Dynamics CRM 2011 Security Policy for the Address for the Federated Security
* @ignore
*/
protected static function getFederatedSecurityAddress(DOMNode $securityPolicyNode) {
$securityURL = NULL;
/* Find the EndorsingSupportingTokens tag */
if ($securityPolicyNode->getElementsByTagName('EndorsingSupportingTokens')->length == 0) {
throw new Exception('Could not find EndorsingSupportingTokens tag in provided security policy XML');
return FALSE;
}
$estNode = $securityPolicyNode->getElementsByTagName('EndorsingSupportingTokens')->item(0);
/* Find the Policy tag */
if ($estNode->getElementsByTagName('Policy')->length == 0) {
throw new Exception('Could not find EndorsingSupportingTokens/Policy tag in provided security policy XML');
return FALSE;
}
$estPolicyNode = $estNode->getElementsByTagName('Policy')->item(0);
/* Find the IssuedToken tag */
if ($estPolicyNode->getElementsByTagName('IssuedToken')->length == 0) {
throw new Exception('Could not find EndorsingSupportingTokens/Policy/IssuedToken tag in provided security policy XML');
return FALSE;
}
$issuedTokenNode = $estPolicyNode->getElementsByTagName('IssuedToken')->item(0);
/* Find the Issuer tag */
if ($issuedTokenNode->getElementsByTagName('Issuer')->length == 0) {
throw new Exception('Could not find EndorsingSupportingTokens/Policy/IssuedToken/Issuer tag in provided security policy XML');
return FALSE;
}
$issuerNode = $issuedTokenNode->getElementsByTagName('Issuer')->item(0);
/* Find the Metadata tag */
if ($issuerNode->getElementsByTagName('Metadata')->length == 0) {
throw new Exception('Could not find EndorsingSupportingTokens/Policy/IssuedToken/Issuer/Metadata tag in provided security policy XML');
return FALSE;
}
$metadataNode = $issuerNode->getElementsByTagName('Metadata')->item(0);
/* Find the Address tag */
if ($metadataNode->getElementsByTagName('Address')->length == 0) {
throw new Exception('Could not find EndorsingSupportingTokens/Policy/IssuedToken/Issuer/Metadata/.../Address tag in provided security policy XML');
return FALSE;
}
$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 FALSE;
}
return $securityURL;
}
/**
* Request a Security Token from the ADFS server using Username & Password authentication
* @ignore
*/
protected function requestSecurityToken($securityServerURI, $loginEndpoint, $loginUsername, $loginPassword) {
/* Generate the Security Token Request XML */