summaryrefslogtreecommitdiff
path: root/inc/adLDAP.php
blob: 209daf37f8871d9eabef8ebbf9170fb1ee28a7b0 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
<?php
/**
 * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
 * Version 3.1
 *
 * PHP Version 5 with SSL and LDAP support
 *
 * Written by Scott Barnett, Richard Hyland
 *   email: scott@wiggumworld.com, adldap@richardhyland.com
 *   http://adldap.sourceforge.net/
 *
 * Copyright (c) 2006-2009 Scott Barnett, Richard Hyland
 *
 * We'd appreciate any improvements or additions to be submitted back
 * to benefit the entire community :)
 *
 * This library 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; either
 * version 2.1 of the License.
 *
 * This library 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 Public License for more details.
 *
 * @category ToolsAndUtilities
 * @package adLDAP
 * @author Scott Barnett, Richard Hyland
 * @copyright (c) 2006-2009 Scott Barnett, Richard Hyland
 * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
 * @revision $Revision: 34 $
 * @version 3.1
 * @link http://adldap.sourceforge.net/
 */

/**
 * Define the different types of account in AD
 */
define ('ADLDAP_NORMAL_ACCOUNT', 805306368);
define ('ADLDAP_WORKSTATION_TRUST', 805306369);
define ('ADLDAP_INTERDOMAIN_TRUST', 805306370);
define ('ADLDAP_SECURITY_GLOBAL_GROUP', 268435456);
define ('ADLDAP_DISTRIBUTION_GROUP', 268435457);
define ('ADLDAP_SECURITY_LOCAL_GROUP', 536870912);
define ('ADLDAP_DISTRIBUTION_LOCAL_GROUP', 536870913);

/**
* Main adLDAP class
*
* Can be initialised using $adldap = new adLDAP();
*
* Something to keep in mind is that Active Directory is a permissions
* based directory. If you bind as a domain user, you can't fetch as
* much information on other users as you could as a domain admin.
*
* Before asking questions, please read the Documentation at
* http://adldap.sourceforge.net/wiki/doku.php?id=api
*/
class adLDAP {
    /**
    * The account suffix for your domain, can be set when the class is invoked
    *
    * @var string
    */
    protected $_account_suffix="@mydomain.local";

    /**
    * The base dn for your domain
    *
    * @var string
    */
    protected $_base_dn = "DC=mydomain,DC=local";

    /**
    * Array of domain controllers. Specifiy multiple controllers if you
    * would like the class to balance the LDAP queries amongst multiple servers
    *
    * @var array
    */
    protected $_domain_controllers = array ("dc01.mydomain.local");

    /**
    * Optional account with higher privileges for searching
    * This should be set to a domain admin account
    *
    * @var string
    * @var string
    */
    protected $_ad_username=NULL;
    protected $_ad_password=NULL;

    /**
    * AD does not return the primary group. http://support.microsoft.com/?kbid=321360
    * This tweak will resolve the real primary group.
    * Setting to false will fudge "Domain Users" and is much faster. Keep in mind though that if
    * someone's primary group is NOT domain users, this is obviously going to mess up the results
    *
    * @var bool
    */
    protected $_real_primarygroup=true;

    /**
    * Use SSL, your server needs to be setup, please see
    * http://adldap.sourceforge.net/wiki/doku.php?id=ldap_over_ssl
    *
    * @var bool
    */
    protected $_use_ssl=false;

    /**
    * When querying group memberships, do it recursively
    * eg. User Fred is a member of Group A, which is a member of Group B, which is a member of Group C
    * user_ingroup("Fred","C") will returns true with this option turned on, false if turned off
    *
    * @var bool
    */
    protected $_recursive_groups=true;

    // You should not need to edit anything below this line
    //******************************************************************************************

    /**
    * Connection and bind default variables
    *
    * @var mixed
    * @var mixed
    */
    protected $_conn;
    protected $_bind;

