summaryrefslogtreecommitdiff
path: root/lib/Net/LDAP3.php
blob: 4d2082afbe52c826b9ea097822b35bace1912197 (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
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
<?php
/*
 +-----------------------------------------------------------------------+
 | Net/LDAP3.php                                                         |
 |                                                                       |
 | Based on code created by the Roundcube Webmail team.                  |
 |                                                                       |
 | Copyright (C) 2006-2014, The Roundcube Dev Team                       |
 | Copyright (C) 2012-2014, Kolab Systems AG                             |
 |                                                                       |
 | Licensed under the GNU General Public License version 3 or            |
 | any later version with exceptions for plugins.                        |
 | See the README file for a full license statement.                     |
 |                                                                       |
 | PURPOSE:                                                              |
 |   Provide advanced functionality for accessing LDAP directories       |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Authors: Thomas Bruederli <roundcube@gmail.com>                       |
 |          Aleksander Machniak <machniak@kolabsys.com>                  |
 |          Jeroen van Meeuwen <vanmeeuwen@kolabsys.com>                 |
 +-----------------------------------------------------------------------+
*/

require_once __DIR__ . '/LDAP3/Result.php';

/**
 * Model class to access a LDAP directories
 *
 * @package Net_LDAP3
 */
class Net_LDAP3
{
    public $conn;
    public $vlv_active = false;

    private $attribute_level_rights_map = array(
        "r" => "read",
        "s" => "search",
        "w" => "write",
        "o" => "delete",
        "c" => "compare",
        "W" => "write",
        "O" => "delete"
    );

    private $entry_level_rights_map = array(
        "a" => "add",
        "d" => "delete",
        "n" => "modrdn",
        "v" => "read"
    );

    /*
     * Manipulate configuration through the config_set and config_get methods.
     * Available options:
     *       'debug'           => false,
     *       'hosts'           => array(),
     *       'port'            => 389,
     *       'use_tls'         => false,
     *       'ldap_version'    => 3,        // using LDAPv3
     *       'auth_method'     => '',       // SASL authentication method (for proxy auth), e.g. DIGEST-MD5
     *       'numsub_filter'   => '(objectClass=organizationalUnit)', // with VLV, we also use numSubOrdinates to query the total number of records. Set this filter to get all numSubOrdinates attributes for counting
     *       'referrals'       => false,    // Sets the LDAP_OPT_REFERRALS option. Mostly used in multi-domain Active Directory setups
     *       'network_timeout' => 10,       // The timeout (in seconds) for connect + bind arrempts. This is only supported in PHP >= 5.3.0 with OpenLDAP 2.x
     *       'sizelimit'       => 0,        // Enables you to limit the count of entries fetched. Setting this to 0 means no limit.
     *       'timelimit'       => 0,        // Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit.
     *       'vlv'             => false,    // force VLV off
     *       'config_root_dn'  => 'cn=config',  // Root DN to read config (e.g. vlv indexes) from
     *       'service_bind_dn' => 'uid=kolab-service,ou=Special Users,dc=example,dc=org',
     *       'service_bind_pw' => 'Welcome2KolabSystems',
     *       'root_dn'         => 'dc=example,dc=org',
     */
    protected $config = array(
        'sizelimit' => 0,
        'timelimit' => 0,
    );

    protected $debug_level = false;
    protected $list_page   = 1;
    protected $page_size   = 10;
    protected $cache;

    // Use public method config_set('log_hook', $callback) to have $callback be
    // call_user_func'ed instead of the local log functions.
    protected $_log_hook;

    // Use public method config_set('config_get_hook', $callback) to have
    // $callback be call_user_func'ed instead of the local config_get function.
    protected $_config_get_hook;

    // Use public method config_set('config_set_hook', $callback) to have
    // $callback be call_user_func'ed instead of the local config_set function.
    protected $_config_set_hook;

    // Not Yet Implemented
    // Intended to allow hooking in for the purpose of caching.
    protected $_result_hook;

    // Runtime. These are not the variables you're looking for.
    protected $_current_bind_dn;
    protected $_current_bind_pw;
    protected $_current_host;
    protected $_supported_control = array();
    protected $_vlv_indexes_and_searches;

    /**
     * Constructor
     *
     * @param array $config Configuration parameters that have not already
     *                      been initialized. For configuration parameters
     *                      that have in fact been set, use the config_set()
     *                      method after initialization.
     */
    public function __construct($config = array())
    {
        if (!empty($config) && is_array($config)) {
            foreach ($config as $key => $value) {
                if (empty($this->config[$key])) {
                    $setter = 'config_set_' . $key;
                    if (method_exists($this, $setter)) {
                        $this->$setter($value);
                    }
                    else if (isset($this->$key)) {
                        $this->$key = $value;
                    }
                    else {
                        $this->config[$key] = $value;
                    }
                }
            }
        }
    }

    /**
     *  Add multiple entries to the directory information tree in one go.
     */
    public function add_entries($entries, $attributes = array())
    {
        // If $entries is an associative array, it's keys are DNs and its
        // values are the attributes for that DN.
        //
        // If $entries is a non-associative array, the attributes are expected
        // to be positional in $attributes.

        $result_set = array();

        if (array_keys($entries) == range(0, count($entries) - 1)) {
            // $entries is sequential
            if (count($entries) !== count($attributes)) {
                $this->_error("Wrong entry/attribute count in " . __FUNCTION__);
                return false;
            }

            for ($i = 0; $i < count($entries); $i++) {
                $result_set[$i] = $this->add_entry($entries[$i], $attributes[$i]);
            }
        }
        else {
            // $entries is associative
            foreach ($entries as $entry_dn => $entry_attributes) {
                if (array_keys($attributes) !== range(0, count($attributes)-1)) {
                    // $attributes is associative as well, let's merge these
                    //
                    // $entry_attributes takes precedence, so is in the second
                    // position in array_merge()
                    $entry_attributes = array_merge($attributes, $entry_attributes);
                }

                $result_set[$entry_dn] = $this->add_entry($entry_dn, $entry_attributes);
            }
        }

        return $result_set;
    }

    /**
     * Add an entry to the directory information tree.
     */
    public function add_entry($entry_dn, $attributes)
    {
        // TODO:
        // - Get entry rdn attribute value from entry_dn and see if it exists in
        //   attributes -> issue warning if so (but not block the operation).
        $this->_debug("Entry DN", $entry_dn);
        $this->_debug("Attributes", $attributes);

        foreach ($attributes as $attr_name => $attr_value) {
            if (empty($attr_value)) {
                unset($attributes[$attr_name]);
            }
        }

        $this->_debug("C: Add $entry_dn: " . json_encode($attributes));

        if (($add_result = ldap_add($this->conn, $entry_dn, $attributes)) == false) {
            $this->_debug("S: " . ldap_error($this->conn));
            $this->_debug("S: Adding entry $entry_dn failed. " . ldap_error($this->conn));

            return false;
        }

        $this->_debug("LDAP: S: OK");

        return true;
    }

    /**
     * Add replication agreements and initialize the consumer(s) for
     * $domain_root_dn.
     *
     * Searches the configured replicas for any of the current domain/config
     * databases, and uses this information to configure the additional
     * replication for the (new) domain database (at $domain_root_dn).
     *
     * Very specific to Netscape-based directory servers, and currently also
     * very specific to multi-master replication.
     */
    public function add_replication_agreements($domain_root_dn)
    {
        $replica_hosts = $this->list_replicas();

        if (empty($replica_hosts)) {
            return;
        }

        $result = $this->search($this->config_get('config_root_dn'), "(&(objectclass=nsDS5Replica)(nsDS5ReplicaType=3))", "sub");

        if (!$result) {
            $this->_debug("No replication configuration found.");
            return;
        }

        // Preserve the number of replicated databases we have, because the replication ID
        // can be calculated from the number of databases replicated, and the number of
        // servers.
        $num_replica_dbs = $result->count();
        $replicas        = $result->entries(true);
        $max_replica_agreements = 0;

        foreach ($replicas as $replica_dn => $replica_attrs) {
            $result = $this->search($replica_dn, "(objectclass=nsDS5ReplicationAgreement)", "sub");
            if ($result) {
                if ($max_replica_agreements < $result->count()) {
                    $max_replica_agreements    = $result->count();
                    $max_replica_agreements_dn = $replica_dn;
                }
            }
        }

        $max_repl_id = $num_replica_dbs * count($replica_hosts);

        $this->_debug("The current maximum replication ID is $max_repl_id");
        $this->_debug("The current maximum number of replication agreements for any database is $max_replica_agreements (for $max_replica_agreements_dn)");
        $this->_debug("With " . count($replica_hosts) . " replicas, the next is " . ($max_repl_id + 1) . " and the last one is " . ($max_repl_id + count($replica_hosts)));

        // Then add the replication agreements
        foreach ($replica_hosts as $num => $replica_host) {
            $ldap = new Net_LDAP3($this->config);
            $ldap->config_set('hosts', array($replica_host));
            $ldap->connect();
            $ldap->bind($this->_current_bind_dn, $this->_current_bind_pw);

            $replica_attrs = array(
                'cn' => 'replica',
                'objectclass' => array(
                    'top',
                    'nsds5replica',
                    'extensibleobject',
                ),
                'nsDS5ReplicaBindDN'     => $ldap->get_entry_attribute($replica_dn, "nsDS5ReplicaBindDN"),
                'nsDS5ReplicaId'         => ($max_repl_id + $num + 1),
                'nsDS5ReplicaRoot'       => $domain_root_dn,
                'nsDS5ReplicaType'       => $ldap->get_entry_attribute($replica_dn, "nsDS5ReplicaType"),
                'nsds5ReplicaPurgeDelay' => $ldap->get_entry_attribute($replica_dn, "nsds5ReplicaPurgeDelay"),
                'nsDS5Flags'             => $ldap->get_entry_attribute($replica_dn, "nsDS5Flags")
            );

            $new_replica_dn = 'cn=replica,cn="' . $domain_root_dn . '",cn=mapping tree,cn=config';

            $this->_debug("Adding $new_replica_dn to $replica_host with attributes: " . var_export($replica_attrs, true));

            $result = $ldap->add_entry($new_replica_dn, $replica_attrs);

            if (!$result) {
                $this->_error("Could not add replication configuration to database for $domain_root_dn on $replica_host");
                continue;
            }

            $result = $ldap->search($replica_dn, "(objectclass=nsDS5ReplicationAgreement)", "sub");

            if (!$result) {
                $this->_error("Host $replica_host does not have any replication agreements");
                continue;
            }

            $entries = $result->entries(true);
            $replica_agreement_tpl_dn = key($entries);

            $this->_debug("Using " . var_export($replica_agreement_tpl_dn, true) . " as the template for new replication agreements");

            foreach ($replica_hosts as $replicate_to_host) {
                // Skip the current server
                if ($replicate_to_host == $replica_host) {
                    continue;
                }

                $this->_debug("Adding a replication agreement for $domain_root_dn to $replicate_to_host on " . $replica_host);

                $attrs = array(
                    'objectclass',
                    'nsDS5ReplicaBindDN',
                    'nsDS5ReplicaCredentials',
                    'nsDS5ReplicaTransportInfo',
                    'nsDS5ReplicaBindMethod',
                    'nsDS5ReplicaHost',
                    'nsDS5ReplicaPort'
                );

                $replica_agreement_attrs = $ldap->get_entry_attributes($replica_agreement_tpl_dn, $attrs);
                $replica_agreement_attrs['cn'] = array_shift(explode('.', $replicate_to_host)) . str_replace(array('dc=',','), array('_',''), $domain_root_dn);
                $replica_agreement_attrs['nsDS5ReplicaRoot'] = $domain_root_dn;
                $replica_agreement_dn = "cn=" . $replica_agreement_attrs['cn'] . "," . $new_replica_dn;

                $this->_debug("Adding $replica_agreement_dn to $replica_host with attributes: " . var_export($replica_agreement_attrs, true));

                $result = $ldap->add_entry($replica_agreement_dn, $replica_agreement_attrs);

                if (!$result) {
                    $this->_error("Failed adding $replica_agreement_dn");
                }
            }
        }

        $server_id = implode('', array_diff($replica_hosts, $this->_server_id_not));

        $this->_debug("About to trigger consumer initialization for replicas on current 'parent': $server_id");

        $result = $this->search($this->config_get('config_root_dn'), "(&(objectclass=nsDS5ReplicationAgreement)(nsds5replicaroot=$domain_root_dn))", "sub");

        if ($result) {
            foreach ($result->entries(true) as $agreement_dn => $agreement_attrs) {
                $this->modify_entry_attributes(
                    $agreement_dn,
                    array(
                        'replace' => array(
                            'nsds5BeginReplicaRefresh' => 'start',
                        ),
                    )
                );
            }
        }
    }

    public function attribute_details($attributes = array())
    {
        $schema = $this->init_schema();

        if (!$schema) {
            return array();
        }

        $attribs = $schema->getAll('attributes');

        $attributes_details = array();

        foreach ($attributes as $attribute) {
            if (array_key_exists($attribute, $attribs)) {
                $attrib_details = $attribs[$attribute];

                if (!empty($attrib_details['sup'])) {
                    foreach ($attrib_details['sup'] as $super_attrib) {
                        $_attrib_details = $attribs[$super_attrib];
                        if (is_array($_attrib_details)) {
                            $attrib_details = array_merge($_attrib_details, $attrib_details);
                        }
                    }
                }
            }
            else if (array_key_exists(strtolower($attribute), $attribs)) {
                $attrib_details = $attribs[strtolower($attribute)];

                if (!empty($attrib_details['sup'])) {
                    foreach ($attrib_details['sup'] as $super_attrib) {
                        $_attrib_details = $attribs[$super_attrib];
                        if (is_array($_attrib_details)) {
                            $attrib_details = array_merge($_attrib_details, $attrib_details);
                        }
                    }
                }
            }
            else {
                $this->_warning("LDAP: No schema details exist for attribute $attribute (which is strange)");
            }

            // The relevant parts only, please
            $attributes_details[$attribute] = array(
                'type'        => !empty($attrib_details['single-value']) ? 'text' : 'list',
                'description' => $attrib_details['desc'],
                'syntax'      => $attrib_details['syntax'],
                'max-length'  => $attrib_details['max-length'] ?: false,
            );
        }

        return $attributes_details;
    }

    public function attributes_allowed($objectclasses = array())
    {
        $this->_debug("Listing allowed_attributes for objectclasses", $objectclasses);

        if (!is_array($objectclasses) || empty($objectclasses)) {
            return false;
        }

        $schema = $this->init_schema();
        if (!$schema) {
            return false;
        }

        $may          = array();
        $must         = array();
        $superclasses = array();

        foreach ($objectclasses as $objectclass) {
            $superclass = $schema->superclass($objectclass);
            if (!empty($superclass)) {
                $superclasses = array_merge($superclass, $superclasses);
            }

            $_may  = $schema->may($objectclass);
            $_must = $schema->must($objectclass);

            if (is_array($_may)) {
                $may = array_merge($may, $_may);
            }
            if (is_array($_must)) {
                $must = array_merge($must, $_must);
            }
        }

        $may          = array_unique($may);
        $must         = array_unique($must);
        $superclasses = array_unique($superclasses);

        return array('may' => $may, 'must' => $must, 'super' => $superclasses);
    }

    public function classes_allowed()
    {
        $schema = $this->init_schema();
        if (!$schema) {
            return false;
        }

        $list    = $schema->getAll('objectclasses');
        $classes = array();

        foreach ($list as $class) {
            $classes[] = $class['name'];
        }

        return $classes;
    }

    /**
     * Bind connection with DN and password
     *
     * @param string $dn   Bind DN
     * @param string $pass Bind password
     *
     * @return boolean True on success, False on error
     */
    public function bind($bind_dn, $bind_pw)
    {
        if (!$this->conn) {
            return false;
        }

        if ($bind_dn == $this->_current_bind_dn) {
            return true;
        }

        $this->_debug("C: Bind [dn: $bind_dn]");

        if (@ldap_bind($this->conn, $bind_dn, $bind_pw)) {
            $this->_debug("S: OK");
            $this->_current_bind_dn = $bind_dn;
            $this->_current_bind_pw = $bind_pw;

            return true;
        }

        $this->_debug("S: ".ldap_error($this->conn));
        $this->_error("Bind failed for dn=$bind_dn: ".ldap_error($this->conn));

        return false;
    }

    /**
     * Close connection to LDAP server
     */
    public function close()
    {
        if ($this->conn) {
            $this->_debug("C: Close");
            ldap_unbind($this->conn);

            $this->_current_bind_dn = null;
            $this->_current_bind_pw = null;
            $this->conn             = null;
        }
    }

    /**
     * Get the value of a configuration item.
     *
     * @param string $key     Configuration key
     * @param mixed  $default Default value to return
     */
    public function config_get($key, $default = null)
    {
        if (!empty($this->_config_get_hook)) {
            return call_user_func_array($this->_config_get_hook, array($key, $value));
        }
        else if (method_exists($this, "config_get_{$key}")) {
            return call_user_func(array($this, "config_get_$key"), $value);
        }
        else if (!isset($this->config[$key])) {
            return $default;
        }
        else {
            return $this->config[$key];
        }
    }

    /**
     * Set a configuration item to value.
     *
     * @param string $key   Configuration key
     * @param mixed  $value Configuration value
     */
    public function config_set($key, $value = null)
    {
        if (is_array($key)) {
            foreach ($key as $k => $v) {
                $this->config_set($k, $v);
            }
            return;
        }

        if (!empty($this->_config_set_hook)) {
            call_user_func($this->_config_set_hook, array($key, $value));
        }
        else if (method_exists($this, "config_set_{$key}")) {
            call_user_func_array(array($this, "config_set_$key"), array($value));
        }
        else if (isset($this->$key)) {
            $this->$key = $value;
        }
        else {
            // 'host' option is deprecated
            if ($key == 'host') {
                $this->config['hosts'] = (array) $value;
            }
            else {
                $this->config[$key] = $value;
            }
        }
    }

    /**
     * Establish a connection to the LDAP server
     */
    public function connect($host = null)
    {
        if (!function_exists('ldap_connect')) {
            $this->_error("No ldap support in this PHP installation");
            return false;
        }

        if (is_resource($this->conn)) {
            $this->_debug("Connection already exists");
            return true;
        }

        $hosts = !empty($host) ? $host : $this->config_get('hosts', array());
        $port  = $this->config_get('port', 389);

        foreach ((array) $hosts as $host) {
            $this->_debug("C: Connect [$host:$port]");

            if ($lc = @ldap_connect($host, $port)) {
                if ($this->config_get('use_tls', false) === true) {
                    if (!ldap_start_tls($lc)) {
                        $this->_debug("S: Could not start TLS. " . ldap_error($lc));
                        continue;
                    }
                }

                $this->_debug("S: OK");

                $ldap_version = $this->config_get('ldap_version', 3);
                $timeout      = $this->config_get('network_timeout');
                $referrals    = $this->config_get('referrals');

                ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $ldap_version);

                if ($timeout) {
                    ldap_set_option($lc, LDAP_OPT_NETWORK_TIMEOUT, $timeout);
                }

                if ($referrals !== null) {
                    ldap_set_option($lc, LDAP_OPT_REFERRALS, (bool) $referrals);
                }

                $this->_current_host = $host;
                $this->conn          = $lc;

                break;
            }

            $this->_debug("S: NOT OK");
        }

        if (!is_resource($this->conn)) {
            $this->_error("Could not connect to LDAP");
            return false;
        }

        return true;
    }

    /**
     *   Shortcut to ldap_delete()
     */
    public function delete_entry($entry_dn)
    {
        $this->_debug("LDAP: C: Delete $entry_dn");

        if (ldap_delete($this->conn, $entry_dn) === false) {
            $this->_debug("LDAP: S: " . ldap_error($this->conn));
            return false;
        }

        $this->_debug("LDAP: S: OK");

        return true;
    }

    /**
     * Deletes specified entry and all entries in the tree
     */
    public function delete_entry_recursive($entry_dn)
    {
        // searching for sub entries, but not scope sub, just one level
        $result = $this->search($entry_dn, '(objectclass=*)', 'one');

        if ($result) {
            $entries = $result->entries(true);

            foreach (array_keys($entries) as $sub_dn) {
                if (!$this->delete_entry_recursive($sub_dn)) {
                    return false;
                }
            }
        }

        if (!$this->delete_entry($entry_dn)) {
            return false;
        }

        return true;
    }

    public function effective_rights($subject)
    {
        $effective_rights_control_oid = "1.3.6.1.4.1.42.2.27.9.5.2";

        $supported_controls = $this->supported_controls();

        if (!in_array($effective_rights_control_oid, $supported_controls)) {
            $this->_debug("LDAP: No getEffectiveRights control in supportedControls");
            return false;
        }

        $attributes = array(
            'attributeLevelRights' => array(),
            'entryLevelRights' => array(),
        );

        $output   = array();
        $entry_dn = $this->entry_dn($subject);

        if (!$entry_dn) {
            $entry_dn = $this->config_get($subject . "_base_dn");
        }
        if (!$entry_dn) {
            $entry_dn = $this->config_get("base_dn");
        }
        if (!$entry_dn) {
            $entry_dn = $this->config_get("root_dn");
        }

        $this->_debug("effective_rights for subject $subject resolves to entry dn $entry_dn");

        $moz_ldapsearch = "/usr/lib64/mozldap/ldapsearch";
        if (!is_file($moz_ldapsearch)) {
            $moz_ldapsearch = "/usr/lib/mozldap/ldapsearch";
        }
        if (!is_file($moz_ldapsearch)) {
            $moz_ldapsearch = null;
        }

        if (empty($moz_ldapsearch)) {
            $this->_error("Mozilla LDAP C SDK binary ldapsearch not found, cannot get effective rights on subject $subject");
            return null;
        }

        $command = array(
            $moz_ldapsearch,
            '-x',
            '-h',
            $this->_ldap_server,
            '-p',
            $this->_ldap_port,
            '-b',
            escapeshellarg($entry_dn),
            '-D',
            escapeshellarg($this->_current_bind_dn),
            '-w',
            escapeshellarg($this->_current_bind_pw),
            '-J',
            escapeshellarg(implode(':', array(
                $effective_rights_control_oid,          // OID
                'true',                                 // Criticality
                'dn:' . $this->_current_bind_dn // User DN
            ))),
            '-s',
            'base',
            '"(objectclass=*)"',
            '"*"',
        );

        // remove password from debug log
        $command_debug     = $command;
        $command_debug[11] = '*';

        $command       = implode(' ', $command);
        $command_debug = implode(' ', $command_debug);

        $this->_debug("LDAP: Executing command: $command_debug");

        exec($command, $output, $return_code);

        $this->_debug("LDAP: Command output:" . var_export($output, true));
        $this->_debug("Return code: " . $return_code);

        if ($return_code) {
            $this->_error("Command $moz_ldapsearch returned error code: $return_code");
            return null;
        }

        $lines = array();
        foreach ($output as $line_num => $line) {
            if (substr($line, 0, 1) == " ") {
                $lines[count($lines)-1] .= trim($line);
            }
            else {
                $lines[] = trim($line);
            }
        }

        foreach ($lines as $line) {
            $line_components = explode(':', $line);
            $attribute_name  = array_shift($line_components);
            $attribute_value = trim(implode(':', $line_components));

            switch ($attribute_name) {
                case "attributeLevelRights":
                    $attributes[$attribute_name] = $this->parse_attribute_level_rights($attribute_value);
                    break;
                case "dn":
                    $attributes[$attribute_name] = $attribute_value;
                    break;
                case "entryLevelRights":
                    $attributes[$attribute_name] = $this->parse_entry_level_rights($attribute_value);
                    break;

                default:
                    break;
            }
        }

        return $attributes;
    }

    /**
     * Resolve entry data to entry DN
     *
     * @param string $subject    Entry string (e.g. entry DN or unique attribute value)
     * @param array  $attributes Additional attributes
     * @param string $base_dn    Optional base DN
     *
     * @return string Entry DN string
     */
    public function entry_dn($subject, $attributes = array(), $base_dn = null)
    {
        $this->_debug("entry_dn on subject $subject");
        $is_dn = ldap_explode_dn($subject, 1);

        if (is_array($is_dn) && array_key_exists("count", $is_dn) && $is_dn["count"] > 0) {
            $this->_debug("$subject is a dn");
            return $subject;
        }

        $this->_debug("$subject is not a dn");

        if (strlen($subject) < 32 || preg_match('/[^a-fA-F0-9-]/', $subject)) {
            $this->_debug("$subject is not a unique identifier");
            return;
        }

        $unique_attr = $this->config_get('unique_attribute', 'nsuniqueid');

        $this->_debug("Using unique_attribute " . var_export($unique_attr, true) . " at " . __FILE__ . ":" . __LINE__);

        $attributes  = array_merge(array($unique_attr => $subject), (array)$attributes);
        $subject     = $this->entry_find_by_attribute($attributes, $base_dn);

        if (!empty($subject)) {
            return key($subject);
        }
    }

    public function entry_find_by_attribute($attributes, $base_dn = null)
    {
        $this->_debug("Net_LDAP3::entry_find_by_attribute(\$attributes, \$base_dn) called with base_dn", $base_dn, "and attributes", $attributes);

        if (empty($attributes) || !is_array($attributes)) {
            return false;
        }

        if (empty($attributes[key($attributes)])) {
            return false;
        }

        $filter = count($attributes) ? "(&" : "";

        foreach ($attributes as $key => $value) {
            $filter .= "(" . $key . "=" . $value . ")";
        }

        $filter .= count($attributes) ? ")" : "";

        if (empty($base_dn)) {
            $base_dn = $this->config_get('root_dn');
            $this->_debug("Using base_dn from domain " . $this->domain . ": " . $base_dn);
        }

        $result = $this->search($base_dn, $filter, 'sub', array_keys($attributes));

        if ($result && $result->count() > 0) {
            $this->_debug("Results found: " . implode(', ', array_keys($result->entries(true))));
            return $result->entries(true);
        }
        else {
            $this->_debug("No result");
            return false;
        }
    }

    public function find_user_groups($member_dn)
    {
        $groups  = array();
        $root_dn = $this->config_get('root_dn');

        // TODO: Do not query for both, it's either one or the other
        $entries = $this->search($root_dn, "(|" .
            "(&(objectclass=groupofnames)(member=$member_dn))" .
            "(&(objectclass=groupofuniquenames)(uniquemember=$member_dn))" .
            ")"
        );

        if ($entries) {
            $groups = array_keys($entries->entries(true));
        }

        return $groups;
    }

    public function get_entry_attribute($subject_dn, $attribute)
    {
        $entry = $this->get_entry_attributes($subject_dn, (array)$attribute);

        return $entry[strtolower($attribute)];
    }

    public function get_entry_attributes($subject_dn, $attributes)
    {
        // @TODO: use get_entry?
        $result = $this->search($subject_dn, '(objectclass=*)', 'base', $attributes);

        if (!$result) {
            return array();
        }

        $entries  = $result->entries(true);
        $entry_dn = key($entries);
        $entry    = $entries[$entry_dn];

        return $entry;
    }

    /**
     * Get a specific LDAP entry, identified by its DN
     *
     * @param string $dn         Record identifier
     * @param array  $attributes Attributes to return
     *
     * @return array Hash array
     */
    public function get_entry($dn, $attributes = array())
    {
        $rec = null;

        if ($this->conn && $dn) {
            $this->_debug("C: Read [dn: $dn] [(objectclass=*)]");

            if ($ldap_result = @ldap_read($this->conn, $dn, '(objectclass=*)', $attributes)) {
                $this->_debug("S: OK");

                if ($entry = ldap_first_entry($this->conn, $ldap_result)) {
                    $rec = ldap_get_attributes($this->conn, $entry);
                }
            }
            else {
                $this->_debug("S: ".ldap_error($this->conn));
            }

            if (!empty($rec)) {
                $rec['dn'] = $dn; // Add in the dn for the entry.
            }
        }

        return $rec;
    }

    public function list_replicas()
    {
        $this->_debug("Finding replicas for this server.");

        // Search any host that is a replica for the current host
        $replica_hosts = $this->config_get('replica_hosts', array());
        $root_dn       = $this->config_get('config_root_dn');

        if (!empty($replica_hosts)) {
            return $replica_hosts;
        }

        $ldap = new Net_LDAP3($this->config);
        $ldap->connect();
        $ldap->bind($this->_current_bind_dn, $this->_current_bind_pw);

        $result = $ldap->search($root_dn, '(objectclass=nsds5replicationagreement)', 'sub', array('nsds5replicahost'));

        if (!$result) {
            $this->_debug("No replicas configured");
            return $replica_hosts;
        }

        $this->_debug("Replication agreements found: " . var_export($result->entries(true), true));

        foreach ($result->entries(true) as $dn => $attrs) {
            if (!in_array($attrs['nsds5replicahost'], $replica_hosts)) {
                $replica_hosts[] = $attrs['nsds5replicahost'];
            }
        }

        // $replica_hosts now holds the IDs of servers we are currently NOT
        // connected to. We might need this later in order to set
        $this->_server_id_not = $replica_hosts;

        $this->_debug("So far, we have the following replicas: " . var_export($replica_hosts, true));

        $ldap->close();

        foreach ($replica_hosts as $replica_host) {
            $ldap->config_set('hosts', array($replica_host));
            $ldap->connect();
            $ldap->bind($this->_current_bind_dn, $this->_current_bind_pw);

            $result = $ldap->search($root_dn, '(objectclass=nsds5replicationagreement)', 'sub', array('nsds5replicahost'));
            if (!$result) {
                $this->_debug("No replicas configured");
            }

            foreach ($result->entries(true) as $dn => $attrs) {
                if (!in_array($attrs['nsds5replicahost'], $replica_hosts)) {
                    $replica_hosts[] = $attrs['nsds5replicahost'];
                }
            }

            $ldap->close();
        }

        $this->config_set('replica_hosts', $replica_hosts);

        return $replica_hosts;
    }

    public function login($username, $password, $domain = null)
    {
        $this->_debug("Net_LDAP3::login(\$username = '" . $username . "', \$password = '****', \$domain = '" . $domain . "')");

        $_bind_dn = $this->config_get('service_bind_dn');
        $_bind_pw = $this->config_get('service_bind_pw');

        if (empty($_bind_dn)) {
            $this->_debug("No valid service bind dn found.");
            return null;
        }

        if (empty($_bind_pw)) {
            $this->_debug("No valid service bind password found.");
            return null;
        }

        $bound = $this->bind($_bind_dn, $_bind_pw);

        if (!$bound) {
            $this->_debug("Could not bind with service bind credentials.");
            return null;
        }

        $entry_dn = $this->entry_dn($username);

        if (!empty($entry_dn)) {
            $bound = $this->bind($entry_dn, $password);

            if (!$bound) {
                $this->_error("Could not bind with " . $entry_dn);
                return null;
            }

            return $entry_dn;
        }

        $base_dn = $this->config_get('root_dn');

        if (empty($base_dn)) {
            $this->_debug("Could not get a valid base dn to search.");
            return null;
        }

        $localpart = $username;

        if (empty($domain) ) {
            if (count(explode('@', $username)) > 1) {
                $_parts    = explode('@', $username);
                $localpart = $_parts[0];
                $domain    = $_parts[1];
            }
            else {
                $localpart = $username;
                $domain    = '';
            }
        }

        $realm  = $domain;
        $filter = $this->config_get("login_filter", null);

        if (empty($filter)) {
            $filter = $this->config_get("filter", null);
        }
        if (empty($filter)) {
            $filter = "(&(|(mail=%s)(mail=%U@%d)(alias=%s)(alias=%U@%d)(uid=%s))(objectclass=inetorgperson))";
        }

        $this->_debug("Net::LDAP3::login() original filter: " . $filter);

        $replace_patterns = array(
            '/%s/' => $username,
            '/%d/' => $domain,
            '/%U/' => $localpart,
            '/%r/' => $realm
        );

        $filter = preg_replace(array_keys($replace_patterns), array_values($replace_patterns), $filter);

        $this->_debug("Net::LDAP3::login() actual filter: " . $filter);

        $result = $this->search($base_dn, $filter, 'sub');

        if (!$result) {
            $this->_debug("Could not search $base_dn with $filter");
            return null;
        }

        if ($result->count() > 1) {
            $this->_debug("Multiple entries found.");
            return null;
        }
        else if ($result->count() < 1) {
            $this->_debug("No entries found.");
            return null;
        }

        $entries  = $result->entries();
        $entry    = self::normalize_result($entries);
        $entry_dn = key($entry);

        $bound = $this->bind($entry_dn, $password);

        if (!$bound) {
            $this->_debug("Could not bind with " . $entry_dn);
            return null;
        }

        return $entry_dn;
    }

    public function list_group_members($dn, $entry = null, $recurse = true)
    {
        $this->_debug("Called list_group_members(" . $dn . ")");

        if (is_array($entry) && in_array('objectclass', $entry)) {
            if (!in_array(array('groupofnames', 'groupofuniquenames', 'groupofurls'), $entry['objectclass'])) {
                $this->_debug("Called list_group_members on a non-group!");
                return array();
            }
        }
        else {
            $entry = $this->get_entry($dn, array('member', 'uniquemember', 'memberurl', 'objectclass'));

            if (!$entry) {
                return array();
            }
        }

        $group_members = array();

        foreach ((array)$entry['objectclass'] as $objectclass) {
            switch (strtolower($objectclass)) {
                case "groupofnames":
                case "kolabgroupofnames":
                    $group_members = array_merge($group_members, $this->list_group_member($dn, $entry['member'], $recurse));
                    break;
                case "groupofuniquenames":
                case "kolabgroupofuniquenames":
                    $group_members = array_merge($group_members, $this->list_group_uniquemember($dn, $entry['uniquemember'], $recurse));
                    break;
                case "groupofurls":
                    $group_members = array_merge($group_members, $this->list_group_memberurl($dn, $entry['memberurl'], $recurse));
                    break;
            }
        }

        return array_values(array_filter($group_members));
    }

    public function modify_entry($subject_dn, $old_attrs, $new_attrs)
    {
        $this->_debug("OLD ATTRIBUTES", $old_attrs);
        $this->_debug("NEW ATTRIBUTES", $new_attrs);

        // TODO: Get $rdn_attr - we have type_id in $new_attrs
        $dn_components  = ldap_explode_dn($subject_dn, 0);
        $rdn_components = explode('=', $dn_components[0]);
        $rdn_attr       = $rdn_components[0];

        $this->_debug("Net_LDAP3::modify_entry() using rdn attribute: " . $rdn_attr);

        $mod_array = array(
            'add'       => array(), // For use with ldap_mod_add()
            'del'       => array(), // For use with ldap_mod_del()
            'replace'   => array(), // For use with ldap_mod_replace()
            'rename'    => array(), // For use with ldap_rename()
        );

        // This is me cheating. Remove this special attribute.
        if (array_key_exists('ou', $old_attrs) || array_key_exists('ou', $new_attrs)) {
            $old_ou = $old_attrs['ou'];
            $new_ou = $new_attrs['ou'];
            unset($old_attrs['ou']);
            unset($new_attrs['ou']);
        }
        else {
            $old_ou = null;
            $new_ou = null;
        }

        // Compare each attribute value of the old attrs with the corresponding value
        // in the new attrs, if any.
        foreach ($old_attrs as $attr => $old_attr_value) {
            if (is_array($old_attr_value)) {
                if (count($old_attr_value) == 1) {
                    $old_attrs[$attr] = $old_attr_value[0];
                    $old_attr_value = $old_attrs[$attr];
                }
            }

            if (array_key_exists($attr, $new_attrs)) {
                if (is_array($new_attrs[$attr])) {
                    if (count($new_attrs[$attr]) == 1) {
                        $new_attrs[$attr] = $new_attrs[$attr][0];
                    }
                }

                if (is_array($old_attrs[$attr]) && is_array($new_attrs[$attr])) {
                    $_sort1 = $new_attrs[$attr];
                    sort($_sort1);
                    $_sort2 = $old_attr_value;
                    sort($_sort2);
                }
                else {
                    $_sort1 = true;
                    $_sort2 = false;
                }

                if ($new_attrs[$attr] !== $old_attr_value && $_sort1 !== $_sort2) {
                    $this->_debug("Attribute $attr changed from " . var_export($old_attr_value, true) . " to " . var_export($new_attrs[$attr], true));
                    if ($attr === $rdn_attr) {
                        $this->_debug("This attribute is the RDN attribute. Let's see if it is multi-valued, and if the original still exists in the new value.");
                        if (is_array($old_attrs[$attr])) {
                            if (!is_array($new_attrs[$attr])) {
                                if (in_array($new_attrs[$attr], $old_attrs[$attr])) {
                                    // TODO: Need to remove all $old_attrs[$attr] values not equal to $new_attrs[$attr], and not equal to the current $rdn_attr value [0]

                                    $this->_debug("old attrs. is array, new attrs. is not array. new attr. exists in old attrs.");

                                    $rdn_attr_value = array_shift($old_attrs[$attr]);
                                    $_attr_to_remove = array();

                                    foreach ($old_attrs[$attr] as $value) {
                                        if (strtolower($value) != strtolower($new_attrs[$attr])) {
                                            $_attr_to_remove[] = $value;
                                        }
                                    }

                                    $this->_debug("Adding to delete attribute $attr values:" . implode(', ', $_attr_to_remove));

                                    $mod_array['del'][$attr] = $_attr_to_remove;

                                    if (strtolower($new_attrs[$attr]) !== strtolower($rdn_attr_value)) {
                                        $this->_debug("new attrs is not the same as the old rdn value, issuing a rename");
                                        $mod_array['rename']['dn'] = $subject_dn;
                                        $mod_array['rename']['new_rdn'] = $rdn_attr . '=' . $new_attrs[$attr][0];
                                    }
                                }
                                else {
                                    $this->_debug("new attrs is not the same as any of the old rdn value, issuing a full rename");
                                    $mod_array['rename']['dn'] = $subject_dn;
                                    $mod_array['rename']['new_rdn'] = $rdn_attr . '=' . $new_attrs[$attr];
                                }
                            }
                            else {
                                // TODO: See if the rdn attr. value is still in $new_attrs[$attr]
                                if (in_array($old_attrs[$attr][0], $new_attrs[$attr])) {
                                    $this->_debug("Simply replacing attr $attr as rdn attr value is preserved.");
                                    $mod_array['replace'][$attr] = $new_attrs[$attr];
                                }
                                else {
                                    // TODO: This fails.
                                    $mod_array['rename']['dn'] = $subject_dn;
                                    $mod_array['rename']['new_rdn'] = $rdn_attr . '=' . $new_attrs[$attr][0];
                                    $mod_array['del'][$attr] = $old_attrs[$attr][0];
                                }
                            }
                        }
                        else {
                            if (!is_array($new_attrs[$attr])) {
                                $this->_debug("Renaming " . $old_attrs[$attr] . " to " . $new_attrs[$attr]);
                                $mod_array['rename']['dn'] = $subject_dn;
                                $mod_array['rename']['new_rdn'] = $rdn_attr . '=' . $new_attrs[$attr];
                            }
                            else {
                                $this->_debug("Adding to replace");
                                // An additional attribute value is being supplied. Just replace and continue.
                                $mod_array['replace'][$attr] = $new_attrs[$attr];
                                continue;
                            }
                        }

                    }
                    else {
                        if (!isset($new_attrs[$attr]) || $new_attrs[$attr] === '' || (is_array($new_attrs[$attr]) && empty($new_attrs[$attr]))) {
                            switch ($attr) {
                                case "userpassword":
                                    break;
                                default:
                                    $this->_debug("Adding to del: $attr");
                                    $mod_array['del'][$attr] = (array)($old_attr_value);
                                    break;
                            }
                        }
                        else {
                            $this->_debug("Adding to replace: $attr");
                            $mod_array['replace'][$attr] = (array)($new_attrs[$attr]);
                        }
                    }
                }
                else {
                    $this->_debug("Attribute $attr unchanged");
                }
            }
            else {
                // TODO: Since we're not shipping the entire object back and forth, and only post
                // part of the data... we don't know what is actually removed (think modifiedtimestamp, etc.)
                $this->_debug("Group attribute $attr not mentioned in \$new_attrs..., but not explicitly removed... by assumption");
            }
        }

        foreach ($new_attrs as $attr => $value) {
            // OU's parent base dn
            if ($attr == 'base_dn') {
                continue;
            }

            if (is_array($value)) {
                if (count($value) == 1) {
                    $new_attrs[$attr] = $value[0];
                    $value = $new_attrs[$attr];
                }
            }

            if (array_key_exists($attr, $old_attrs)) {
                if (is_array($old_attrs[$attr])) {
                    if (count($old_attrs[$attr]) == 1) {
                        $old_attrs[$attr] = $old_attrs[$attr][0];
                    }
                }

                if (is_array($new_attrs[$attr]) && is_array($old_attrs[$attr])) {
                    $_sort1 = $old_attrs[$attr];
                    sort($_sort1);
                    $_sort2 = $value;
                    sort($_sort2);
                }
                else {
                    $_sort1 = true;
                    $_sort2 = false;
                }

                if ($value === null || $value === '' || (is_array($value) && empty($value))) {
                    if (!array_key_exists($attr, $mod_array['del'])) {
                        switch ($attr) {
                            case 'userpassword':
                                break;
                            default:
                                $this->_debug("Adding to del(2): $attr");
                                $mod_array['del'][$attr] = (array)($old_attrs[$attr]);
                                break;
                        }
                    }
                }
                else {
                    if (!($old_attrs[$attr] === $value) && !($attr === $rdn_attr) && !($_sort1 === $_sort2)) {
                        if (!array_key_exists($attr, $mod_array['replace'])) {
                            $this->_debug("Adding to replace(2): $attr");
                            $mod_array['replace'][$attr] = $value;
                        }
                    }
                }
            }
            else {
                if (!empty($value)) {
                    $mod_array['add'][$attr] = $value;
                }
            }
        }

        if (empty($old_ou)) {
            $subject_dn_components = ldap_explode_dn($subject_dn, 0);
            unset($subject_dn_components["count"]);
            $subject_rdn = array_shift($subject_dn_components);
            $old_ou      = implode(',', $subject_dn_components);
        }

        // object is an organizational unit
        if (strpos($subject_dn, 'ou=' . $old_ou) === 0) {
            $root = substr($subject_dn, strlen($old_ou) + 4); // remove ou=*,

            if ((!empty($new_attrs['base_dn']) && strtolower($new_attrs['base_dn']) !== strtolower($root))
                || (strtolower($old_ou) !== strtolower($new_ou))
            ) {
                if (!empty($new_attrs['base_dn'])) {
                    $root = $new_attrs['base_dn'];
                }

                $mod_array['rename']['new_parent'] = $root;
                $mod_array['rename']['dn']         = $subject_dn;
                $mod_array['rename']['new_rdn']    = 'ou=' . $new_ou;
            }
        }
        // not OU object, but changed ou attribute
        else if ((!empty($old_ou) && !empty($new_ou)) && strtolower($old_ou) !== strtolower($new_ou)) {
            $mod_array['rename']['new_parent'] = $new_ou;
            if (empty($mod_array['rename']['dn']) || empty($mod_array['rename']['new_rdn'])) {
                $mod_array['rename']['dn']      = $subject_dn;
                $mod_array['rename']['new_rdn'] = $rdn_attr . '=' . $new_attrs[$rdn_attr];
            }
        }

        $this->_debug($mod_array);

        $result = $this->modify_entry_attributes($subject_dn, $mod_array);

        if ($result) {
            return $mod_array;
        }
    }

    /**
     * Bind connection with (SASL-) user and password
     *
     * @param string $authc Authentication user
     * @param string $pass  Bind password
     * @param string $authz Autorization user
     *
     * @return boolean True on success, False on error
     */
    public function sasl_bind($authc, $pass, $authz=null)
    {
        if (!$this->conn) {
            return false;
        }

        if (!function_exists('ldap_sasl_bind')) {
            $this->_error("Unable to bind: ldap_sasl_bind() not exists");
            return false;
        }

        if (!empty($authz)) {
            $authz = 'u:' . $authz;
        }

        $method = $this->config_get('auth_method');
        if (empty($method)) {
            $method = 'DIGEST-MD5';
        }

        $this->_debug("C: Bind [mech: $method, authc: $authc, authz: $authz]");

        if (ldap_sasl_bind($this->conn, null, $pass, $method, null, $authc, $authz)) {
            $this->_debug("S: OK");
            return true;
        }

        $this->_debug("S: ".ldap_error($this->conn));
        $this->_error("Bind failed for authcid=$authc ".ldap_error($this->conn));

        return false;
    }

    /**
     * Execute LDAP search
     *
     * @param string $base_dn    Base DN to use for searching
     * @param string $filter     Filter string to query
     * @param string $scope      The LDAP scope (list|sub|base)
     * @param array  $attrs      List of entry attributes to read
     * @param array  $prop       Hash array with query configuration properties:
     *   - sort:   array of sort attributes (has to be in sync with the VLV index)
     *   - search: search string used for VLV controls
     * @param bool   $count_only Set to true if only entry count is requested
     *
     * @return mixed Net_LDAP3_Result object or number of entries (if $count_only=true) or False on failure
     */
    public function search($base_dn, $filter = '(objectclass=*)', $scope = 'sub', $attrs = array('dn'), $props = array(), $count_only = false)
    {
        if (!$this->conn) {
            $this->_debug("No active connection for " . __CLASS__ . "::" . __FUNCTION__);
            return false;
        }

        $this->_debug("C: Search base dn: [$base_dn] scope [$scope] with filter [$filter]");

        // make sure attributes list is not empty
        if (empty($attrs)) {
            $attrs = array('dn');
        }

        if (!$count_only && ($sort = $this->find_vlv($base_dn, $filter, $scope, $props['sort']))) {
            // when using VLV, we get the total count by...
            // ...either reading numSubOrdinates attribute
            if (($sub_filter = $this->config_get('numsub_filter')) &&
                ($result_count = @$ns_function($this->conn, $base_dn, $sub_filter, array('numSubOrdinates'), 0, 0, 0))
            ) {
                $counts = ldap_get_entries($this->conn, $result_count);
                for ($vlv_count = $j = 0; $j < $counts['count']; $j++) {
                    $vlv_count += $counts[$j]['numsubordinates'][0];
                }
                $this->_debug("D: total numsubordinates = " . $vlv_count);
            }
            // ...or by fetching all records dn and count them
            else if (!function_exists('ldap_parse_virtuallist_control')) {
                $vlv_count = $this->search($base_dn, $filter, $scope, array('dn'), $props, true);
            }

            $this->vlv_active = $this->_vlv_set_controls($sort, $this->list_page, $this->page_size,
                $this->_vlv_search($sort, $props['search']));
        }
        else {
            $this->vlv_active = false;
        }

        $function  = self::scope_to_function($scope, $ns_function);
        $sizelimit = (int) $this->config['sizelimit'];
        $timelimit = (int) $this->config['timelimit'];

        $this->_debug("Using function $function on scope $scope (\$ns_function is $ns_function)");

        if ($this->vlv_active) {
            if (!empty($this->additional_filter)) {
                $filter = "(&" . $filter . $this->additional_filter . ")";
                $this->_debug("C: (With VLV) Setting a filter (with additional filter) of " . $filter);
            }
            else {
                $this->_debug("C: (With VLV) Setting a filter (without additional filter) of " . $filter);
            }
        }
        else {
            if (!empty($this->additional_filter)) {
                $filter = "(&" . $filter . $this->additional_filter . ")";
            }
            $this->_debug("C: (Without VLV) Setting a filter of " . $filter);
        }

        $this->_debug("Executing search with return attributes: " . var_export($attrs, true));

        $ldap_result = @$function($this->conn, $base_dn, $filter, $attrs, 0, $sizelimit, $timelimit);

        if (!$ldap_result) {
            $this->_debug("$function failed for dn=$base_dn: ".ldap_error($this->conn));
            return false;
        }

        // when running on a patched PHP we can use the extended functions
        // to retrieve the total count from the LDAP search result
        if ($this->vlv_active && function_exists('ldap_parse_virtuallist_control')) {
            if (ldap_parse_result($this->conn, $ldap_result, $errcode, $matcheddn, $errmsg, $referrals, $serverctrls)) {
                ldap_parse_virtuallist_control($this->conn, $serverctrls, $last_offset, $vlv_count, $vresult);
                $this->_debug("S: VLV result: last_offset=$last_offset; content_count=$vlv_count");
            }
            else {
                $this->_debug("S: ".($errmsg ? $errmsg : ldap_error($this->conn)));
            }
        }
        else if ($this->debug) {
            $this->_debug("S: ".ldap_count_entries($this->conn, $ldap_result)." record(s) found");
        }

        $result = new Net_LDAP3_Result($this->conn, $base_dn, $filter, $scope, $ldap_result);
        $result->set('offset', $last_offset);
        $result->set('count', $vlv_count);
        $result->set('vlv', true);

        return $count_only ? $result->count() : $result;
    }

    /**
     * Similar to Net_LDAP3::search() but using a search array with multiple
     * keys and values that to continue to use the VLV but with an original
     * filter adding the search stuff to an additional filter.
     *
     * @see Net_LDAP3::search()
     */
    public function search_entries($base_dn, $filter = '(objectclass=*)', $scope = 'sub', $attrs = array('dn'), $props = array())
    {
        $this->_debug("Net_LDAP3::search_entries with search " . var_export($props, true));

        if (is_array($props['search']) && array_key_exists('params', $props['search'])) {
            $_search = $this->search_filter($props['search']);
            $this->_debug("C: Search filter: $_search");

            if (!empty($_search)) {
                $this->additional_filter = $_search;
            }
            else {
                $this->additional_filter = "(|";

                foreach ($props['search'] as $attr => $value) {
                    $this->additional_filter .= "(" . $attr . "=" . $this->_fuzzy_search_prefix() . $value . $this->_fuzzy_search_suffix() . ")";
                }

                $this->additional_filter .= ")";
            }

            $this->_debug("C: Setting an additional filter " . $this->additional_filter);
        }

        $search = $this->search($base_dn, $filter, $scope, $attrs, $props);

        $this->additional_filter = null;

        if (!$search) {
            $this->_debug("Net_LDAP3: Search did not succeed!");
            return false;
        }

        return $search;
    }

    /**
     * Create LDAP search filter string according to defined parameters.
     */
    public function search_filter($search)
    {
        if (empty($search) || !is_array($search) || empty($search['params'])) {
            return null;
        }

        $operators = array('=', '~=', '>=', '<=');
        $filter    = '';

        foreach ((array) $search['params'] as $field => $param) {
            switch ((string)$param['type']) {
                case 'prefix':
                    $prefix = '';
                    $suffix = '*';
                    break;

                case 'suffix':
                    $prefix = '*';
                    $suffix = '';
                    break;

                case 'exact':
                case '=':
                case '~=':
                case '>=':
                case '<=':
                    $prefix = '';
                    $suffix = '';
                    break;

                case 'exists':
                    $prefix = '*';
                    $suffix = '';
                    $param['value'] = '';
                    break;

                case 'both':
                default:
                    $prefix = '*';
                    $suffix = '*';
                    break;
            }

            $operator = $param['type'] && in_array($param['type'], $operators) ? $param['type'] : '=';

            if (is_array($param['value'])) {
                $val_filter = array();
                foreach ($param['value'] as $val) {
                    $value = self::quote_string($val);
                    $val_filter[] = "(" . $field . $operator . $prefix . $value . $suffix . ")";
                }
                $filter .= "(|" . implode($val_filter, '') . ")";
            }
            else {
                $value = self::quote_string($param['value']);
                $filter .= "(" . $field . $operator . $prefix . $value . $suffix . ")";
            }
        }

        // join search parameters with specified operator ('OR' or 'AND')
        if (count($search['params']) > 1) {
            $filter = '(' . ($search['operator'] == 'AND' ? '&' : '|') . $filter . ')';
        }

        return $filter;
    }

    /**
     * Set properties for VLV-based paging
     *
     * @param number $page Page number to list (starting at 1)
     * @param number $size Number of entries to display on one page
     */
    public function set_vlv_page($page, $size = 10)
    {
        $this->list_page = $page;
        $this->page_size = $size;
    }

    /**
     * Turn an LDAP entry into a regular PHP array with attributes as keys.
     *
     * @param array $entry Attributes array as retrieved from ldap_get_attributes() or ldap_get_entries()
     *
     * @return array Hash array with attributes as keys
     */
    public static function normalize_entry($entry)
    {
        $rec = array();
        for ($i=0; $i < $entry['count']; $i++) {
            $attr = $entry[$i];
            for ($j=0; $j < $entry[$attr]['count']; $j++) {
                $rec[$attr][$j] = $entry[$attr][$j];
            }
        }

        return $rec;
    }

    /**
     * Normalize a ldap result by converting entry attribute arrays into single values
     */
    public static function normalize_result($_result)
    {
        if (!is_array($_result)) {
            return array();
        }

        $result = array();

        for ($x = 0; $x < $_result['count']; $x++) {
            $dn = $_result[$x]['dn'];
            $result[$dn] = array();
            for ($y = 0; $y < $_result[$x]['count']; $y++) {
                $attr = $_result[$x][$y];
                if ($_result[$x][$attr]['count'] == 1) {
                    switch ($attr) {
                        case 'objectclass':
                            $result[$dn][$attr] = array(strtolower($_result[$x][$attr][0]));
                            break;
                        default:
                            $result[$dn][$attr] = $_result[$x][$attr][0];
                            break;
                    }
                }
                else {
                    $result[$dn][$attr] = array();
                    for ($z = 0; $z < $_result[$x][$attr]['count']; $z++) {
                        switch ($attr) {
                            case 'objectclass':
                                $result[$dn][$attr][] = strtolower($_result[$x][$attr][$z]);
                                break;
                            default:
                                $result[$dn][$attr][] = $_result[$x][$attr][$z];
                                break;
                        }
                    }
                }
            }
        }

        return $result;
    }

    public static function scopeint2str($scope)
    {
        switch ($scope) {
            case 2:
                return 'sub';
                break;
            case 1:
                return 'one';
                break;
            case 0:
                return 'base';
                break;
            default:
                $this->_debug("Scope $scope is not a valid scope integer");
                break;
        }
    }

    /**
     * Choose the right PHP function according to scope property
     *
     * @param string $scope         The LDAP scope (sub|base|list)
     * @param string $ns_function   Function to be used for numSubOrdinates queries
     * @return string  PHP function to be used to query directory
     */
    public static function scope_to_function($scope, &$ns_function = null)
    {
        switch ($scope) {
            case 'sub':
                $function = $ns_function  = 'ldap_search';
                break;
            case 'base':
                $function = $ns_function = 'ldap_read';
                break;
            case 'one':
            case 'list':
            default:
                $function    = 'ldap_list';
                $ns_function = 'ldap_read';
                break;
        }

        return $function;
    }

    private function config_set_config_get_hook($callback)
    {
        $this->_config_get_hook = $callback;
    }

    private function config_set_config_set_hook($callback)
    {
        $this->_config_set_hook = $callback;
    }

    /**
     * Sets the debug level both for this class and the ldap connection.
     */
    private function config_set_debug($value)
    {
        $this->config['debug'] = (bool) $value;
        if ((int)($value) > 0) {
            ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, (int)($value));
        }
    }

    /**
     *  Sets a log hook that is called with every log message in this module.
     */
    private function config_set_log_hook($callback)
    {
        $this->_log_hook = $callback;
    }

    /**
     * Find a matching VLV
     */
    protected function find_vlv($base_dn, $filter, $scope, $sort_attrs = null)
    {
        if ($scope == 'base') {
            return false;
        }

        $vlv_indexes = $this->find_vlv_indexes_and_searches();

        if (empty($vlv_indexes)) {
            return false;
        }

        $this->_debug("Existing vlv index and search information", $vlv_indexes);

        $filter = strtolower($filter);

        foreach ($vlv_indexes as $vlv_index) {
            if (!empty($vlv_index[$base_dn])) {
                $this->_debug("Found a VLV for base_dn: " . $base_dn);
                if ($vlv_index[$base_dn]['filter'] == $filter) {
                    if ($vlv_index[$base_dn]['scope'] == $scope) {
                        $this->_debug("Scope and filter matches");

                        // Not passing any sort attributes means you don't care
                        if (!empty($sort_attrs)) {
                            $sort_attrs = (array) $sort_attrs;
                            foreach ($vlv_index[$base_dn]['sort'] as $sss_config) {
                                if (count(array_intersect($sort_attrs, $sss_config)) == count($sort_attrs)) {
                                    return $sort_attrs;
                                }
                            }

                            $this->_error("The requested sorting does not match any server-side sorting configuration");

                            return false;
                        }
                        else {
                            return $vlv_index[$base_dn]['sort'][0];
                        }
                    }
                    else {
                        $this->_debug("Scope does not match. VLV: " . var_export($vlv_index[$base_dn]['scope'], true)
                            . " while looking for " . var_export($scope, true));
                        return false;
                    }
                }
                else {
                    $this->_debug("Filter does not match");
                }
            }
        }

        return false;
    }

    /**
     * Return VLV indexes and searches including necessary configuration
     * details.
     */
    protected function find_vlv_indexes_and_searches()
    {
        if ($this->config['vlv'] === false) {
            return false;
        }

        if (is_array($this->config['vlv'])) {
            return $this->config['vlv'];
        }

        if ($this->_vlv_indexes_and_searches !== null) {
            return $this->_vlv_indexes_and_searches;
        }

        $this->_vlv_indexes_and_searches = array();

        $config_root_dn = $this->config_get('config_root_dn');

        if (empty($config_root_dn)) {
            return array();
        }

        if ($this->cache && ($cached_config = $this->cache->get('vlvconfig'))) {
            $this->_vlv_indexes_and_searches = $cached_config;
            return $this->_vlv_indexes_and_searches;
        }

        $this->_debug("No VLV information available yet, refreshing");

        $search_filter = '(objectclass=vlvsearch)';
        $search_result = ldap_search($this->conn, $config_root_dn, $search_filter, array('*'), 0, 0, 0);

        if ($search_result === false) {
            $this->_debug("Search for '$search_filter' on '$config_root_dn' failed:".ldap_error($this->conn));
            return;
        }

        $vlv_searches = new Net_LDAP3_Result($this->conn, $config_root_dn, $search_filter, 'sub', $search_result);

        if ($vlv_searches->count() < 1) {
            $this->_debug("Empty result from search for '(objectclass=vlvsearch)' on '$config_root_dn'");
            return;
        }

        $index_filter = '(objectclass=vlvindex)';

        foreach ($vlv_searches->entries(true) as $vlv_search_dn => $vlv_search_attrs) {
            // The attributes we are interested in are as follows:
            $_vlv_base_dn = $vlv_search_attrs['vlvbase'];
            $_vlv_scope   = $vlv_search_attrs['vlvscope'];
            $_vlv_filter  = $vlv_search_attrs['vlvfilter'];

            // Multiple indexes may exist
            $index_result = ldap_search($this->conn, $vlv_search_dn, $index_filter, array('*'), 0, 0, 0);

            if ($index_result === false) {
                $this->_debug("Search for '$index_filter' on '$vlv_search_dn' failed:".ldap_error($this->conn));
                continue;
            }

            $vlv_indexes = new Net_LDAP3_Result($this->conn, $vlv_search_dn, $index_filter, 'sub', $index_result);
            $vlv_indexes = $vlv_indexes->entries(true);

            // Reset this one for each VLV search.
            $_vlv_sort = array();

            foreach ($vlv_indexes as $vlv_index_dn => $vlv_index_attrs) {
                $_vlv_sort[] = explode(' ', $vlv_index_attrs['vlvsort']);
            }

            $this->_vlv_indexes_and_searches[] = array(
                    $_vlv_base_dn => array(
                            'scope'  => self::scopeint2str($_vlv_scope),
                            'filter' => strtolower($_vlv_filter),
                            'sort'   => $_vlv_sort,
                        ),
                );
        }

        // cache this
        if ($this->cache) {
            $this->cache->set('vlvconfig', $this->_vlv_indexes_and_searches);
        }

        return $this->_vlv_indexes_and_searches;
    }

    private function init_schema()
    {
        // use PEAR include if autoloading failed
        if (!class_exists('Net_LDAP2')) {
            require_once('Net/LDAP2.php');
        }

        $port = $this->config_get('port', 389);
        $tls  = $this->config_get('use_tls', false);

        foreach ((array) $this->config_get('hosts') as $host) {
            $this->_debug("C: Connect [$host:$port]");

            $_ldap_cfg = array(
                'host'   => $host,
                'port'   => $port,
                'tls'    => $tls,
                'version' => 3,
                'binddn' => $this->config_get('service_bind_dn'),
                'bindpw' => $this->config_get('service_bind_pw')
            );

            $_ldap_schema_cache_cfg = array(
                'path' => "/tmp/" . $host . ":" . ($port ? $port : '389') . "-Net_LDAP2_Schema.cache",
                'max_age' => 86400,
            );

            $_ldap = Net_LDAP2::connect($_ldap_cfg);

            if (!is_a($_ldap, 'Net_LDAP2_Error')) {
                $this->_debug("S: OK");
                break;
            }

            $this->_debug("S: NOT OK");
            $this->_debug($_ldap->getMessage());
        }

        if (is_a($_ldap, 'Net_LDAP2_Error')) {
            return null;
        }

        $_ldap_schema_cache = new Net_LDAP2_SimpleFileSchemaCache($_ldap_schema_cache_cfg);

        $_ldap->registerSchemaCache($_ldap_schema_cache);

        // TODO: We should learn what LDAP tech. we're running against.
        // Perhaps with a scope base objectclass recognize rootdse entry
        $schema_root_dn = $this->config_get('schema_root_dn');

        if (!$schema_root_dn) {
            $_schema = $_ldap->schema();
        }

        return $_schema;
    }

    private function list_group_member($dn, $members, $recurse = true)
    {
        $this->_debug("Called list_group_member(" . $dn . ")");

        $members       = (array) $members;
        $group_members = array();

        // remove possible 'count' item
        unset($members['count']);

        // Use the member attributes to return an array of member ldap objects
        // NOTE that the member attribute is supposed to contain a DN
        foreach ($members as $member) {
            $member_entry = $this->get_entry($member, array('member', 'uniquemember', 'memberurl', 'objectclass'));

            if (empty($member_entry)) {
                continue;
            }

            $group_members[$member] = $member;

            if ($recurse) {
                // Nested groups
                $group_group_members = $this->list_group_members($member, $member_entry);
                if ($group_group_members) {
                    $group_members = array_merge($group_group_members, $group_members);
                }
            }
        }

        return array_filter($group_members);
    }

    private function list_group_uniquemember($dn, $uniquemembers, $recurse = true)
    {
        $this->_debug("Called list_group_uniquemember(" . $dn . ")", $entry);

        $uniquemembers = (array)($uniquemembers);
        $group_members = array();

        // remove possible 'count' item
        unset($uniquemembers['count']);

        foreach ($uniquemembers as $member) {
            $member_entry = $this->get_entry($member, array('member', 'uniquemember', 'memberurl', 'objectclass'));

            if (empty($member_entry)) {
                continue;
            }

            $group_members[$member] = $member;

            if ($recurse) {
                // Nested groups
                $group_group_members = $this->list_group_members($member, $member_entry);
                if ($group_group_members) {
                    $group_members = array_merge($group_group_members, $group_members);
                }
            }
        }

        return array_filter($group_members);
    }

    private function list_group_memberurl($dn, $memberurls, $recurse = true)
    {
        $this->_debug("Called list_group_memberurl(" . $dn . ")");

        $group_members = array();
        $memberurls    = (array) $memberurls;
        $attributes    = array('member', 'uniquemember', 'memberurl', 'objectclass');

        // remove possible 'count' item
        unset($memberurls['count']);

        foreach ($memberurls as $url) {
            $ldap_uri = $this->parse_memberurl($url);
            $result   = $this->search($ldap_uri[3], $ldap_uri[6], 'sub', $attributes);

            if (!$result) {
                continue;
            }

            foreach ($result->entries(true) as $entry_dn => $_entry) {
                $group_members[$entry_dn] = $entry_dn;
                $this->_debug("Found " . $entry_dn);

                if ($recurse) {
                    // Nested group
                    $group_group_members = $this->list_group_members($entry_dn, $_entry);
                    if ($group_group_members) {
                        $group_members = array_merge($group_members, $group_group_members);
                    }
                }
            }
        }

        return array_filter($group_members);
    }

    /**
     * memberUrl attribute parser
     *
     * @param string $url URL string
     *
     * @return array URL elements
     */
    private function parse_memberurl($url)
    {
        preg_match('/(.*):\/\/(.*)\/(.*)\?(.*)\?(.*)\?(.*)/', $url, $matches);
        return $matches;
    }

    private function modify_entry_attributes($subject_dn, $attributes)
    {
        // Opportunities to set false include failed ldap commands.
        $result = true;

        if (is_array($attributes['rename']) && !empty($attributes['rename'])) {
            $olddn  = $attributes['rename']['dn'];
            $newrdn = $attributes['rename']['new_rdn'];

            if (!empty($attributes['rename']['new_parent'])) {
                $new_parent = $attributes['rename']['new_parent'];
            }
            else {
                $new_parent = null;
            }

            $this->_debug("LDAP: C: Rename $olddn to $newrdn,$new_parent");

            $result = ldap_rename($this->conn, $olddn, $newrdn, $new_parent, true);

            if ($result) {
                $this->_debug("LDAP: S: OK");

                if ($new_parent) {
                    $subject_dn = $newrdn . ',' . $new_parent;
                }
                else {
                    $old_parent_dn_components = ldap_explode_dn($olddn, 0);
                    unset($old_parent_dn_components["count"]);
                    $old_rdn       = array_shift($old_parent_dn_components);
                    $old_parent_dn = implode(",", $old_parent_dn_components);
                    $subject_dn    = $newrdn . ',' . $old_parent_dn;
                }
            }
            else {
                $this->_debug("LDAP: S: " . ldap_error($this->conn));
                $this->_warning("LDAP: Failed to rename $olddn to $newrdn,$new_parent");
                return false;
            }
        }

        if (is_array($attributes['replace']) && !empty($attributes['replace'])) {
            $this->_debug("LDAP: C: Mod-Replace $subject_dn: " . json_encode($attributes['replace']));

            $result = ldap_mod_replace($this->conn, $subject_dn, $attributes['replace']);

            if ($result) {
                $this->_debug("LDAP: S: OK");
            }
            else {
                $this->_debug("LDAP: S: " . ldap_error($this->conn));
                $this->_warning("LDAP: Failed to replace attributes on $subject_dn: " . json_encode($attributes['replace']));
                return false;
            }
        }

        if (is_array($attributes['del']) && !empty($attributes['del'])) {
            $this->_debug("LDAP: C: Mod-Delete $subject_dn: " . json_encode($attributes['del']));

            $result = ldap_mod_del($this->conn, $subject_dn, $attributes['del']);

            if ($result) {
                $this->_debug("LDAP: S: OK");
            }
            else {
                $this->_debug("LDAP: S: " . ldap_error($this->conn));
                $this->_warning("LDAP: Failed to delete attributes on $subject_dn: " . json_encode($attributes['del']));
                return false;
            }
        }

        if (is_array($attributes['add']) && !empty($attributes['add'])) {
            $this->_debug("LDAP: C: Mod-Add $subject_dn: " . json_encode($attributes['add']));

            $result = ldap_mod_add($this->conn, $subject_dn, $attributes['add']);

            if ($result) {
                $this->_debug("LDAP: S: OK");
            }
            else {
                $this->_debug("LDAP: S: " . ldap_error($this->conn));
                $this->_warning("LDAP: Failed to add attributes on $subject_dn: " . json_encode($attributes['add']));
                return false;
            }
        }

        return true;
    }

    private function parse_attribute_level_rights($attribute_value)
    {
        $attribute_value  = str_replace(", ", ",", $attribute_value);
        $attribute_values = explode(",", $attribute_value);
        $attribute_value  = array();

        foreach ($attribute_values as $access_right) {
            $access_right_components = explode(":", $access_right);
            $access_attribute        = strtolower(array_shift($access_right_components));
            $access_value            = array_shift($access_right_components);

            $attribute_value[$access_attribute] = array();

            for ($i = 0; $i < strlen($access_value); $i++) {
                $method = $this->attribute_level_rights_map[substr($access_value, $i, 1)];

                if (!in_array($method, $attribute_value[$access_attribute])) {
                    $attribute_value[$access_attribute][] = $method;
                }
            }
        }

        return $attribute_value;
    }

    private function parse_entry_level_rights($attribute_value)
    {
        $_attribute_value = array();

        for ($i = 0; $i < strlen($attribute_value); $i++) {
            $method = $this->entry_level_rights_map[substr($attribute_value, $i, 1)];

            if (!in_array($method, $_attribute_value)) {
                $_attribute_value[] = $method;
            }
        }

        return $_attribute_value;
    }

    private function supported_controls()
    {
        if (!empty($this->supported_controls)) {
            return $this->supported_controls;
        }

        $this->_info("Obtaining supported controls");

        if ($result = $this->search('', '(objectclass=*)', 'base', array('supportedcontrol'))) {
            $result  = $result->entries(true);
            $control = $result['']['supportedcontrol'];
        }
        else {
            $control = array();
        }

        $this->_info("Obtained " . count($control) . " supported controls");
        $this->supported_controls = $control;

        return $control;
    }

    protected function _alert()
    {
        $this->__log(LOG_ALERT, func_get_args());
    }

    protected function _critical()
    {
        $this->__log(LOG_CRIT, func_get_args());
    }

    protected function _debug()
    {
        $this->__log(LOG_DEBUG, func_get_args());
    }

    protected function _emergency()
    {
        $this->__log(LOG_EMERG, func_get_args());
    }

    protected function _error()
    {
        $this->__log(LOG_ERR, func_get_args());
    }

    protected function _info()
    {
        $this->__log(LOG_INFO, func_get_args());
    }

    protected function _notice()
    {
        $this->__log(LOG_NOTICE, func_get_args());
    }

    protected function _warning()
    {
        $this->__log(LOG_WARNING, func_get_args());
    }

    /**
     *  Log a message.
     */
    private function __log($level, $args)
    {
        $msg = array();

        foreach ($args as $arg) {
            $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
        }

        if (!empty($this->_log_hook)) {
            call_user_func_array($this->_log_hook, array($level, $msg));
            return;
        }

        if ($this->debug_level > 0) {
            syslog($level, implode("\n", $msg));
        }
    }

    /**
     * Add BER sequence with correct length and the given identifier
     */
    private static function _ber_addseq($str, $identifier)
    {
        $len = dechex(strlen($str)/2);
        if (strlen($len) % 2 != 0) {
            $len = '0'.$len;
        }

        return $identifier . $len . $str;
    }

    /**
     * Returns BER encoded integer value in hex format
     */
    private static function _ber_encode_int($offset)
    {
        $val    = dechex($offset);
        $prefix = '';

        // check if bit 8 of high byte is 1
        if (preg_match('/^[89abcdef]/', $val)) {
            $prefix = '00';
        }

        if (strlen($val)%2 != 0) {
            $prefix .= '0';
        }

        return $prefix . $val;
    }

    /**
     * Quotes attribute value string
     *
     * @param string $str Attribute value
     * @param bool   $dn  True if the attribute is a DN
     *
     * @return string Quoted string
     */
    public static function quote_string($str, $is_dn = false)
    {
        // take firt entry if array given
        if (is_array($str)) {
            $str = reset($str);
        }

        if ($is_dn) {
            $replace = array(
                ',' => '\2c',
                '=' => '\3d',
                '+' => '\2b',
                '<' => '\3c',
                '>' => '\3e',
                ';' => '\3b',
                "\\"=> '\5c',
                '"' => '\22',
                '#' => '\23'
            );
        }
        else {
            $replace = array(
                '*' => '\2a',
                '(' => '\28',
                ')' => '\29',
                "\\" => '\5c',
                '/' => '\2f'
            );
        }

        return strtr($str, $replace);
    }

    /**
     * create ber encoding for sort control
     *
     * @param array List of cols to sort by
     * @return string BER encoded option value
     */
    private static function _sort_ber_encode($sortcols)
    {
        $str = '';
        foreach (array_reverse((array)$sortcols) as $col) {
            $ber_val = self::_string2hex($col);

            // 30 = ber sequence with a length of octet value
            // 04 = octet string with a length of the ascii value
            $oct = self::_ber_addseq($ber_val, '04');
            $str = self::_ber_addseq($oct, '30') . $str;
        }

        // now tack on sequence identifier and length
        $str = self::_ber_addseq($str, '30');

        return pack('H'.strlen($str), $str);
    }

    /**
     * Returns ascii string encoded in hex
     */
    private static function _string2hex($str)
    {
        $hex = '';
        for ($i=0; $i < strlen($str); $i++)
            $hex .= dechex(ord($str[$i]));

        return $hex;
    }

    /**
     * Generate BER encoded string for Virtual List View option
     *
     * @param integer List offset (first record)
     * @param integer Records per page
     * @return string BER encoded option value
     */
    private static function _vlv_ber_encode($offset, $rpp, $search = '')
    {
        // This string is ber-encoded, php will prefix this value with:
        // 04 (octet string) and 10 (length of 16 bytes)
        // the code behind this string is broken down as follows:
        // 30 = ber sequence with a length of 0e (14) bytes following
        // 02 = type integer (in two's complement form) with 2 bytes following (beforeCount): 01 00 (ie 0)
        // 02 = type integer (in two's complement form) with 2 bytes following (afterCount):  01 18 (ie 25-1=24)
        // a0 = type context-specific/constructed with a length of 06 (6) bytes following
        // 02 = type integer with 2 bytes following (offset): 01 01 (ie 1)
        // 02 = type integer with 2 bytes following (contentCount):  01 00

        // whith a search string present:
        // 81 = type context-specific/constructed with a length of 04 (4) bytes following (the length will change here)
        // 81 indicates a user string is present where as a a0 indicates just a offset search
        // 81 = type context-specific/constructed with a length of 06 (6) bytes following

        // the following info was taken from the ISO/IEC 8825-1:2003 x.690 standard re: the
        // encoding of integer values (note: these values are in
        // two-complement form so since offset will never be negative bit 8 of the
        // leftmost octet should never by set to 1):
        // 8.3.2: If the contents octets of an integer value encoding consist
        // of more than one octet, then the bits of the first octet (rightmost) and bit 8
        // of the second (to the left of first octet) octet:
        // a) shall not all be ones; and
        // b) shall not all be zero

        if ($search) {
            $search  = preg_replace('/[^-[:alpha:] ,.()0-9]+/', '', $search);
            $ber_val = self::_string2hex($search);
            $str     = self::_ber_addseq($ber_val, '81');
        }
        else {
            // construct the string from right to left
            $str = "020100"; # contentCount

            // returns encoded integer value in hex format
            $ber_val = self::_ber_encode_int($offset);

            // calculate octet length of $ber_val
            $str = self::_ber_addseq($ber_val, '02') . $str;

            // now compute length over $str
            $str = self::_ber_addseq($str, 'a0');
        }

        // now tack on records per page
        $str = "020100" . self::_ber_addseq(self::_ber_encode_int($rpp-1), '02') . $str;

        // now tack on sequence identifier and length
        $str = self::_ber_addseq($str, '30');

        return pack('H'.strlen($str), $str);
    }

    private function _fuzzy_search_prefix()
    {
        switch ($this->config_get("fuzzy_search", 2)) {
            case 2:
                return "*";
                break;
            case 1:
            case 0:
            default:
                return "";
                break;
        }
    }

    private function _fuzzy_search_suffix()
    {
        switch ($this->config_get("fuzzy_search", 2)) {
            case 2:
                return "*";
                break;
            case 1:
                return "*";
            case 0:
            default:
                return "";
                break;
        }
    }

    /**
     * Return the search string value to be used in VLV controls
     */
    private function _vlv_search($sort, $search)
    {
        if (!empty($this->additional_filter)) {
            $this->_debug("Not setting a VLV search filter because we already have a filter");
            return;
        }

        if (empty($search)) {
            return;
        }

        $search_suffix = $this->_fuzzy_search_suffix();

        foreach ($search as $attr => $value) {
            if (!in_array(strtolower($attr), $sort)) {
                $this->_debug("Cannot use VLV search using attribute not indexed: $attr (not in " . var_export($sort, true) . ")");
                return;
            }
            else {
                return $value . $search_suffix;
            }
        }
    }

    /**
     * Set server controls for Virtual List View (paginated listing)
     */
    private function _vlv_set_controls($sort, $list_page, $page_size, $search = null)
    {
        $sort_ctrl = array(
            'oid'   => "1.2.840.113556.1.4.473",
            'value' => self::_sort_ber_encode($sort)
        );

        if (!empty($search)) {
            $this->_debug("_vlv_set_controls to include search: " . var_export($search, true));
        }

        $vlv_ctrl  = array(
            'oid' => "2.16.840.1.113730.3.4.9",
            'value' => self::_vlv_ber_encode(
                    $offset = ($list_page-1) * $page_size + 1,
                    $page_size,
                    $search
            ),
            'iscritical' => true
        );

        $this->_debug("C: set controls sort=" . join(' ', unpack('H'.(strlen($sort_ctrl['value'])*2), $sort_ctrl['value']))
            . " (" . implode(',', (array) $sort) . ");"
            . " vlv=" . join(' ', (unpack('H'.(strlen($vlv_ctrl['value'])*2), $vlv_ctrl['value']))) . " ($offset/$page_size)");

        if (!ldap_set_option($this->conn, LDAP_OPT_SERVER_CONTROLS, array($sort_ctrl, $vlv_ctrl))) {
            $this->_debug("S: ".ldap_error($this->conn));
            $this->set_error(self::ERROR_SEARCH, 'vlvnotsupported');

            return false;
        }

        return true;
    }

}