    /**
    * Default Constructor
    *
    * Tries to bind to the AD domain over LDAP or LDAPs
    *
    * @param array $options Array of options to pass to the constructor
    * @throws Exception - if unable to bind to Domain Controller
    * @return bool
    */
    function __construct($options=array()){
        // You can specifically overide any of the default configuration options setup above
        if (count($options)>0){
            if (array_key_exists("account_suffix",$options)){ $this->_account_suffix=$options["account_suffix"]; }
            if (array_key_exists("base_dn",$options)){ $this->_base_dn=$options["base_dn"]; }
            if (array_key_exists("domain_controllers",$options)){ $this->_domain_controllers=$options["domain_controllers"]; }
            if (array_key_exists("ad_username",$options)){ $this->_ad_username=$options["ad_username"]; }
            if (array_key_exists("ad_password",$options)){ $this->_ad_password=$options["ad_password"]; }
            if (array_key_exists("real_primarygroup",$options)){ $this->_real_primarygroup=$options["real_primarygroup"]; }
            if (array_key_exists("use_ssl",$options)){ $this->_use_ssl=$options["use_ssl"]; }
            if (array_key_exists("recursive_groups",$options)){ $this->_recursive_groups=$options["recursive_groups"]; }
        }

        // Connect to the AD/LDAP server as the username/password
        $dc=$this->random_controller();
        if ($this->_use_ssl){
            $this->_conn = ldap_connect("ldaps://".$dc, 636);
        } else {
            $this->_conn = ldap_connect($dc);
        }

        // Set some ldap options for talking to AD
        ldap_set_option($this->_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($this->_conn, LDAP_OPT_REFERRALS, 0);

        // Bind as a domain admin if they've set it up
        if ($this->_ad_username!=NULL && $this->_ad_password!=NULL){
            $this->_bind = @ldap_bind($this->_conn,$this->_ad_username.$this->_account_suffix,$this->_ad_password);
            if (!$this->_bind){
                if ($this->_use_ssl){
                    // If you have problems troubleshooting, remove the @ character from the ldap_bind command above to get the actual error message
                    throw new adLDAPException('Bind to Active Directory failed. Either the LDAPs connection failed or the login credentials are incorrect. AD said: ' . $this->get_last_error());
                } else {
                    throw new adLDAPException('Bind to Active Directory failed. Check the login credentials and/or server details. AD said: ' . $this->get_last_error());
                }
            }
        }

        return (true);
    }

    /**
    * Default Destructor
    *
    * Closes the LDAP connection
    *
    * @return void
    */
    function __destruct(){ ldap_close ($this->_conn); }

    /**
    * Validate a user's login credentials
    *
    * @param string $username A user's AD username
    * @param string $password A user's AD password
    * @param bool optional $prevent_rebind
    * @return bool
    */
    public function authenticate($username,$password,$prevent_rebind=false){
        // Prevent null binding
        if ($username==NULL || $password==NULL){ return (false); }

        // Bind as the user
        $this->_bind = @ldap_bind($this->_conn,$username.$this->_account_suffix,$password);
        if (!$this->_bind){ return (false); }

        // Cnce we've checked their details, kick back into admin mode if we have it
        if ($this->_ad_username!=NULL && !$prevent_rebind){
            $this->_bind = @ldap_bind($this->_conn,$this->_ad_username.$this->_account_suffix,$this->_ad_password);
            if (!$this->_bind){
                // This should never happen in theory
                throw new adLDAPException('Rebind to Active Directory failed. AD said: ' . $this->get_last_error());
            }
        }

        return (true);
    }

    //*****************************************************************************************************************
    // GROUP FUNCTIONS

    /**
    * Add a group to a group
    *
    * @param string $parent The parent group name
    * @param string $child The child group name
    * @return bool
    */
    public function group_add_group($parent,$child){

        // Find the parent group's dn
        $parent_group=$this->group_info($parent,array("cn"));
        if ($parent_group[0]["dn"]==NULL){ return (false); }
        $parent_dn=$parent_group[0]["dn"];

        // Find the child group's dn
        $child_group=$this->group_info($child,array("cn"));
        if ($child_group[0]["dn"]==NULL){ return (false); }
        $child_dn=$child_group[0]["dn"];

        $add=array();
        $add["member"] = $child_dn;

        $result=@ldap_mod_add($this->_conn,$parent_dn,$add);
        if ($result==false){ return (false); }
        return (true);
    }

    /**
    * Add a user to a group
    *
    * @param string $group The group to add the user to
    * @param string $user The user to add to the group
    * @return bool
    */
    public function group_add_user($group,$user){
        // Adding a user is a bit fiddly, we need to get the full DN of the user
        // and add it using the full DN of the group

        // Find the user's dn
        $user_dn=$this->user_dn($user);
        if ($user_dn===false){ return (false); }

        // Find the group's dn
        $group_info=$this->group_info($group,array("cn"));
        if ($group_info[0]["dn"]==NULL){ return (false); }
        $group_dn=$group_info[0]["dn"];

        $add=array();
        $add["member"] = $user_dn;

        $result=@ldap_mod_add($this->_conn,$group_dn,$add);
        if ($result==false){ return (false); }
        return (true);
    }

    /**
    * Add a contact to a group
    *
    * @param string $group The group to add the contact to
    * @param string $contact_dn The DN of the contact to add
    * @return bool
    */
    public function group_add_contact($group,$contact_dn){
        // To add a contact we take the contact's DN
        // and add it using the full DN of the group

        // Find the group's dn
        $group_info=$this->group_info($group,array("cn"));
        if ($group_info[0]["dn"]==NULL){ return (false); }
        $group_dn=$group_info[0]["dn"];

        $add=array();
        $add["member"] = $contact_dn;

        $result=@ldap_mod_add($this->_conn,$group_dn,$add);
        if ($result==false){ return (false); }
        return (true);
    }

    /**
    * Create a group
    *
    * @param array $attributes Default attributes of the group
    * @return bool
    */
    public function group_create($attributes){
        if (!is_array($attributes)){ return ("Attributes must be an array"); }
        if (!array_key_exists("group_name",$attributes)){ return ("Missing compulsory field [group_name]"); }
        if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); }
        if (!array_key_exists("description",$attributes)){ return ("Missing compulsory field [description]"); }
        if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }
        $attributes["container"]=array_reverse($attributes["container"]);

        //$member_array = array();
        //$member_array[0] = "cn=user1,cn=Users,dc=yourdomain,dc=com";
        //$member_array[1] = "cn=administrator,cn=Users,dc=yourdomain,dc=com";

        $add=array();
        $add["cn"] = $attributes["group_name"];
        $add["samaccountname"] = $attributes["group_name"];
        $add["objectClass"] = "Group";
        $add["description"] = $attributes["description"];
        //$add["member"] = $member_array; UNTESTED

        $container="OU=".implode(",OU=",$attributes["container"]);
        $result=ldap_add($this->_conn,"CN=".$add["cn"].", ".$container.",".$this->_base_dn,$add);
        if ($result!=true){ return (false); }

        return (true);
    }

    /**
    * Remove a group from a group
    *
    * @param string $parent The parent group name
    * @param string $child The child group name
    * @return bool
    */
    public function group_del_group($parent,$child){

        // Find the parent dn
        $parent_group=$this->group_info($parent,array("cn"));
        if ($parent_group[0]["dn"]==NULL){ return (false); }
        $parent_dn=$parent_group[0]["dn"];

        // Find the child dn
        $child_group=$this->group_info($child,array("cn"));
        if ($child_group[0]["dn"]==NULL){ return (false); }
        $child_dn=$child_group[0]["dn"];

        $del=array();
        $del["member"] = $child_dn;

        $result=@ldap_mod_del($this->_conn,$parent_dn,$del);
        if ($result==false){ return (false); }
        return (true);
    }

    /**
    * Remove a user from a group
    *
    * @param string $group The group to remove a user from
    * @param string $user The AD user to remove from the group
    * @return bool
    */
    public function group_del_user($group,$user){

        // Find the parent dn
        $group_info=$this->group_info($group,array("cn"));
        if ($group_info[0]["dn"]==NULL){ return (false); }
        $group_dn=$group_info[0]["dn"];

        // Find the users dn
        $user_dn=$this->user_dn($user);
        if ($user_dn===false){ return (false); }

        $del=array();
        $del["member"] = $user_dn;

        $result=@ldap_mod_del($this->_conn,$group_dn,$del);
        if ($result==false){ return (false); }
        return (true);
    }

    /**
    * Remove a contact from a group
    *
    * @param string $group The group to remove a user from
    * @param string $contact_dn The DN of a contact to remove from the group
    * @return bool
    */
    public function group_del_contact($group,$contact_dn){

        // Find the parent dn
        $group_info=$this->group_info($group,array("cn"));
        if ($group_info[0]["dn"]==NULL){ return (false); }
        $group_dn=$group_info[0]["dn"];

        $del=array();
        $del["member"] = $contact_dn;

        $result=@ldap_mod_del($this->_conn,$group_dn,$del);
        if ($result==false){ return (false); }
        return (true);
    }

    /**
    * Return a list of members in a group
    *
    * @param string $group The group to query
    * @return array
    */
    public function group_members($group){
        if (!$this->_bind){ return (false); }
        // Search the directory for the members of a group
        $info=$this->group_info($group,array("member","cn"));
        $users=$info[0]["member"];
        if (!is_array($users)) {
            return (false);
        }

        $user_array=array();

        for ($i=0; $i<$users["count"]; $i++){
             $filter="(&(objectCategory=person)(distinguishedName=".$this->ldap_slashes($users[$i])."))";
             $fields = array("samaccountname", "distinguishedname");
             $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
             $entries = ldap_get_entries($this->_conn, $sr);
             if ($entries[0]['samaccountname'][0] == NULL) {
                 $user_array[$i] = $entries[0]['distinguishedname'][0];
             }
             else {
                $user_array[$i] = $entries[0]['samaccountname'][0];
             }
        }
        return ($user_array);
    }

    /**
    * Group Information.  Returns an array of information about a group.
    * The group name is case sensitive
    *
    * @param string $group_name The group name to retrieve info about
    * @param array $fields Fields to retrieve
    * @return array
    */
    public function group_info($group_name,$fields=NULL){
        if ($group_name==NULL){ return (false); }
        if (!$this->_bind){ return (false); }

        $filter="(&(objectCategory=group)(name=".$this->ldap_slashes($group_name)."))";
        //echo ($filter."!!!<br>");
        if ($fields==NULL){ $fields=array("member","memberof","cn","description","distinguishedname","objectcategory","samaccountname"); }
        $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        $entries = ldap_get_entries($this->_conn, $sr);
        //print_r($entries);
        return ($entries);
    }

    /**
    * Return a complete list of "groups in groups"
    *
    * @param string $group The group to get the list from
    * @return array
    */
    public function recursive_groups($group){
        if ($group==NULL){ return (false); }

        $ret_groups=array();

        $groups=$this->group_info($group,array("memberof"));
        $groups=$groups[0]["memberof"];

        if ($groups){
            $group_names=$this->nice_names($groups);
            $ret_groups=array_merge($ret_groups,$group_names); //final groups to return

            foreach ($group_names as $id => $group_name){
                $child_groups=$this->recursive_groups($group_name);
                $ret_groups=array_merge($ret_groups,$child_groups);
            }
        }

        return ($ret_groups);
    }

    /**
    * Returns a complete list of the groups in AD based on a SAM Account Type
    *
    * @param string $samaccounttype The account type to return
    * @param bool $include_desc Whether to return a description
    * @param string $search Search parameters
    * @param bool $sorted Whether to sort the results
    * @return array
    */
    public function search_groups($samaccounttype = ADLDAP_SECURITY_GLOBAL_GROUP, $include_desc = false, $search = "*", $sorted = true) {
        if (!$this->_bind){ return (false); }

        // Perform the search and grab all their details
        $filter = "(&(objectCategory=group)(samaccounttype=". $samaccounttype .")(cn=".$search."))";
        $fields=array("samaccountname","description");
        $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        $entries = ldap_get_entries($this->_conn, $sr);

        $groups_array = array();
        for ($i=0; $i<$entries["count"]; $i++){
            if ($include_desc && strlen($entries[$i]["description"][0]) > 0 ){
                $groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["description"][0];
            } elseif ($include_desc){
                $groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0];
            } else {
                array_push($groups_array, $entries[$i]["samaccountname"][0]);
            }
        }
        if( $sorted ){ asort($groups_array); }
        return ($groups_array);
    }

    /**
    * Returns a complete list of security groups in AD
    *
    * @param bool $include_desc Whether to return a description
    * @param string $search Search parameters
    * @param bool $sorted Whether to sort the results
    * @return array
    */
    public function all_groups($include_desc = false, $search = "*", $sorted = true){
        $groups_array = $this->search_groups(ADLDAP_SECURITY_GLOBAL_GROUP, $include_desc, $search, $sorted);
        return ($groups_array);
    }

    /**
    * Returns a complete list of distribution lists in AD
    *
    * @param bool $include_desc Whether to return a description
    * @param string $search Search parameters
    * @param bool $sorted Whether to sort the results
    * @return array
    */
    public function all_distribution_groups($include_desc = false, $search = "*", $sorted = true){
        $groups_array = $this->search_groups(ADLDAP_DISTRIBUTION_GROUP, $include_desc, $search, $sorted);
        return ($groups_array);
    }

    //*****************************************************************************************************************
    // USER FUNCTIONS

    /**
    * Create a user
    *
    * If you specify a password here, this can only be performed over SSL
    *
    * @param array $attributes The attributes to set to the user account
    * @return bool
    */
    public function user_create($attributes){
        // Check for compulsory fields
        if (!array_key_exists("username",$attributes)){ return ("Missing compulsory field [username]"); }
        if (!array_key_exists("firstname",$attributes)){ return ("Missing compulsory field [firstname]"); }
        if (!array_key_exists("surname",$attributes)){ return ("Missing compulsory field [surname]"); }
        if (!array_key_exists("email",$attributes)){ return ("Missing compulsory field [email]"); }
        if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); }
        if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }

        if (array_key_exists("password",$attributes) && !$this->_use_ssl){
            throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
        }

        if (!array_key_exists("display_name",$attributes)){ $attributes["display_name"]=$attributes["firstname"]." ".$attributes["surname"]; }

        // Translate the schema
        $add=$this->adldap_schema($attributes);

        // Additional stuff only used for adding accounts
        $add["cn"][0]=$attributes["display_name"];
        $add["samaccountname"][0]=$attributes["username"];
        $add["objectclass"][0]="top";
        $add["objectclass"][1]="person";
        $add["objectclass"][2]="organizationalPerson";
        $add["objectclass"][3]="user"; //person?
        //$add["name"][0]=$attributes["firstname"]." ".$attributes["surname"];

        // Set the account control attribute
        $control_options=array("NORMAL_ACCOUNT");
        if (!$attributes["enabled"]){ $control_options[]="ACCOUNTDISABLE"; }
        $add["userAccountControl"][0]=$this->account_control($control_options);
        //echo ("<pre>"); print_r($add);

        // Determine the container
        $attributes["container"]=array_reverse($attributes["container"]);
        $container="OU=".implode(",OU=",$attributes["container"]);

        // Add the entry
        $result=@ldap_add($this->_conn, "CN=".$add["cn"][0].", ".$container.",".$this->_base_dn, $add);
        if ($result!=true){ return (false); }

        return (true);
    }

    /**
    * Delete a user account
    *
    * @param string $username The username to delete (please be careful here!)
    * @return array
    */
    public function user_delete($username) {
        $userinfo = $this->user_info($username, array("*"));
        $dn = $userinfo[0]['distinguishedname'][0];
        $result=$this->dn_delete($dn);
        if ($result!=true){ return (false); }
        return (true);
    }

    /**
    * Groups the user is a member of
    *
    * @param string $username The username to query
    * @param bool $recursive Recursive list of groups
    * @return array
    */
    public function user_groups($username,$recursive=NULL){
        if ($username==NULL){ return (false); }
        if ($recursive==NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it
        if (!$this->_bind){ return (false); }

        // Search the directory for their information
        $info=@$this->user_info($username,array("memberof","primarygroupid"));
        $groups=$this->nice_names($info[0]["memberof"]); // Presuming the entry returned is our guy (unique usernames)

        if ($recursive){
            foreach ($groups as $id => $group_name){
                $extra_groups=$this->recursive_groups($group_name);
                $groups=array_merge($groups,$extra_groups);
            }
        }

        return ($groups);
    }

    /**
    * Find information about the users
    *
    * @param string $username The username to query
    * @param array $fields Array of parameters to query
    * @return array
    */
    public function user_info($username,$fields=NULL){
        if ($username==NULL){ return (false); }
        if (!$this->_bind){ return (false); }

        $filter="samaccountname=".$username;
        if ($fields==NULL){ $fields=array("samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); }
        $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        $entries = ldap_get_entries($this->_conn, $sr);

        if ($entries[0]['count'] >= 1) {
            // AD does not return the primary group in the ldap query, we may need to fudge it
            if ($this->_real_primarygroup && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["objectsid"][0])){
                //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);
                $entries[0]["memberof"][]=$this->get_primary_group($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]);
            } else {
                $entries[0]["memberof"][]="CN=Domain Users,CN=Users,".$this->_base_dn;
            }
        }

        $entries[0]["memberof"]["count"]++;
        return ($entries);
    }

    /**
    * Determine if a user is in a specific group
    *
    * @param string $username The username to query
    * @param string $group The name of the group to check against
    * @param bool $recursive Check groups recursively
    * @return bool
    */
    public function user_ingroup($username,$group,$recursive=NULL){
        if ($username==NULL){ return (false); }
        if ($group==NULL){ return (false); }
        if (!$this->_bind){ return (false); }
        if ($recursive==NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it

        // Get a list of the groups
        $groups=$this->user_groups($username,array("memberof"),$recursive);

        // Return true if the specified group is in the group list
        if (in_array($group,$groups)){ return (true); }

        return (false);
    }

    /**
    * Modify a user
    *
    * @param string $username The username to query
    * @param array $attributes The attributes to modify.  Note if you set the enabled attribute you must not specify any other attributes
    * @return bool
    */
    public function user_modify($username,$attributes){
        if ($username==NULL){ return ("Missing compulsory field [username]"); }
        if (array_key_exists("password",$attributes) && !$this->_use_ssl){
            throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
        }
        //if (array_key_exists("container",$attributes)){
            //if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }
            //$attributes["container"]=array_reverse($attributes["container"]);
        //}

        // Find the dn of the user
        $user_dn=$this->user_dn($username);
        if ($user_dn===false){ return (false); }

        // Translate the update to the LDAP schema
        $mod=$this->adldap_schema($attributes);

        // Check to see if this is an enabled status update
        if (!$mod && !array_key_exists("enabled", $attributes)){ return (false); }

        // Set the account control attribute (only if specified)
        if (array_key_exists("enabled",$attributes)){
            if ($attributes["enabled"]){ $control_options=array("NORMAL_ACCOUNT"); }
            else { $control_options=array("NORMAL_ACCOUNT","ACCOUNTDISABLE"); }
            $mod["userAccountControl"][0]=$this->account_control($control_options);
        }

        // Do the update
        $result=@ldap_modify($this->_conn,$user_dn,$mod);
        if ($result==false){ return (false); }

        return (true);
    }

    /**
    * Disable a user account
    *
    * @param string $username The username to disable
    * @return bool
    */
    public function user_disable($username){
        if ($username==NULL){ return ("Missing compulsory field [username]"); }
        $attributes=array("enabled"=>0);
        $result = $this->user_modify($username, $attributes);
        if ($result==false){ return (false); }

        return (true);
    }

    /**
    * Enable a user account
    *
    * @param string $username The username to enable
    * @return bool
    */
    public function user_enable($username){
        if ($username==NULL){ return ("Missing compulsory field [username]"); }
        $attributes=array("enabled"=>1);
        $result = $this->user_modify($username, $attributes);
        if ($result==false){ return (false); }

        return (true);
    }

    /**
    * Set the password of a user - This must be performed over SSL
    *
    * @param string $username The username to modify
    * @param string $password The new password
    * @return bool
    */
    public function user_password($username,$password){
        if ($username==NULL){ return (false); }
        if ($password==NULL){ return (false); }
        if (!$this->_bind){ return (false); }
        if (!$this->_use_ssl){
            throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
        }

        $user_dn=$this->user_dn($username);
        if ($user_dn===false){ return (false); }

        $add=array();
        $add["unicodePwd"][0]=$this->encode_password($password);

        $result=ldap_mod_replace($this->_conn,$user_dn,$add);
        if ($result==false){ return (false); }

        return (true);
    }

    /**
    * Return a list of all users in AD
    *
    * @param bool $include_desc Return a description of the user
    * @param string $search Search parameter
    * @param bool $sorted Sort the user accounts
    * @return array
    */
    public function all_users($include_desc = false, $search = "*", $sorted = true){
        if (!$this->_bind){ return (false); }

        // Perform the search and grab all their details
        $filter = "(&(objectClass=user)(samaccounttype=". ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=".$search."))";
        $fields=array("samaccountname","displayname");
        $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        $entries = ldap_get_entries($this->_conn, $sr);

        $users_array = array();
        for ($i=0; $i<$entries["count"]; $i++){
            if ($include_desc && strlen($entries[$i]["displayname"][0])>0){
                $users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["displayname"][0];
            } elseif ($include_desc){
                $users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0];
            } else {
                array_push($users_array, $entries[$i]["samaccountname"][0]);
            }
        }
        if ($sorted){ asort($users_array); }
        return ($users_array);
    }

    //*****************************************************************************************************************
    // CONTACT FUNCTIONS
    // * Still work to do in this area, and new functions to write

    /**
    * Create a contact
    *
    * @param array $attributes The attributes to set to the contact
    * @return bool
    */
    public function contact_create($attributes){
        // Check for compulsory fields
        if (!array_key_exists("display_name",$attributes)){ return ("Missing compulsory field [display_name]"); }
        if (!array_key_exists("email",$attributes)){ return ("Missing compulsory field [email]"); }
        if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); }
        if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }

        // Translate the schema
        $add=$this->adldap_schema($attributes);

        // Additional stuff only used for adding contacts
        $add["cn"][0]=$attributes["display_name"];
        $add["objectclass"][0]="top";
        $add["objectclass"][1]="person";
        $add["objectclass"][2]="organizationalPerson";
        $add["objectclass"][3]="contact";
        if (!isset($attributes['exchange_hidefromlists'])) {
            $add["msExchHideFromAddressLists"][0]="TRUE";
        }

        // Determine the container
        $attributes["container"]=array_reverse($attributes["container"]);
        $container="OU=".implode(",OU=",$attributes["container"]);

        // Add the entry
        $result=@ldap_add($this->_conn, "CN=".$add["cn"][0].", ".$container.",".$this->_base_dn, $add);
        if ($result!=true){ return (false); }

        return (true);
    }

    /**
    * Determine the list of groups a contact is a member of
    *
    * @param string $distinguisedname The full DN of a contact
    * @param bool $recursive Recursively check groups
    * @return array
    */
    public function contact_groups($distinguishedname,$recursive=NULL){
        if ($distinguishedname==NULL){ return (false); }
        if ($recursive==NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it
        if (!$this->_bind){ return (false); }

        // Search the directory for their information
        $info=@$this->contact_info($distinguishedname,array("memberof","primarygroupid"));
        $groups=$this->nice_names($info[0]["memberof"]); //presuming the entry returned is our contact

        if ($recursive){
            foreach ($groups as $id => $group_name){
                $extra_groups=$this->recursive_groups($group_name);
                $groups=array_merge($groups,$extra_groups);
            }
        }

        return ($groups);
    }

    /**
    * Get contact information
    *
    * @param string $distinguisedname The full DN of a contact
    * @param array $fields Attributes to be returned
    * @return array
    */
    public function contact_info($distinguishedname,$fields=NULL){
        if ($distinguishedname==NULL){ return (false); }
        if (!$this->_bind){ return (false); }

        $filter="distinguishedName=".$distinguishedname;
        if ($fields==NULL){ $fields=array("distinguishedname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); }
        $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        $entries = ldap_get_entries($this->_conn, $sr);

        if ($entries[0]['count'] >= 1) {
            // AD does not return the primary group in the ldap query, we may need to fudge it
            if ($this->_real_primarygroup && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["primarygroupid"][0])){
                //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);
                $entries[0]["memberof"][]=$this->get_primary_group($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]);
            } else {
                $entries[0]["memberof"][]="CN=Domain Users,CN=Users,".$this->_base_dn;
            }
        }

        $entries[0]["memberof"]["count"]++;
        return ($entries);
    }

    /**
    * Determine if a contact is a member of a group
    *
    * @param string $distinguisedname The full DN of a contact
    * @param string $group The group name to query
    * @param bool $recursive Recursively check groups
    * @return bool
    */
    public function contact_ingroup($distinguisedname,$group,$recursive=NULL){
        if ($distinguisedname==NULL){ return (false); }
        if ($group==NULL){ return (false); }
        if (!$this->_bind){ return (false); }
        if ($recursive==NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it

        // Get a list of the groups
        $groups=$this->contact_groups($distinguisedname,array("memberof"),$recursive);

        // Return true if the specified group is in the group list
        if (in_array($group,$groups)){ return (true); }

        return (false);
    }

    /**
    * Modify a contact
    *
    * @param string $distinguishedname The contact to query
    * @param array $attributes The attributes to modify.  Note if you set the enabled attribute you must not specify any other attributes
    * @return bool
    */
    public function contact_modify($distinguishedname,$attributes){
        if ($distinguishedname==NULL){ return ("Missing compulsory field [distinguishedname]"); }

        // Translate the update to the LDAP schema
        $mod=$this->adldap_schema($attributes);

        // Check to see if this is an enabled status update
        if (!$mod){ return (false); }

        // Do the update
        $result=ldap_modify($this->_conn,$distinguishedname,$mod);
        if ($result==false){ return (false); }

        return (true);
    }

    /**
    * Delete a contact
    *
    * @param string $distinguishedname The contact dn to delete (please be careful here!)
    * @return array
    */
    public function contact_delete($distinguishedname) {
        $result = $this->dn_delete($distinguishedname);
        if ($result!=true){ return (false); }
        return (true);
    }

    /**
    * Return a list of all contacts
    *
    * @param bool $include_desc Include a description of a contact
    * @param string $search The search parameters
    * @param bool $sorted Whether to sort the results
    * @return array
    */
    public function all_contacts($include_desc = false, $search = "*", $sorted = true){
        if (!$this->_bind){ return (false); }

        // Perform the search and grab all their details
        $filter = "(&(objectClass=contact)(cn=".$search."))";
        $fields=array("displayname","distinguishedname");
        $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        $entries = ldap_get_entries($this->_conn, $sr);

        $users_array = array();
        for ($i=0; $i<$entries["count"]; $i++){
            if ($include_desc && strlen($entries[$i]["displayname"][0])>0){
                $users_array[ $entries[$i]["distinguishedname"][0] ] = $entries[$i]["displayname"][0];
            } elseif ($include_desc){
                $users_array[ $entries[$i]["distinguishedname"][0] ] = $entries[$i]["distinguishedname"][0];
            } else {
                array_push($users_array, $entries[$i]["distinguishedname"][0]);
            }
        }
        if ($sorted){ asort($users_array); }
        return ($users_array);
    }

    //*****************************************************************************************************************
    // COMPUTER FUNCTIONS

    /**
    * Get information about a specific computer
    *
    * @param string $computer_name The name of the computer
    * @param array $fields Attributes to return
    * @return array
    */
    public function computer_info($computer_name,$fields=NULL){
        if ($computer_name==NULL){ return (false); }
        if (!$this->_bind){ return (false); }

        $filter="(&(objectClass=computer)(cn=".$computer_name."))";
        if ($fields==NULL){ $fields=array("memberof","cn","displayname","dnshostname","distinguishedname","objectcategory","operatingsystem","operatingsystemservicepack","operatingsystemversion"); }
        $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        $entries = ldap_get_entries($this->_conn, $sr);

        return ($entries);
    }

    //************************************************************************************************************
    // EXCHANGE FUNCTIONS

    /**
    * Create an Exchange account
    *
    * @param string $username The username of the user to add the Exchange account to
    * @param array $storagegroup The mailbox, Exchange Storage Group, for the user account, this must be a full CN
    *                            If the storage group has a different base_dn to the adLDAP configuration, set it using $base_dn
    * @param string $emailaddress The primary email address to add to this user
    * @param string $mailnickname The mail nick name.  If mail nickname is blank, the username will be used
    * @param bool $usedefaults Indicates whether the store should use the default quota, rather than the per-mailbox quota.
    * @param string $base_dn Specify an alternative base_dn for the Exchange storage grop
    * @return bool
    */
    public function exchange_create_mailbox($username, $storagegroup, $emailaddress, $mailnickname=NULL, $usedefaults=TRUE, $base_dn=NULL){
        if ($username==NULL){ return ("Missing compulsory field [username]"); }
        if ($storagegroup==NULL){ return ("Missing compulsory array [storagegroup]"); }
        if (!is_array($storagegroup)){ return ("[storagegroup] must be an array"); }
        if ($emailaddress==NULL){ return ("Missing compulsory field [emailaddress]"); }

        if ($base_dn==NULL) {
            $base_dn = $this->_base_dn;
        }

        $container="CN=".implode(",CN=",$storagegroup);

        if ($mailnickname==NULL) { $mailnickname=$username; }
        $mdbUseDefaults = $this->bool2str($usedefaults);

        $attributes = array(
            'exchange_homemdb'=>$container.",".$base_dn,
            'exchange_proxyaddress'=>'SMTP:' . $emailaddress,
            'exchange_mailnickname'=>$mailnickname,
            'exchange_usedefaults'=>$mdbUseDefaults
        );
        $result = $this->user_modify($username,$attributes);
        if ($result==false){ return (false); }
        return (true);
    }

    /**
    * Add an address to Exchange
    *
    * @param string $username The username of the user to add the Exchange account to
    * @param string $emailaddress The email address to add to this user
    * @param bool $default Make this email address the default address, this is a bit more intensive as we have to demote any existing default addresses
    * @return bool
    */
    public function exchange_add_address($username, $emailaddress, $default=FALSE) {
        if ($username==NULL){ return ("Missing compulsory field [username]"); }
        if ($emailaddress==NULL) { return ("Missing compulsory fields [emailaddress]"); }

        $proxyvalue = 'smtp:';
        if ($default === true) {
            $proxyvalue = 'SMTP:';
        }

        // Find the dn of the user
        $user=$this->user_info($username,array("cn","proxyaddresses"));
        if ($user[0]["dn"]==NULL){ return (false); }
        $user_dn=$user[0]["dn"];

        // We need to scan existing proxy addresses and demote the default one
        if (is_array($user[0]["proxyaddresses"]) && $default===true) {
            $modaddresses = array();
            for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
                if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
                    $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
                }
                if ($user[0]['proxyaddresses'][$i] != '') {
                    $modaddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
                }
            }
            $modaddresses['proxyAddresses'][(sizeof($user[0]['proxyaddresses'])-1)] = 'SMTP:' . $emailaddress;

            $result=@ldap_mod_replace($this->_conn,$user_dn,$modaddresses);
            if ($result==false){ return (false); }

            return (true);
        }
        else {
            // We do not have to demote an email address from the default so we can just add the new proxy address
            $attributes['exchange_proxyaddress'] = $proxyvalue . $emailaddress;

            // Translate the update to the LDAP schema
            $add=$this->adldap_schema($attributes);

            if (!$add){ return (false); }

            // Do the update
            // Take out the @ to see any errors, usually this error might occur because the address already
            // exists in the list of proxyAddresses
            $result=@ldap_mod_add($this->_conn,$user_dn,$add);
            if ($result==false){ return (false); }

            return (true);
        }
    }

    /**
    * Remove an address to Exchange
    * If you remove a default address the account will no longer have a default,
    * we recommend changing the default address first
    *
    * @param string $username The username of the user to add the Exchange account to
    * @param string $emailaddress The email address to add to this user
    * @return bool
    */
    public function exchange_del_address($username, $emailaddress) {
        if ($username==NULL){ return ("Missing compulsory field [username]"); }
        if ($emailaddress==NULL) { return ("Missing compulsory fields [emailaddress]"); }

        // Find the dn of the user
        $user=$this->user_info($username,array("cn","proxyaddresses"));
        if ($user[0]["dn"]==NULL){ return (false); }
        $user_dn=$user[0]["dn"];

        if (is_array($user[0]["proxyaddresses"])) {
            $mod = array();
            for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
                if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false && $user[0]['proxyaddresses'][$i] == 'SMTP:' . $emailaddress) {
                    $mod['proxyAddresses'][0] = 'SMTP:' . $emailaddress;
                }
                elseif (strstr($user[0]['proxyaddresses'][$i], 'smtp:') !== false && $user[0]['proxyaddresses'][$i] == 'smtp:' . $emailaddress) {
                    $mod['proxyAddresses'][0] = 'smtp:' . $emailaddress;
                }
            }

            $result=@ldap_mod_del($this->_conn,$user_dn,$mod);
            if ($result==false){ return (false); }

            return (true);
        }
        else {
            return (false);
        }
    }
    /**
    * Change the default address
    *
    * @param string $username The username of the user to add the Exchange account to
    * @param string $emailaddress The email address to make default
    * @return bool
    */
    public function exchange_primary_address($username, $emailaddress) {
        if ($username==NULL){ return ("Missing compulsory field [username]"); }
        if ($emailaddress==NULL) { return ("Missing compulsory fields [emailaddress]"); }

        // Find the dn of the user
        $user=$this->user_info($username,array("cn","proxyaddresses"));
        if ($user[0]["dn"]==NULL){ return (false); }
        $user_dn=$user[0]["dn"];

        if (is_array($user[0]["proxyaddresses"])) {
            $modaddresses = array();
            for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
                if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
                    $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
                }
                if ($user[0]['proxyaddresses'][$i] == 'smtp:' . $emailaddress) {
                    $user[0]['proxyaddresses'][$i] = str_replace('smtp:', 'SMTP:', $user[0]['proxyaddresses'][$i]);
                }
                if ($user[0]['proxyaddresses'][$i] != '') {
                    $modaddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
                }
            }

            $result=@ldap_mod_replace($this->_conn,$user_dn,$modaddresses);
            if ($result==false){ return (false); }

            return (true);
        }

    }

    /**
    * Mail enable a contact
    * Allows email to be sent to them through Exchange
    *
    * @param string $distinguishedname The contact to mail enable
    * @param string $emailaddress The email address to allow emails to be sent through
    * @param string $mailnickname The mailnickname for the contact in Exchange.  If NULL this will be set to the display name
    * @return bool
    */
    public function exchange_contact_mailenable($distinguishedname, $emailaddress, $mailnickname=NULL){
        if ($distinguishedname==NULL){ return ("Missing compulsory field [distinguishedname]"); }
        if ($emailaddress==NULL){ return ("Missing compulsory field [emailaddress]"); }

        if ($mailnickname != NULL) {
            // Find the dn of the user
            $user=$this->contact_info($distinguishedname,array("cn","displayname"));
            if ($user[0]["displayname"]==NULL){ return (false); }
            $mailnickname = $user[0]['displayname'][0];
        }

        $attributes = array("email"=>$emailaddress,"contact_email"=>"SMTP:" . $emailaddress,"exchange_proxyaddress"=>"SMTP:" . $emailaddress,"exchange_mailnickname"=>$mailnickname);

        // Translate the update to the LDAP schema
        $mod=$this->adldap_schema($attributes);

        // Check to see if this is an enabled status update
        if (!$mod){ return (false); }

        // Do the update
        $result=ldap_modify($this->_conn,$distinguishedname,$mod);
        if ($result==false){ return (false); }

        return (true);
    }

    //************************************************************************************************************
    // UTILITY FUNCTIONS (Many of these functions are protected and can only be called from within the class)

    /**
    * Get last error from Active Directory
    *
    * This function gets the last message from Active Directory
    * This may indeed be a 'Success' message but if you get an unknown error
    * it might be worth calling this function to see what errors were raised
    *
    * return string
    */
    public function get_last_error() {
        return @ldap_error($this->_conn);
    }

    /**
    * Schema
    *
    * @param array $attributes Attributes to be queried
    * @return array
    */
    protected function adldap_schema($attributes){

        // LDAP doesn't like NULL attributes, only set them if they have values
        // If you wish to remove an attribute you should set it to a space
        // TO DO: Adapt user_modify to use ldap_mod_delete to remove a NULL attribute
        $mod=array();

        // Check every attribute to see if it contains 8bit characters and then UTF8 encode them
        array_walk($attributes, array($this, 'encode8bit'));

        if ($attributes["address_city"]){ $mod["l"][0]=$attributes["address_city"]; }
        if ($attributes["address_code"]){ $mod["postalCode"][0]=$attributes["address_code"]; }
        //if ($attributes["address_country"]){ $mod["countryCode"][0]=$attributes["address_country"]; } // use country codes?
        if ($attributes["address_country"]){ $mod["c"][0]=$attributes["address_country"]; }
        if ($attributes["address_pobox"]){ $mod["postOfficeBox"][0]=$attributes["address_pobox"]; }
        if ($attributes["address_state"]){ $mod["st"][0]=$attributes["address_state"]; }
        if ($attributes["address_street"]){ $mod["streetAddress"][0]=$attributes["address_street"]; }
        if ($attributes["company"]){ $mod["company"][0]=$attributes["company"]; }
        if ($attributes["change_password"]){ $mod["pwdLastSet"][0]=0; }
        if ($attributes["department"]){ $mod["department"][0]=$attributes["department"]; }
        if ($attributes["description"]){ $mod["description"][0]=$attributes["description"]; }
        if ($attributes["display_name"]){ $mod["displayName"][0]=$attributes["display_name"]; }
        if ($attributes["email"]){ $mod["mail"][0]=$attributes["email"]; }
        if ($attributes["expires"]){ $mod["accountExpires"][0]=$attributes["expires"]; } //unix epoch format?
        if ($attributes["firstname"]){ $mod["givenName"][0]=$attributes["firstname"]; }
        if ($attributes["home_directory"]){ $mod["homeDirectory"][0]=$attributes["home_directory"]; }
        if ($attributes["home_drive"]){ $mod["homeDrive"][0]=$attributes["home_drive"]; }
        if ($attributes["initials"]){ $mod["initials"][0]=$attributes["initials"]; }
        if ($attributes["logon_name"]){ $mod["userPrincipalName"][0]=$attributes["logon_name"]; }
        if ($attributes["manager"]){ $mod["manager"][0]=$attributes["manager"]; }  //UNTESTED ***Use DistinguishedName***
        if ($attributes["office"]){ $mod["physicalDeliveryOfficeName"][0]=$attributes["office"]; }
        if ($attributes["password"]){ $mod["unicodePwd"][0]=$this->encode_password($attributes["password"]); }
        if ($attributes["profile_path"]){ $mod["profilepath"][0]=$attributes["profile_path"]; }
        if ($attributes["script_path"]){ $mod["scriptPath"][0]=$attributes["script_path"]; }
        if ($attributes["surname"]){ $mod["sn"][0]=$attributes["surname"]; }
        if ($attributes["title"]){ $mod["title"][0]=$attributes["title"]; }
        if ($attributes["telephone"]){ $mod["telephoneNumber"][0]=$attributes["telephone"]; }
        if ($attributes["mobile"]){ $mod["mobile"][0]=$attributes["mobile"]; }
        if ($attributes["pager"]){ $mod["pager"][0]=$attributes["pager"]; }
        if ($attributes["ipphone"]){ $mod["ipphone"][0]=$attributes["ipphone"]; }
        if ($attributes["web_page"]){ $mod["wWWHomePage"][0]=$attributes["web_page"]; }
        if ($attributes["fax"]){ $mod["facsimileTelephoneNumber"][0]=$attributes["fax"]; }
        if ($attributes["enabled"]){ $mod["userAccountControl"][0]=$attributes["enabled"]; }

        // Distribution List specific schema
        if ($attributes["group_sendpermission"]){ $mod["dlMemSubmitPerms"][0]=$attributes["group_sendpermission"]; }
        if ($attributes["group_rejectpermission"]){ $mod["dlMemRejectPerms"][0]=$attributes["group_rejectpermission"]; }

        // Exchange Schema
        if ($attributes["exchange_homemdb"]){ $mod["homeMDB"][0]=$attributes["exchange_homemdb"]; }
        if ($attributes["exchange_mailnickname"]){ $mod["mailNickname"][0]=$attributes["exchange_mailnickname"]; }
        if ($attributes["exchange_proxyaddress"]){ $mod["proxyAddresses"][0]=$attributes["exchange_proxyaddress"]; }
        if ($attributes["exchange_usedefaults"]){ $mod["mDBUseDefaults"][0]=$attributes["exchange_usedefaults"]; }

        // This schema is designed for contacts
        if ($attributes["exchange_hidefromlists"]){ $mod["msExchHideFromAddressLists"][0]=$attributes["exchange_hidefromlists"]; }
        if ($attributes["contact_email"]){ $mod["targetAddress"][0]=$attributes["contact_email"]; }

        //echo ("<pre>"); print_r($mod);
        /*
        // modifying a name is a bit fiddly
        if ($attributes["firstname"] && $attributes["surname"]){
            $mod["cn"][0]=$attributes["firstname"]." ".$attributes["surname"];
            $mod["displayname"][0]=$attributes["firstname"]." ".$attributes["surname"];
            $mod["name"][0]=$attributes["firstname"]." ".$attributes["surname"];
        }
        */

        if (count($mod)==0){ return (false); }
        return ($mod);
    }

    /**
    * Coping with AD not returning the primary group
    * http://support.microsoft.com/?kbid=321360
    *
    * For some reason it's not possible to search on primarygrouptoken=XXX
    * If someone can show otherwise, I'd like to know about it :)
    * this way is resource intensive and generally a pain in the @#%^
    *
    * @deprecated deprecated since version 3.1, see get get_primary_group
    * @param string $gid Group ID
    * @return string
    */
    protected function group_cn($gid){
        if ($gid==NULL){ return (false); }
        $r=false;

        $filter="(&(objectCategory=group)(samaccounttype=". ADLDAP_SECURITY_GLOBAL_GROUP ."))";
        $fields=array("primarygrouptoken","samaccountname","distinguishedname");
        $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        $entries = ldap_get_entries($this->_conn, $sr);

        for ($i=0; $i<$entries["count"]; $i++){
            if ($entries[$i]["primarygrouptoken"][0]==$gid){
                $r=$entries[$i]["distinguishedname"][0];
                $i=$entries["count"];
            }
        }

        return ($r);
    }

    /**
    * Coping with AD not returning the primary group
    * http://support.microsoft.com/?kbid=321360
    *
    * This is a re-write based on code submitted by Bruce which prevents the
    * need to search each security group to find the true primary group
    *
    * @param string $gid Group ID
    * @param string $usersid User's Object SID
    * @return string
    */
    protected function get_primary_group($gid, $usersid){
        if ($gid==NULL || $usersid==NULL){ return (false); }
        $r=false;

        $gsid = substr_replace($usersid,pack('V',$gid),strlen($usersid)-4,4);
        $filter='(objectsid='.$this->getTextSID($gsid).')';
        $fields=array("samaccountname","distinguishedname");
        $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        $entries = ldap_get_entries($this->_conn, $sr);

        return $entries[0]['distinguishedname'][0];
     }

    /**
    * Convert a binary SID to a text SID
    *
    * @param string $binsid A Binary SID
    * @return string
    */
     protected function getTextSID($binsid) {
        $hex_sid = bin2hex($binsid);
        $rev = hexdec(substr($hex_sid, 0, 2));
        $subcount = hexdec(substr($hex_sid, 2, 2));
        $auth = hexdec(substr($hex_sid, 4, 12));
        $result = "$rev-$auth";

        for ($x=0;$x < $subcount; $x++) {
            $subauth[$x] =
                hexdec($this->little_endian(substr($hex_sid, 16 + ($x * 8), 8)));
                $result .= "-" . $subauth[$x];
        }

        // Cheat by tacking on the S-
        return 'S-' . $result;
     }

    /**
    * Converts a little-endian hex number to one that hexdec() can convert
    *
    * @param string $hex A hex code
    * @return string
    */
     protected function little_endian($hex) {
        $result = '';
        for ($x = strlen($hex) - 2; $x >= 0; $x = $x - 2) {
            $result .= substr($hex, $x, 2);
        }
        return $result;
     }

    /**
    * Obtain the user's distinguished name based on their userid
    *
    *
    * @param string $username The username
    * @return string
    */
    protected function user_dn($username){
        $user=$this->user_info($username,array("cn"));
        if ($user[0]["dn"]==NULL){ return (false); }
        $user_dn=$user[0]["dn"];
        return ($user_dn);
    }

    /**
    * Encode a password for transmission over LDAP
    *
    * @param string $password The password to encode
    * @return string
    */
    protected function encode_password($password){
        $password="\"".$password."\"";
        $encoded="";
        for ($i=0; $i <strlen($password); $i++){ $encoded.="{$password{$i}}\000"; }
        return ($encoded);
    }

    /**
    * Escape strings for the use in LDAP filters
    *
    * Ported from Perl's Net::LDAP::Util escape_filter_value
    *
    * @author Andreas Gohr <andi@splitbrain.org>
    * @param string $str The string to escape
    * @return string
    */
    protected function ldap_slashes($str){
        return preg_replace('/([\x00-\x1F\*\(\)\\\\])/e',
                            '"\\\\\".join("",unpack("H2","$1"))',
                            $string);
    }

    /**
    * Select a random domain controller from your domain controller array
    *
    * @return string
    */
    protected function random_controller(){
        mt_srand(doubleval(microtime()) * 100000000); // For older PHP versions
        return ($this->_domain_controllers[array_rand($this->_domain_controllers)]);
    }

    /**
    * Account control options
    *
    * @param array $options The options to convert to int
    * @return int
    */
    protected function account_control($options){
        $val=0;

        if (is_array($options)){
            if (in_array("SCRIPT",$options)){ $val=$val+1; }
            if (in_array("ACCOUNTDISABLE",$options)){ $val=$val+2; }
            if (in_array("HOMEDIR_REQUIRED",$options)){ $val=$val+8; }
            if (in_array("LOCKOUT",$options)){ $val=$val+16; }
            if (in_array("PASSWD_NOTREQD",$options)){ $val=$val+32; }
            //PASSWD_CANT_CHANGE Note You cannot assign this permission by directly modifying the UserAccountControl attribute.
            //For information about how to set the permission programmatically, see the "Property flag descriptions" section.
            if (in_array("ENCRYPTED_TEXT_PWD_ALLOWED",$options)){ $val=$val+128; }
            if (in_array("TEMP_DUPLICATE_ACCOUNT",$options)){ $val=$val+256; }
            if (in_array("NORMAL_ACCOUNT",$options)){ $val=$val+512; }
            if (in_array("INTERDOMAIN_TRUST_ACCOUNT",$options)){ $val=$val+2048; }
            if (in_array("WORKSTATION_TRUST_ACCOUNT",$options)){ $val=$val+4096; }
            if (in_array("SERVER_TRUST_ACCOUNT",$options)){ $val=$val+8192; }
            if (in_array("DONT_EXPIRE_PASSWORD",$options)){ $val=$val+65536; }
            if (in_array("MNS_LOGON_ACCOUNT",$options)){ $val=$val+131072; }
            if (in_array("SMARTCARD_REQUIRED",$options)){ $val=$val+262144; }
            if (in_array("TRUSTED_FOR_DELEGATION",$options)){ $val=$val+524288; }
            if (in_array("NOT_DELEGATED",$options)){ $val=$val+1048576; }
            if (in_array("USE_DES_KEY_ONLY",$options)){ $val=$val+2097152; }
            if (in_array("DONT_REQ_PREAUTH",$options)){ $val=$val+4194304; }
            if (in_array("PASSWORD_EXPIRED",$options)){ $val=$val+8388608; }
            if (in_array("TRUSTED_TO_AUTH_FOR_DELEGATION",$options)){ $val=$val+16777216; }
        }
        return ($val);
    }

    /**
    * Take an LDAP query and return the nice names, without all the LDAP prefixes (eg. CN, DN)
    *
    * @param array $groups
    * @return array
    */
    protected function nice_names($groups){

        $group_array=array();
        for ($i=0; $i<$groups["count"]; $i++){ // For each group
            $line=$groups[$i];

            if (strlen($line)>0){
                // More presumptions, they're all prefixed with CN=
                // so we ditch the first three characters and the group
                // name goes up to the first comma
                $bits=explode(",",$line);
                $group_array[]=substr($bits[0],3,(strlen($bits[0])-3));
            }
        }
        return ($group_array);
    }

    /**
    * Delete a distinguished name from Active Directory
    * You should never need to call this yourself, just use the wrapper functions user_delete and contact_delete
    *
    * @param string $dn The distinguished name to delete
    * @return bool
    */
    protected function dn_delete($dn){
        $result=ldap_delete($this->_conn, $dn);
        if ($result!=true){ return (false); }
        return (true);
    }

    /**
    * Convert a boolean value to a string
    * You should never need to call this yourself
    *
    * @param bool $bool Boolean value
    * @return string
    */
    protected function bool2str($bool) {
        return ($bool) ? 'TRUE' : 'FALSE';
    }

    /**
    * Convert 8bit characters e.g. accented characters to UTF8 encoded characters
    */
    protected function encode8bit(&$item, $key) {
        $encode = false;
        if (is_string($item)) {
            for ($i=0; $i<strlen($item); $i++) {
                if (ord($item[$i]) >> 7) {
                    $encode = true;
                }
            }
        }
        if ($encode === true && $key != 'password') {
            $item = utf8_encode($item);
        }
    }
}

/**
* adLDAP Exception Handler
*
* Exceptions of this type are thrown on bind failure or when SSL is required but not configured
* Example:
* try {
*   $adldap = new adLDAP();
* }
* catch (adLDAPException $e) {
*   echo $e;
*   exit();
* }
*/
class adLDAPException extends Exception {}

?>