File: functions.php

package info (click to toggle)
phpldapadmin 0.9.5-3sarge3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,052 kB
  • ctags: 2,526
  • sloc: php: 21,258; sh: 262; makefile: 132; xml: 42
file content (3656 lines) | stat: -rw-r--r-- 120,724 bytes parent folder | download
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
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
<?php
// $Header: /cvsroot/phpldapadmin/phpldapadmin/functions.php,v 1.222 2004/12/18 22:07:48 uugdave Exp $


/**
 * A collection of functions used throughout phpLDAPadmin.
 * @author The phpLDAPadmin development team
 * @package phpLDAPadmin
 *
 * @todo move functions that are only used by one script into said script (if any)
 */

/**
 * Determines if an attribute's value can contain multiple lines. Attributes that fall
 * in this multi-line category may be configured in config.php. Hence, this function
 * accesses the global variable $multi_line_attributes;
 *
 * Usage example:
 * <code>
 *  if( is_muli_line_attr( "postalAddress" ) )
 *      echo "<textarea name=\"postalAddress\"></textarea>";
 *  else 
 *      echo "<input name=\"postalAddress\" type=\"text\">";
 * </code>
 *
 * @param string $attr_name The name of the attribute of interestd (case insensivite)
 * @param string $val (optional) The current value of the attribute (speeds up the 
 *               process by searching for carriage returns already in the attribute value)
 * @param int $server_id (optional) The ID of the server of interest. If specified, 
 *               is_multi_line_attr() will read the schema from the server to determine if 
 *               the attr is multi-line capable. (note that schema reads can be expensive, 
 *               but that impact is lessened due to PLA's new caching mechanism)
 * @return bool
 */
function is_multi_line_attr( $attr_name, $val=null, $server_id=null )
{
    // First, check the optional val param for a \n or a \r
    if( null != $val && 
        ( false !== strpos( $val, "\n" ) || 
          false !== strpos( $val, "\r" ) ) )
        return true;

    // Next, compare strictly by name first
    global $multi_line_attributes;
    if( isset( $multi_line_attributes ) && is_array( $multi_line_attributes ) )
        foreach( $multi_line_attributes as $multi_line_attr_name )
            if( 0 == strcasecmp( $multi_line_attr_name, $attr_name ) )
                return true;

    // If unfound, compare by syntax OID
    if( null !== $server_id ) {
        global $multi_line_syntax_oids;
        if( isset( $multi_line_syntax_oids ) && is_array( $multi_line_syntax_oids ) ) {
            $schema_attr = get_schema_attribute( $server_id, $attr_name );
            if( ! $schema_attr )
                return false;
            $syntax_oid = $schema_attr->getSyntaxOID();
            if( ! $syntax_oid )
                return false;
            foreach( $multi_line_syntax_oids as $multi_line_syntax_oid )
                if( $multi_line_syntax_oid == $syntax_oid )
                    return true;
        }
    }

    return false;

}

/**
 * Fetches the user setting for $search_deref from config.php. The returned value
 * will be one of the four LDAP_DEREF_* constancts defined by the PHP LDAP API. If
 * the user has failed to configure this setting or configured an inappropriate
 * value, the constant DEFAULT_SEARCH_DEREF_SETTING is returned.
 *
 * @see DEFAULT_SEARCH_DEREF_SETTING
 * @see is_valid_deref_setting()
 * @return int
 */
function get_search_deref_setting()
{
    global $search_deref;
    if( ! isset( $search_deref ) || ! is_valid_deref_setting( $search_deref ) )
        return DEFAULT_SEARCH_DEREF_SETTING;
    else
        return $search_deref;
}

/**
 * Fetches the user setting for $tree_deref from config.php. The returned value
 * will be one of the four LDAP_DEREF_* constancts defined by the PHP LDAP API. If
 * the user has failed to configure this setting or configured an inappropriate
 * value, the constant DEFAULT_TREE_DEREF_SETTING is returned.
 *
 * @see DEFAULT_TREE_DEREF_SETTING
 * @see is_valid_deref_setting()
 * @return int
 */
function get_tree_deref_setting()
{
    global $tree_deref;
    if( ! isset( $tree_deref ) || ! is_valid_deref_setting( $tree_deref ) )
        return DEFAULT_TREE_DEREF_SETTING;
    else
        return $tree_deref;
}

/**
 * Fetches the user setting for $export_deref from config.php. The returned value
 * will be one of the four LDAP_DEREF_* constancts defined by the PHP LDAP API. If
 * the user has failed to configure this setting or configured an inappropriate
 * value, the constant DEFAULT_EXPORT_DEREF_SETTING is returned.
 *
 * @see DEFAULT_EXPORT_DEREF_SETTING
 * @see is_valid_deref_setting()
 * @return int
 */
function get_export_deref_setting()
{
    global $export_deref;
    if( ! isset( $export_deref ) || ! is_valid_deref_setting( $export_deref ) )
        return DEFAULT_EXPORT_DEREF_SETTING;
    else
        return $export_deref;
}

/**
 * Fetches the user setting for $view_deref from config.php. The returned value
 * will be one of the four LDAP_DEREF_* constancts defined by the PHP LDAP API. If
 * the user has failed to configure this setting or configured an inappropriate
 * value, the constant DEFAULT_VIEW_DEREF_SETTING is returned.
 *
 * @see DEFAULT_VIEW_DEREF_SETTING
 * @see is_valid_deref_setting()
 * @return int
 */
function get_view_deref_setting()
{
    global $view_deref;
    if( ! isset( $view_deref ) || ! is_valid_deref_setting( $view_deref ) )
        return DEFAULT_VIEW_DEREF_SETTING;
    else
        return $view_deref;
}

/** 
 * Checks the user-configured parameter for sanity. For the various *_deref settings, users
 * may only use one of LDAP_DEREF_NEVER, LDAP_DEREF_SEARCHING, LDAP_DEREF_FINDING, or
 * LDAP_DEREF_ALWAYS. This function can be used to conveniently enforce this.
 *
 * @param int $deref_setting The deref setting to validate.
 * @return bool
 */
function is_valid_deref_setting( $deref_setting )
{
    if( $deref_setting == LDAP_DEREF_NEVER ||
        $deref_setting == LDAP_DEREF_SEARCHING ||
        $deref_setting == LDAP_DEREF_FINDING ||
        $deref_setting == LDAP_DEREF_ALWAYS )
        return true;
    else
        return false;

}

/**
 * Fetch whether the user has configured a certain server as "low bandwidth". Users may
 * choose to configure a server as "low bandwidth" in config.php thus:
 * <code>
 *   $servers[$i]['low_bandwidth'] = true;
 * </code>
 * @param int $server_id The ID of the server of interest from config.php.
 * @return bool
 */
function is_server_low_bandwidth( $server_id )
{
    global $servers;
    if( isset( $servers[$server_id]['low_bandwidth'] ) && true == $servers[$server_id]['low_bandwidth'] )
        return true;
    else
        return false;
}

/**
 * Fetch whether the user has configured a certain server login to be non anonymous
 *
 * <code>
 *   $servers[$i]['disable_anon_bind'] = true;
 * </code>
 * @param int $server_id The ID of the server of interest from config.php.
 * @return bool 
 */
function is_anonymous_bind_allowed( $server_id )
{
	global $servers;
	
	return ( ! isset( $servers[$server_id]['disable_anon_bind'] )
		|| false == $servers[$server_id]['disable_anon_bind'] )
		? true
		: false;
}

/** 
 * Fetches whether TLS has been configured for use with a certain server.
 * Users may configure phpLDAPadmin to use TLS in config,php thus:
 * <code>
 *   $servers[$i]['tls'] = true;
 * </code>
 * @param int $server_id The ID of the server of interest from config.php.
 * @return bool
 */
function tls_enabled( $server_id )
{
    global $servers;
    if( isset( $servers[$server_id]['tls'] ) && true == $servers[$server_id]['tls'] )
        return true;
    else
        return false;
}

/**
 * Fetches whether phpLDAPadmin has been configured to redirect anonymously bound users
 * to a search form with no tree displayed.
 * This is configured in config.php thus:
 * <code>
 *  $anonymous_bind_redirect_no_tree = true;
 * </code>
 * @return bool
 */
function anon_bind_tree_disabled()
{
	global $anonymous_bind_redirect_no_tree;
	if( isset( $anonymous_bind_redirect_no_tree ) && true == $anonymous_bind_redirect_no_tree )
		return true;
	else
		return false;
}

/**
 * Fetches whether phpLDAPadmin has been configured to display configuration
 * management links (report bug, request feature, etc)
 * @return bool
 */
function hide_configuration_management()
{
    global $hide_configuration_management;
    if( isset( $hide_configuration_management ) &&
        $hide_configuration_management == true )
        return true;
    else
        return false;
}

/** 
 * Fetches whether the user has configured phpLDAPadmin to obfuscate passwords
 * with "*********" when displaying them. This is configured in config.php thus:
 * <code>
 *  $obfuscate_password_display = true;
 * </code>
 * @return bool
 */
function obfuscate_password_display()
{
	global $obfuscate_password_display;
	if( isset( $obfuscate_password_display ) && true == $obfuscate_password_display )
		return true;
	else
		return false;
}

/** 
 * Fetches whether the login_attr feature is enabled for a specified server. 
 * This is configured in config.php thus:
 * <code>
 *  $servers[$server_id]['login_attr'] = 'uid';
 * </code>
 * By virtue of the fact that the login_attr is not blank and not 'dn', the 
 * feature is configured to be enabled.
 *
 * @return bool
 */
function login_attr_enabled( $server_id )
{
	global $servers;
	if(	isset( $servers[$server_id]['login_attr'] ) && 
		0 != strcasecmp( $servers[$server_id]['login_attr'], "dn" ) && 
		trim( $servers[$server_id]['login_attr'] != "" ) )
		return true;
	else
		return false;
}

function login_string_enabled( $server_id )
{
	global $servers;
	if(	isset( $servers[$server_id]['login_attr'] ) && 
		0 == strcasecmp( $servers[$server_id]['login_attr'], "string" ) )
		return true;
	else
		return false;
}

function get_login_string( $server_id )
{
	global $servers;
	if(	isset( $servers[$server_id]['login_string'] ) )
		return $servers[$server_id]['login_string'];
	else
		return false;
}

/** 
 * Returns an HTML-beautified version of a DN.
 * Internally, this function makes use of pla_explode_dn() to break the 
 * the DN into its components. It then glues them back together with
 * "pretty" HTML. The returned HTML is NOT to be used as a real DN, but 
 * simply displayed.
 * 
 * @param string $dn The DN to pretty-print.
 * @return string
 */
function pretty_print_dn( $dn )
{
	$dn = pla_explode_dn( $dn );
	foreach( $dn as $i => $element ) {
		$element = htmlspecialchars( $element );
		$element = explode( '=', $element, 2 );
		$element = implode( '<span style="color: blue; font-family: courier; font-weight: bold">=</span>', $element );
		$dn[$i] = $element;
	}
	$dn = implode( '<span style="color:red; font-family:courier; font-weight: bold;">,</span>', $dn );

	return $dn;
}

/**
 * Returns true if the attribute specified is required to take as input a DN.
 * Some examples include 'distinguishedName', 'member' and 'uniqueMember'.
 * @param int $server_id The ID of the server of interest 
 *            (required since this operation demands a schema lookup)
 * @param string $attr_name The name of the attribute of interest (case insensitive)
 * @return bool
 */
function is_dn_attr( $server_id, $attr_name )
{
    // Simple test first
    $dn_attrs = array( "aliasedObjectName" );
    foreach( $dn_attrs as $dn_attr )
        if( 0 == strcasecmp( $attr_name, $dn_attr ) )
            return true;

    // Now look at the schema OID
	$attr_schema = get_schema_attribute( $server_id, $attr_name );
	if( ! $attr_schema )
		return false;
	$syntax_oid = $attr_schema->getSyntaxOID();
	if( '1.3.6.1.4.1.1466.115.121.1.12' == $syntax_oid )
		return true;
	if( '1.3.6.1.4.1.1466.115.121.1.34' == $syntax_oid )
		return true;
	$syntaxes = get_schema_syntaxes( $server_id );
	if( ! isset( $syntaxes[ $syntax_oid ] ) )
		return false;
	$syntax_desc = $syntaxes[ $syntax_oid ]->getDescription();
	if( false !== strpos( strtolower($syntax_desc), 'distinguished name' ) )
		return true;
	return false;
}

/**
 * Given a string, this function returns true if the string has the format
 * of a DN (ie, looks like "cn=Foo,dc=example,dc=com"). Returns false otherwise.
 * The purpose of this function is so that developers can examine a string and
 * know if it looks like a DN, and draw a hyperlink as needed.
 *
 * (See unit_test.php for test cases)
 *
 * @param string $attr The attribute to examine for "DNness"
 * @see unit_test.php
 * @return bool
 */
function is_dn_string( $str )
{
    // Try to break the string into its component parts if it can be done
    // ie, "uid=Manager" "dc=example" and "dc=com"
    $parts = pla_explode_dn( $str );
    if( ! is_array( $parts ) )
        return false;
    if( 0 == count( $parts ) )
        return false;

    // Foreach of the "parts", look for an "=" character,
    // and make sure neither the left nor the right is empty
    foreach( $parts as $part ) {
        if( false === strpos( $part, "=" ) )
            return false;
        $sub_parts = explode( "=", $part, 2 );
        $left = $sub_parts[0];
        $right = $sub_parts[1];
        if( 0 == strlen( trim( $left ) ) || 0 == strlen( trim( $right ) ) )
            return false;
        if( false !== strpos( $left, '#' ) )
            return false;
    }

    // We survived the above rigor. This is a bonified DN string.
    return true;
}

/** 
 * Get whether a string looks like an email address (user@example.com).
 * 
 * @param string $str The string to analyze.
 * @return bool Returns true if the specified string looks like 
 *   an email address or false otherwise.
 */
function is_mail_string( $str )
{
    $mail_regex = "/^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*$/";
    if( preg_match( $mail_regex, $str ) )
        return true;
    else
        return false;
}

/** 
 * Get whether a string looks like a web URL (http://www.example.com/)
 * 
 * @param string $str The string to analyze.
 * @return bool Returns true if the specified string looks like 
 *   a web URL or false otherwise.
 */
function is_url_string( $str )
{
    $url_regex = '/(ftp|https?):\/\/+[\w\.\-\/\?\=\&]*\w+/';
    if( preg_match( $url_regex, $str ) )
        return true;
    else
        return false;

}


/**
 * Utility wrapper for setting cookies, which takes into consideration
 * phpLDAPadmin configuration values. On success, true is returned. On 
 * failure, false is returned.
 *
 * @param string $name The name of the cookie to set.
 * @param string $val The value of the cookie to set.
 * @param int $expire (optional) The duration in seconds of this cookie. If unspecified, $cookie_time 
 *            is used from config.php
 * @param string $dir (optional) The directory value of this cookie (see php.net/setcookie)
 *
 * @see setcookie
 * @return bool
 */
function pla_set_cookie( $name, $val, $expire=null, $dir=null )
{
	if( $expire == null ) {
		global $cookie_time;
		if( ! isset( $cookie_time ) )
				$cookie_time = 0;
		$expire = $cookie_time == 0 ? null : time() + $cookie_time;
	}

	if( $dir == null ) {
		$dir = dirname( $_SERVER['PHP_SELF'] );
	}

	if( @setcookie( $name, $val, $expire, $dir ) ) {
		$_COOKIE[ $name ] = $val;
		return true;
	} else {
		return false;
	}
}

/**
 * Responsible for setting two cookies/session-vars to indicate that a user has logged in,
 * one for the logged in DN and one for the logged in password. Cookies  
 * are stored unencrypted in the client's browser's cookie cache. Use caution!
 *
 * This function is only used if 'auth_type' is set to 'cookie' or 'session'. The values
 * written have the name "pla_login_dn_X" and "pla_login_pass_X" where X is the 
 * ID of the server to which the user is attempting login.
 *
 * Note that as with all cookie/session operations this function must be called BEFORE 
 * any output is sent to the browser.
 *
 * On success, true is returned. On failure, false is returned.
 * 
 * @param int $server_id The ID of the server to which the user is logged in.
 * @param string $dn The DN with which the user has logged in. 
 * @param string $password The password of the user logged in.
 * @param bool $anon_bind Indicates that this is an anonymous bind such that
 *             a password of "0" is stored.
 * @return bool
 * @see unset_login_dn
 */
function set_login_dn( $server_id, $dn, $password, $anon_bind )
{
	global $servers;

	if( ! check_server_id( $server_id ) )
		return false;
	if( ! isset( $servers[ $server_id ][ 'auth_type' ] ) )
		return false;
	$auth_type = $servers[ $server_id ][ 'auth_type' ]; 

    switch( $auth_type ) 
    {
        case 'cookie':
            $cookie_dn_name = "pla_login_dn_$server_id";
            $cookie_pass_name = "pla_login_pass_$server_id";
            if( $anon_bind ) {
                // we set the cookie password to 0 for anonymous binds.
                $dn = 'anonymous';
                $password = '0';
            }
            $res1 = pla_set_cookie( $cookie_dn_name, pla_blowfish_encrypt( $dn ) );
            $res2 = pla_set_cookie( $cookie_pass_name, pla_blowfish_encrypt( $password ) );
            if( $res1 && $res2 )
                return true;
            else
                return false;
            break;
        case 'session':
            $sess_var_dn_name = "pla_login_dn_$server_id";
            $sess_var_pass_name = "pla_login_pass_$server_id";
            if( $anon_bind ) {
                $dn = 'anonymous';
                $password = '0';
            } 
            $_SESSION[ $sess_var_dn_name ] = $dn;
            $_SESSION[ $sess_var_pass_name ] = $password;
            return true;
            break;
        default:
            global $lang;
			pla_error( sprintf( $lang['unknown_auth_type'], htmlspecialchars( $auth_type ) ) );
            break;
    }
}

/**
 * Effectively logs a user out from a server. 
 * Removes the cookies/session-vars set by set_login_dn() 
 * after a user logs out using "auth_type" of "session" or "cookie".
 * Returns true on success, false on failure.
 *
 * @param int $server_id The ID of the server from which the user is logging out.
 * @return bool True on success, false on failure.
 * @see set_login_dn
 */
function unset_login_dn( $server_id )
{
	global $servers;

	if( ! check_server_id( $server_id ) )
		return false;
	if( ! isset( $servers[ $server_id ][ 'auth_type' ] ) )
		return false;
	$auth_type = $servers[ $server_id ][ 'auth_type' ]; 
    switch( $auth_type ) 
    {
        case 'cookie':
            $logged_in_dn = get_logged_in_dn( $server_id );
            if( ! $logged_in_dn )
                return false;
            $logged_in_pass = get_logged_in_pass( $server_id );
            $anon_bind = $logged_in_dn == 'anonymous' ? true : false;

            // set cookie with expire time already passed to erase cookie from client
            $expire = time()-3600;
            $cookie_dn_name = "pla_login_dn_$server_id";
            $cookie_pass_name = "pla_login_pass_$server_id";
            if( $anon_bind ) {
                $res1 = pla_set_cookie( $cookie_dn_name, 'anonymous', $expire );
                $res2 = pla_set_cookie( $cookie_pass_name, '0', $expire );
            } else {
                $res1 = pla_set_cookie( $cookie_dn_name, pla_blowfish_encrypt( $logged_in_dn ), $expire );
                $res2 = pla_set_cookie( $cookie_pass_name, pla_blowfish_encrypt( $logged_in_pass ), $expire );
            }

            if( ! $res1 || ! $res2 )
                return false;
            else
                return true;
            break;
       case 'session':
            // unset session variables
            $session_var_dn_name = "pla_login_dn_$server_id";
            $session_var_pass_name = "pla_login_pass_$server_id";
            if( array_key_exists( $session_var_dn_name, $_SESSION ) )
                unset( $_SESSION[ $session_var_dn_name ] );
            if( array_key_exists( $session_var_pass_name, $_SESSION ) )
                unset( $_SESSION[ "$session_var_pass_name" ] );
            session_write_close();
            return true;
            break;
      default:
            global $lang;
			pla_error( sprintf( $lang['unknown_auth_type'], htmlspecialchars( $auth_type ) ) );
            break;
    }
}


/**
 * Get a customized file for a server
 * We don't need any caching, because it's done by PHP
 *
 * @param int $server_id The ID of the server
 * @param string $filename The requested filename
 *
 * @return string The customized filename, if exists, or the standard one
 */
function get_custom_file( $server_id, $filename )
{
	global $servers;

	if( ! check_server_id( $server_id ) )
		return $filename;
	
	if( isset( $servers[ $server_id ]['custom_pages_prefix'] ) ) {
		$custom = $servers[ $server_id ][ 'custom_pages_prefix' ];
		if( is_file( realpath( $custom . $filename ) ) )
			return ( $custom . $filename );
	}

	return $filename;
}

/**
 * Call a customized function
 *
 * @param int $server_id The ID of the server
 * @param string $filename The requested function
 *
 * @return any The result of the called function
 */
function call_custom_function( $server_id, $function )
{
	global $servers;

	if( ! check_server_id( $server_id ) )
		return $function;

	if( isset( $servers[$server_id]['custom_pages_prefix'] ) ) {
		$custom = $servers[$server_id]['custom_pages_prefix'];
		if( function_exists( $custom . $function ) )
			return call_user_func ( $custom . $function );
	}
	return call_user_func( $function );
}

/**
 * Compares 2 DNs. If they are equivelant, returns 0, otherwise,
 * returns their sorting order (similar to strcmp()):
 *      Returns < 0 if dn1 is less than dn2.
 *      Returns > 0 if dn1 is greater than dn2.
 *
 * The comparison is performed starting with the top-most element 
 * of the DN. Thus, the following list:
 *    <code>
 *       ou=people,dc=example,dc=com
 *       cn=Admin,ou=People,dc=example,dc=com
 *       cn=Joe,ou=people,dc=example,dc=com
 *       dc=example,dc=com
 *       cn=Fred,ou=people,dc=example,dc=org
 *       cn=Dave,ou=people,dc=example,dc=org
 *    </code>
 * Will be sorted thus using usort( $list, "pla_compare_dns" ):
 *    <code>
 *       dc=com
 *       dc=example,dc=com
 *       ou=people,dc=example,dc=com
 *       cn=Admin,ou=People,dc=example,dc=com
 *       cn=Joe,ou=people,dc=example,dc=com
 *       cn=Dave,ou=people,dc=example,dc=org
 *       cn=Fred,ou=people,dc=example,dc=org
 *    </code>
 *
 * @param string $dn1 The first of two DNs to compare
 * @param string $dn2 The second of two DNs to compare
 * @return int
 */
function pla_compare_dns( $dn1, $dn2 )
{
	// If they are obviously the same, return immediately
	if( 0 === strcasecmp( $dn1, $dn2 ) )
		return 0;
	
	$dn1_parts = pla_explode_dn( pla_reverse_dn($dn1) );
	$dn2_parts = pla_explode_dn( pla_reverse_dn($dn2) );
	assert( is_array( $dn1_parts ) );
	assert( is_array( $dn2_parts ) );
	
	// Foreach of the "parts" of the smaller DN
	for( $i=0; $i<count( $dn1_parts ) && $i<count( $dn2_parts ); $i++ )
	{
		// dnX_part is of the form: "cn=joe" or "cn = joe" or "dc=example"
		// ie, one part of a multi-part DN.
		$dn1_part = $dn1_parts[$i];
		$dn2_part = $dn2_parts[$i];
		
		// Each "part" consists of two sub-parts:
		//   1. the attribute (ie, "cn" or "o")
		//   2. the value (ie, "joe" or "example")
		$dn1_sub_parts = explode( '=', $dn1_part, 2 );
		$dn2_sub_parts = explode( '=', $dn2_part, 2 );

		$dn1_sub_part_attr = trim( $dn1_sub_parts[0] );
		$dn2_sub_part_attr = trim( $dn2_sub_parts[0] );
		if( 0 != ( $cmp = strcasecmp( $dn1_sub_part_attr, $dn2_sub_part_attr ) ) )
			return $cmp;

		$dn1_sub_part_val = trim( $dn1_sub_parts[1] );
		$dn2_sub_part_val = trim( $dn2_sub_parts[1] );
		if( 0 != ( $cmp = strcasecmp( $dn1_sub_part_val, $dn2_sub_part_val ) ) )
			return $cmp;
	}

    // If we iterated through all entries in the smaller of the two DNs
    // (ie, the one with fewer parts), and the entries are different sized,
    // then, the smaller of the two must be "less than" than the larger.
    if( count($dn1_parts) > count($dn2_parts) ) {
        return 1;
    } elseif( count( $dn2_parts ) > count( $dn1_parts ) ) {
        return -1;
    } else {
        return 0;
    }
}

/** 
 * Prunes off anything after the ";" in an attr name. This is useful for
 * attributes that may have ";binary" appended to their names. With 
 * real_attr_name(), you can more easily fetch these attributes' schema
 * with their "real" attribute name.
 *
 * @param string $attr_name The name of the attribute to examine.
 * @return string
 */
function real_attr_name( $attr_name )
{
	$attr_name = preg_replace( "/;.*$/U", "", $attr_name );
	return $attr_name;
}

/**
 * Returns true if the user has configured the specified
 * server to enable mass deletion. Mass deletion is enabled in config.php this:
 * <code>
 *   $enable_mass_delete = true;
 * </code>
 * Notice that mass deletes are not enabled on a per-server basis, but this
 * function checks that the sever is not in a read-only state as well.
 *
 * @param int $server_id The ID of the server of interest.
 * @return bool
 */
function mass_delete_enabled( $server_id )
{
	global $enable_mass_delete;

	if( check_server_id( $server_id ) && 
		! pla_ldap_connection_is_error( pla_ldap_connect( $server_id ), false ) &&
		have_auth_info( $server_id ) && 
		! is_server_read_only( $server_id ) && 
		isset( $enable_mass_delete ) && 
		true === $enable_mass_delete )
		return true;
	else
		return false;
}

/**
 * Returns true if the user has configured PLA to show
 * helpful hints with the $show_hints setting.
 * This is configured in config.php thus:
 * <code>
 *  $show_hints = true;
 * </code>
 *
 * @return bool
 */
function show_hints()
{
	global $show_hints;
	if( isset( $show_hints ) && $show_hints === true )
		return true;
}

/**
 * Determines if the user has enabled auto uidNumbers for the specified server ID.
 *
 * @param int $server_id The id of the server of interest.
 * @return bool True if auto uidNumbers are enabled, false otherwise.
 */
function auto_uid_numbers_enabled( $server_id ) 
{
    global $servers;
    if( isset( $servers[$server_id]['enable_auto_uid_numbers'] ) &&
        true == $servers[$server_id]['enable_auto_uid_numbers'] )
        return true;
    else
        return false;
}

/**
 * For hosts who have 'enable_auto_uid_numbers' set to true, this function will
 * get the next available uidNumber using the host's preferred mechanism
 * (uidpool or search). The uidpool mechanism uses a user-configured entry in
 * the LDAP server to store the last used uidNumber. This mechanism simply fetches
 * and increments and returns that value. The search mechanism is more complicated
 * and slow. It searches all entries that have uidNumber set, finds the smalles and
 * "fills in the gaps" by incrementing the smallest uidNumber until an unused value
 * is found. Both mechanisms do NOT prevent race conditions or toe-stomping, so
 * care must be taken when actually creating the entry to check that the uidNumber
 * returned here has not been used in the mean time. Note that the two different
 * mechanisms may (will!) return different values as they use different algorithms
 * to arrive at their result. Do not be alarmed if (when!) this is the case.
 * 
 * Also note that both algorithms are susceptible to a race condition. If two admins
 * are adding users simultaneously, the users may get identical uidNumbers with this
 * function.
 *
 * See config.php.example for more notes on the two auto uidNumber mechanisms.
 *
 * @param int $server_id The ID of the server of interest.
 * @return int
 *
 * @todo eliminate race condition at create time by re-running this function.
 */
function get_next_uid_number( $server_id )
{
	global $servers, $lang;
	// Some error checking
	if( ! check_server_id( $server_id ) )
		return false;
    if( ! auto_uid_numbers_enabled( $server_id ) )
        return false;
	$server_name = isset( $servers[ $server_id ]['name'] ) ?
		$servers[$server_id]['name'] :
		"Server $server_id";
	if( ! isset( $servers[ $server_id ]['enable_auto_uid_numbers'] ) )
		return false;
	if( ! isset( $servers[ $server_id ]['auto_uid_number_mechanism'] ) )
		pla_error( sprintf($lang['auto_update_not_setup'], $server_name));

	// Based on the configured mechanism, go get the next available uidNumber!
	$mechanism = $servers[$server_id]['auto_uid_number_mechanism'];

	//
	// case 1: uidpool mechanism
	//
	if( 0 == strcasecmp( $mechanism, 'uidpool' ) ) {
		if( ! isset( $servers[ $server_id ][ 'auto_uid_number_uid_pool_dn' ] ) )
			pla_error( sprintf( $lang['uidpool_not_set'], $server_name ) );
		$uid_pool_dn = $servers[ $server_id ][ 'auto_uid_number_uid_pool_dn' ];
		if( ! dn_exists( $server_id, $uid_pool_dn ) )
			pla_error( sprintf( $lang['uidpool_not_exist'] , $uid_pool_dn ) );

		$next_uid_number = get_object_attr( $server_id, $uid_pool_dn, 'uidNumber' );
		$next_uid_number = intval( $next_uid_number[ 0 ] );
		$next_uid_number++;

		return $next_uid_number;

	//
	// case 2: search mechanism
	//
	} elseif( 0 == strcasecmp( $mechanism, 'search' ) ) {
		if( ! isset( $servers[ $server_id ][ 'auto_uid_number_search_base' ] ) )
			pla_error( sprintf( $lang['specified_uidpool'] , $server_name ) );

		$base_dn = $servers[ $server_id ][ 'auto_uid_number_search_base' ];
		$filter = "(uidNumber=*)";

		// Check see and use our alternate uid_dn and password if we have it.
		if ( isset( $servers[ $server_id ][ 'auto_uid_number_search_dn' ] ) &&
			isset( $servers[ $server_id ][ 'auto_uid_number_search_dn_pass' ] ) ) {
			$con = @ldap_connect( $servers[$server_id]['host'], $servers[$server_id]['port'] );
            @ldap_set_option( $con, LDAP_OPT_PROTOCOL_VERSION, 3 );
            @ldap_set_option( $con, LDAP_OPT_REFERRALS, 0);

			// Bind with the alternate ID.
			$res = @ldap_bind( $con,
				$servers[ $server_id ][ 'auto_uid_number_search_dn' ],
				$servers[ $server_id ][ 'auto_uid_number_search_dn_pass' ] );
			if (! $res) pla_error( sprintf( $lang['auto_uid_invalid_credential'] , $server_name ) );
			$search = @ldap_search( $con, $base_dn, $filter, array('uidNumber'), 0, 0, 0, get_search_deref_setting() );
            if( ! $search ) pla_error( sprintf( $lang['bad_auto_uid_search_base'], $server_name ) );
			$search = @ldap_get_entries( $con, $search );
			$res = @ldap_unbind( $con );

			$results = array();
			for( $i=0; $i<$search['count']; $i++ ) {
				$entry = $search[$i];
				$dn['dn'] = $entry['dn'];
				$dn['uidnumber'] = $entry['uidnumber'][0];
				$results[] = $dn;
			}

		} else {
			$results = pla_ldap_search( $server_id, $filter, $base_dn, array('uidNumber'));
		}
		// lower-case all the inices so we can access them by name correctly
		foreach( $results as $dn => $attrs )
			foreach( $attrs as $attr => $vals ) {
				unset( $results[$dn][$attr] );
				$results[$dn][strtolower( $attr )] = $vals;
			}

		// construct a list of used uidNumbers
		$uids = array();
		foreach ($results as $result)
			$uids[] = $result['uidnumber'];
		$uids = array_unique( $uids );
		if( count( $uids ) == 0 )
			return false;
		sort( $uids );
		foreach( $uids as $uid )
			$uid_hash[ $uid ] = 1;
		// start with the least existing uidNumber and add 1
		if (isset($servers[$server_id]['auto_uid_number_min'])) {
			$uidNumber = $servers[$server_id]['auto_uid_number_min'];
		} else {
			$uidNumber = intval( $uids[0] ) + 1;
		}
		// this loop terminates as soon as we encounter the next available uidNumber
		while( isset( $uid_hash[ $uidNumber ] ) )
			$uidNumber++;
		return $uidNumber;
	//
	// No other cases allowed. The user has an error in the configuration
	//
	} else {
		pla_error( sprintf( $lang['auto_uid_invalid_value'] , $mechanism) );
	}
}

/**
 * Used to determine if the specified attribute is indeed a jpegPhoto. If the
 * specified attribute is one that houses jpeg data, true is returned. Otherwise
 * this function returns false.
 *
 * @param int $server_id The ID of the server hosuing the attribute of interest
 * @param string $attr_name The name of the attribute to test.
 * @return bool
 * @see draw_jpeg_photos
 */
function is_jpeg_photo( $server_id, $attr_name )
{
	// easy quick check
	if( 0 == strcasecmp( $attr_name, 'jpegPhoto' ) ||
	    0 == strcasecmp( $attr_name, 'photo' ) )
	    return true;

	// go to the schema and get the Syntax OID
	require_once realpath( 'schema_functions.php' );
	$schema_attr = get_schema_attribute( $server_id, $attr_name );
	if( ! $schema_attr )
		return false;

	$oid = $schema_attr->getSyntaxOID();
	$type = $schema_attr->getType();

	if( 0 == strcasecmp( $type, 'JPEG' ) )
		return true;
	if( $oid == '1.3.6.1.4.1.1466.115.121.1.28' )
		return true;

	return false;
}

/**
 * Given an attribute name and server ID number, this function returns
 * whether the attrbiute contains boolean data. This is useful for 
 * developers who wish to display the contents of a boolean attribute
 * with a drop-down.
 * 
 * @param int $server_id The ID of the server of interest (required since 
 *            this action requires a schema lookup on the server)
 * @param string $attr_name The name of the attribute to test.
 * @return bool
 */
function is_attr_boolean( $server_id, $attr_name )
{
    $type = ( $schema_attr = get_schema_attribute( $server_id, $attr_name ) ) ? 
        $schema_attr->getType() : 
        null;
    if( 0 == strcasecmp( 'boolean', $type ) ||
        0 == strcasecmp( 'isCriticalSystemObject', $attr_name ) ||
        0 == strcasecmp( 'showInAdvancedViewOnly', $attr_name ) )
        return true;
    else
        return false;
}

/**
 * Given an attribute name and server ID number, this function returns
 * whether the attrbiute may contain binary data. This is useful for 
 * developers who wish to display the contents of an arbitrary attribute
 * but don't want to dump binary data on the page.
 * 
 * @param int $server_id The ID of the server of interest (required since 
 *            this action requires a schema lookup on the server)
 * @param string $attr_name The name of the attribute to test.
 * @return bool
 *
 * @see is_jpeg_photo
 */
function is_attr_binary( $server_id, $attr_name )
{
    $attr_name = strtolower( $attr_name );
    /** Determining if an attribute is binary can be an expensive
       operation. We cache the results for each attr name on each
       server in the $attr_cache to speed up subsequent calls. 
       The $attr_cache looks like this:
       Array 
        0 => Array 
              'objectclass' => false
              'cn' => false
              'usercertificate' => true
        1 => Array 
              'jpegphoto' => true 
              'cn' => false
    */

    static $attr_cache;
    if( isset( $attr_cache[ $server_id ][ $attr_name ] ) )
        return $attr_cache[ $server_id ][ $attr_name ];

    if( $attr_name == 'userpassword' ) {
        $attr_cache[ $server_id ][ $attr_name ] = false;
        return false;
    }

    // Quick check: If the attr name ends in ";binary", then it's binary.
	if( 0 == strcasecmp( substr( $attr_name, strlen( $attr_name ) - 7 ), ";binary" ) ) {
        $attr_cache[ $server_id ][ $attr_name ] = true;
		return true;
    }

    // See what the server schema says about this attribute
	$schema_attr = get_schema_attribute( $server_id, $attr_name );
	if( ! $schema_attr ) {
        // Strangely, some attributeTypes may not show up in the server
        // schema. This behavior has been observed in MS Active Directory.
        $type = null;
        $syntax = null;
    } else {
        $type = $schema_attr->getType();
        $syntax = $schema_attr->getSyntaxOID();
    }

	if(	0 == strcasecmp( $type, 'Certificate' ) ||
		0 == strcasecmp( $type, 'Binary' ) ||
		0 == strcasecmp( $attr_name, 'usercertificate' ) ||
		0 == strcasecmp( $attr_name, 'usersmimecertificate' ) ||
		0 == strcasecmp( $attr_name, 'networkaddress' ) ||
		0 == strcasecmp( $attr_name, 'objectGUID' ) ||
		0 == strcasecmp( $attr_name, 'objectSID' ) ||
		$syntax == '1.3.6.1.4.1.1466.115.121.1.10' ||
		$syntax == '1.3.6.1.4.1.1466.115.121.1.28' ||
		$syntax == '1.3.6.1.4.1.1466.115.121.1.5' ||
		$syntax == '1.3.6.1.4.1.1466.115.121.1.8' ||
		$syntax == '1.3.6.1.4.1.1466.115.121.1.9' ) {
            $attr_cache[ $server_id ][ $attr_name ] = true;
			return true;
    } else {
            $attr_cache[ $server_id ][ $attr_name ] = false;
			return false;
    }
}

/**
 * Returns true if the specified attribute is configured as read only
 * in config.php with the $read_only_attrs array. 
 * Attributes are configured as read-only in config.php thus:
 * <code>
 *  $read_only_attrs = array( "objectClass", "givenName" );
 * </code>
 *
 * @param string $attr The name of the attribute to test.
 * @return bool
 */
function is_attr_read_only( $server_id, $attr )
{
	global $read_only_attrs, $read_only_except_dn;

	$attr = trim( $attr );
	if( '' ===  $attr )
		return false;
	if( ! isset( $read_only_attrs ) ) 
		return false;
	if( ! is_array( $read_only_attrs) )
		return false;

	// Is the user excluded?
	if (isset($read_only_except_dn) && userIsMember($server_id, get_logged_in_dn( $server_id ),$read_only_except_dn))
		return false;

	foreach( $read_only_attrs as $attr_name )
		if( 0 == strcasecmp( $attr, trim($attr_name) ) )
			return true;
	return false;
}

/**
 * Returns true if the specified attribute is configured as hidden
 * in config.php with the $hidden_attrs array or the $hidden_attrs_ro
 * array.
 * Attributes are configured as hidden in config.php thus:
 * <code>
 *  $hidden_attrs = array( "objectClass", "givenName" );
 * </code>
 * or
 * <code>
 *  $hidden_attrs_ro = array( "objectClass", "givenName", "shadowWarning",
 *                     "shadowLastChange", "shadowMax", "shadowFlag",
 *                     "shadowInactive", "shadowMin", "shadowExpire" );
 * </code>
 *
 * @param string $attr The name of the attribute to test.
 * @return bool
 */
function is_attr_hidden( $server_id, $attr )
{
    global $hidden_attrs, $hidden_attrs_ro, $hidden_except_dn;

	$attr = trim( $attr );
	if( '' ===  $attr )
		return false;
	if( ! isset( $hidden_attrs ) ) 
		return false;
	if( ! is_array( $hidden_attrs) )
		return false;
    if( ! isset( $hidden_attrs_ro ) )
        $hidden_attrs_ro = $hidden_attrs;
    if( ! is_array( $hidden_attrs_ro) )
        $hidden_attrs_ro = $hidden_attrs;

	// Is the user excluded?
	if (isset($hidden_except_dn) && userIsMember($server_id, get_logged_in_dn( $server_id ),$hidden_except_dn))
		return false;

     if( is_server_read_only( $server_id ) ) {
             foreach( $hidden_attrs_ro as $attr_name )
                     if( 0 == strcasecmp( $attr, trim($attr_name) ) )
                             return true;
     } else {
             foreach( $hidden_attrs as $attr_name )
                     if( 0 == strcasecmp( $attr, trim($attr_name) ) )
                             return true;
    }
	return false;
}

/**
 * Returns true if the specified server is configured to be displayed
 * in read only mode. If a user has logged in via anonymous bind, and
 * config.php specifies anonymous_bind_implies_read_only as true, then
 * this also returns true. Servers can be configured read-only in
 * config.php thus:
 * <code>
 *  $server[$i]['read_only'] = true;
 * </code>
 *
 * @param int $server_id The ID of the server of interest from the $servers array in config.php
 * @return bool
 */
function is_server_read_only( $server_id )
{
	global $servers;
	if( isset( $servers[$server_id]['read_only'] ) &&
	    $servers[$server_id]['read_only'] == true )
		return true;

	global $anonymous_bind_implies_read_only;

	if( "anonymous" == get_logged_in_dn( $server_id ) &&
	    isset( $anonymous_bind_implies_read_only ) &&
	    $anonymous_bind_implies_read_only == true )
		return true;

	return false;
}

/**
 * Given a DN and server ID, this function reads the DN's objectClasses and
 * determines which icon best represents the entry. The results of this query
 * are cached in a session variable so it is not run every time the tree
 * browser changes, just when exposing new DNs that were not displayed
 * previously. That means we can afford a little bit of inefficiency here
 * in favor of coolness. :)
 *
 * This function returns a string like "country.png". All icon files are assumed
 * to be contained in the /images/ directory of phpLDAPadmin.
 *
 * Developers are encouraged to add new icons to the images directory and modify
 * this function as needed to suit their types of LDAP entries. If the modifications
 * are general to an LDAP audience, the phpLDAPadmin team will gladly accept them
 * as a patch.
 * 
 * @param int $server_id The ID of the LDAP server housing the DN of interest.
 * @param string $dn The DN of the entry whose icon you wish to fetch.
 *
 * @return string
 */
function get_icon( $server_id, $dn )
{
	// fetch and lowercase all the objectClasses in an array
	$object_classes = get_object_attr( $server_id, $dn, 'objectClass', true );

	if( $object_classes === null || $object_classes === false || ! is_array( $object_classes ) )
		$object_classes = array();

	foreach( $object_classes as $i => $class )
		$object_classes[$i] = strtolower( $class );

	$rdn = get_rdn( $dn );
    $rdn_parts = explode( '=', $rdn, 2 );
    $rdn_value = isset( $rdn_parts[0] ) ? $rdn_parts[0] : null;
    $rdn_attr = isset( $rdn_parts[1] ) ? $rdn_parts[1] : null;
    unset( $rdn_parts );

	// return icon filename based upon objectClass value
	if( in_array( 'sambaaccount', $object_classes ) &&
		'$' == $rdn{ strlen($rdn) - 1 } )
		return 'nt_machine.png';
	if( in_array( 'sambaaccount', $object_classes ) )
		return 'nt_user.png';
	elseif( in_array( 'person', $object_classes ) ||
	    in_array( 'organizationalperson', $object_classes ) ||
	    in_array( 'inetorgperson', $object_classes ) ||
	    in_array( 'account', $object_classes ) ||
   	    in_array( 'posixaccount', $object_classes )  )
		return 'user.png';
	elseif( in_array( 'organization', $object_classes ) )
		return 'o.png';
	elseif( in_array( 'organizationalunit', $object_classes ) )
		return 'ou.png';
	elseif( in_array( 'organizationalrole', $object_classes ) )
		return 'uid.png';
	elseif( in_array( 'dcobject', $object_classes ) ||
		in_array( 'domainrelatedobject', $object_classes ) ||
		in_array( 'domain', $object_classes ) ||
        in_array( 'builtindomain', $object_classes )) 
		return 'dc.png';
    elseif( in_array( 'alias', $object_classes ) )
        return 'go.png';
    elseif( in_array( 'room', $object_classes ) )
        return 'door.png';
    elseif( in_array( 'device', $object_classes ) )
        return 'device.png';
    elseif( in_array( 'document', $object_classes ) )
        return 'document.png';
	elseif( in_array( 'country', $object_classes ) ) {
        $tmp = pla_explode_dn( $dn );
        $cval = explode( '=', $tmp[0], 2 );
        $cval = isset( $cval[1] ) ? $cval[1] : false;
        if( $cval && false === strpos( $cval, ".." ) && 
            file_exists( realpath( "./images/countries/$cval.png" ) ) )
            return "countries/$cval.png";
        else
            return 'country.png';
    }
	elseif( in_array( 'jammvirtualdomain', $object_classes ) )
		return 'mail.png';
	elseif( in_array( 'locality', $object_classes ) )
		return 'locality.png';
	elseif( in_array( 'posixgroup', $object_classes ) ||
		in_array( 'groupofnames', $object_classes ) ||
		in_array( 'group', $object_classes ) )
		return 'ou.png';
	elseif( in_array( 'applicationprocess', $object_classes ) )
		return 'process.png';
	elseif( in_array( 'groupofuniquenames', $object_classes ) )
		return 'uniquegroup.png';
	elseif( in_array( 'iphost', $object_classes ) )
		return 'host.png';
	elseif( in_array( 'nlsproductcontainer', $object_classes ) )
        return 'n.png';
	elseif( in_array( 'ndspkikeymaterial', $object_classes ) )
        return 'lock.png';
	elseif( in_array( 'server', $object_classes ) )
        return 'server-small.png';
	elseif( in_array( 'volume', $object_classes ) )
        return 'hard-drive.png';
	elseif( in_array( 'ndscatcatalog', $object_classes ) )
        return 'catalog.png';
	elseif( in_array( 'resource', $object_classes ) )
        return 'n.png';
	elseif( in_array( 'ldapgroup', $object_classes ) )
        return 'ldap-server.png';
	elseif( in_array( 'ldapserver', $object_classes ) )
        return 'ldap-server.png';
	elseif( in_array( 'nisserver', $object_classes ) )
        return 'ldap-server.png';
	elseif( in_array( 'rbscollection', $object_classes ) )
        return 'ou.png';
	elseif( in_array( 'dfsconfiguration', $object_classes ) )
        return 'nt_machine.png';
	elseif( in_array( 'applicationsettings', $object_classes ) )
        return 'server-settings.png';
	elseif( in_array( 'aspenalias', $object_classes ) )
        return 'mail.png';
	elseif( in_array( 'container', $object_classes ) )
        return 'folder.png';
	elseif( in_array( 'ipnetwork', $object_classes ) )
        return 'network.png';
	elseif( in_array( 'samserver', $object_classes ) )
        return 'server-small.png';
	elseif( in_array( 'lostandfound', $object_classes ) )
        return 'find.png';
	elseif( in_array( 'infrastructureupdate', $object_classes ) )
        return 'server-small.png';
	elseif( in_array( 'filelinktracking', $object_classes ) )
        return 'files.png';
	elseif( in_array( 'automountmap', $object_classes ) ||
            in_array( 'automount', $object_classes ) )
        return 'hard-drive.png';
    elseif( 0 === strpos( $rdn_value, "ipsec" ) || 
            0 == strcasecmp( $rdn_value, "IP Security" ) ||
            0 == strcasecmp( $rdn_value, "MSRADIUSPRIVKEY Secret" ) ||
            0 === strpos( $rdn_value, "BCKUPKEY_" ) )
        return 'lock.png';
	elseif( 0 == strcasecmp( $rdn_value, "MicrosoftDNS" ) )
        return 'dc.png';
	// Oh well, I don't know what it is. Use a generic icon.
	else
		return 'object.png';
}

/**
 * Does the same thing as get_icon(), but it tries to fetch the icon name from the
 * tree_icons session variable first. If not found, resorts to get_icon() and stores
 * the icon nmae in the tree_icons session before returing the icon.
 *
 * @param int $server_id The ID of the server housing the DN of interest.
 * @param string $dn The DN of the entry of interest.
 *
 * @return string
 *
 * @see get_icon
 */
function get_icon_use_cache( $server_id, $dn )
{
    initialize_session_tree();
	if( array_key_exists( 'tree_icons', $_SESSION ) ) {
		if( array_key_exists( $server_id, $_SESSION['tree_icons'] ) &&
			array_key_exists( $dn, $_SESSION['tree_icons'][$server_id] ) )
		{
			return $_SESSION['tree_icons'][ $server_id ][ $dn ];
		} else {
			$icon = get_icon( $server_id, $dn );
			$_SESSION['tree_icons'][ $server_id ][ $dn ] = $icon;
			return $icon;
		}
	}
}

/**
 * Given a server_id, returns whether or not we have enough information
 * to authenticate against the server. For example, if the user specifies
 * auth_type of 'cookie' in the config for that server, it checks the $_COOKIE array to
 * see if the cookie username and password is set for the server. If the auth_type
 * is 'session', the $_SESSION array is checked.
 *
 * There are three cases for this function depending on the auth_type configured for
 * the specified server. If the auth_type is form or http, then get_logged_in_dn() is 
 * called to verify that the user has logged in. If the auth_type is config, then the
 * $servers array in config.php is checked to ensure that the user has specified
 * login information. In any case, if phpLDAPadmin has enough information to login
 * to the server, true is returned. Otherwise false is returned.
 *
 * @param int $server_id
 * @return bool
 * @see get_logged_in_dn
 */
function have_auth_info( $server_id )
{
	global $servers;

	if( ! check_server_id( $server_id ) )
		return false;

	$server = $servers[$server_id];

	// For session or cookie auth_types, we check the session or cookie to see if a user has logged in.
	if( isset( $server['auth_type'] ) && ( in_array( $server['auth_type'], array( 'session', 'cookie' ) ) ) ) {
		// we don't look at get_logged_in_pass() cause it may be null for anonymous binds
		// get_logged_in_dn() will never return null if someone is really logged in.
		if( get_logged_in_dn( $server_id ) )
			return true;
		else
			return false;
	}
	// whether or not the login_dn or pass is specified, we return
	// true here. (if they are blank, we do an anonymous bind anyway)
	elseif( ! isset( $server['auth_type'] ) || $server['auth_type'] == 'config' ) {
		return true;
	}
	else {
		global $lang;
		pla_error( sprintf( $lang['error_auth_type_config'], 
			htmlspecialchars( $server[ 'auth_type' ] ) ) );
	}
}

/**
 * Fetches the password of the currently logged in user (for auth_types "form" and "http" only)
 * or false if the current login is anonymous.
 *
 * @param int $server_id The ID of the server of interest.
 *
 * @return string
 *
 * @see have_auth_info
 * @see get_logged_in_dn
 */
function get_logged_in_pass( $server_id )
{
	global $servers;
	if( ! is_numeric( $server_id ) )
		return false;
	if( ! isset( $servers[ $server_id ][ 'auth_type' ] ) )
		return false;
	$auth_type = $servers[ $server_id ][ 'auth_type' ];
	switch( $auth_type ) {
		case 'cookie':
			$cookie_name = 'pla_login_pass_' . $server_id;
			$pass = isset( $_COOKIE[ $cookie_name ] ) ? $_COOKIE[ $cookie_name ] : false;
			if( $pass == '0' )
				return null;
			else
				return pla_blowfish_decrypt( $pass );
			break;
        case 'session':
			$session_var_name = 'pla_login_pass_' . $server_id;
			$pass = isset( $_SESSION[ $session_var_name ] ) ? $_SESSION[ $session_var_name ] : false;
			if( $pass == '0' )
				return null;
			else
				return $pass;
			break;
		case 'config':
			if( isset( $servers[ $server_id ][ 'login_pass' ] ) )
				return ( $servers[ $server_id ][ 'login_pass' ] );
			return false;
			break;
		default:
            global $lang;
			pla_error( sprintf( $lang['unknown_auth_type'], htmlspecialchars( $auth_type ) ) );
	}
}

/**
 * Returns the DN who is logged in currently to the given server, which may 
 * either be a DN or the string 'anonymous'. This applies only for auth_types
 * "form" and "http". 
 *
 * One place where this function is used is the tree viewer:
 * After a user logs in, the text "Logged in as: " is displayed under the server
 * name. This information is retrieved from this function.
 *
 * @param int $server_id The ID of the server of interest.
 *
 * @return string
 *
 * @see have_auth_info
 * @see get_logged_in_pass
 */
function get_logged_in_dn( $server_id )
{
	global $servers;
	if( ! is_numeric( $server_id ) )
		return false;
	if( ! isset( $servers[ $server_id ][ 'auth_type' ] ) )
		return false;
	$auth_type = $servers[ $server_id ][ 'auth_type' ];
	switch( $auth_type ) {
		case 'cookie':
			$cookie_name = 'pla_login_dn_' . $server_id;
			if( isset( $_COOKIE[ $cookie_name ] ) ) {
				$dn = $_COOKIE[ $cookie_name ];
			} else {
				return false;
			}
			return pla_blowfish_decrypt( $dn );
			break;
		case 'session':
			$session_var_name = 'pla_login_dn_' . $server_id;
			if( isset( $_SESSION[ $session_var_name ] ) ) {
				$dn = $_SESSION[ $session_var_name ];
                return $dn;
			} else {
				return false;
			}
			break;
		case 'config':
			if( isset( $servers[ $server_id ][ 'login_dn' ] ) )
				return ( $servers[ $server_id ][ 'login_dn' ] );
			return false;
			break;
		default:
            global $lang;
			pla_error( sprintf( $lang['unknown_auth_type'], htmlspecialchars( $auth_type ) ) );
	}
}

/**
 * Appends a servers base to a "sub" dn or returns the base.
 * If $get_base is true, return at least the base, otherwise null.
 */
function expand_dn_with_base( $server_id, $sub_dn, $conn = null, $get_base = true )
{
	global $servers;

	if( ! check_server_id( $server_id ) )
		return false;

	$empty_str = ( is_null($sub_dn) || ( ( $len = strlen( trim( $sub_dn ) ) ) == 0 ) );

	if ( $empty_str ) {
		// If we have no string and want not base
		if ( ! $get_base )
			return null;
	} elseif ( $sub_dn[$len - 1] != ',' )
        // If we have a string which doesn't need a base
		return $sub_dn;

	if( ( $empty_str && $get_base ) || ! $empty_str )
	{
		if( isset($servers[$server_id]['base']) ) {
			$base = $servers[$server_id]['base'];
			if ( strlen( trim( $base ) ) == 0 )
				$base = try_to_get_root_dn( $server_id, $conn );
		} else { 
            $base = try_to_get_root_dn( $server_id, $conn );
        }

		if ( $base )
			return ( ! $empty_str ) ? $sub_dn . $base : $base;
	}
	return null;
}

/**
 * Logs into the specified server using the auth_type configured for that server using
 * ldap_connect() and ldap_bind() from the PHP LDAP API.
 * If anonymous is true bind information (user / pass) is ignored (= anonymous).
 * If anonymous is null a new bind is done (i.e. user changed).
 *
 * @param int $server_id The ID of the server of interest.
 * @param bool $anonymous Set to override server config
 * @return resource The LDAP connection resource or the LDAP errorcode
 *
 * @see get_logged_in_dn
 * @see get_logged_in_pass
 * @see have_auth_info
 * @see check_server_id
 */
function pla_ldap_connect( $server_id, $anonymous = false, $use_cache = true)
{
    //echo "pla_ldap_connect( $server_id, $anonymous, $use_cache )<br />\n";
	if( ! check_server_id( $server_id ) )
		return -1;

	if( ! $anonymous && ! have_auth_info( $server_id ) )
		return -2;

	global $servers, $lang;

	// cache the connection, so if we are called multiple
	// times, we don't have to reauthenticate with the LDAP server
	static $conns;

	// We can reuse connections for multiple binds if we don't ldap_unbind
	if( $use_cache && isset( $conns[ $server_id ] ) ) {
		$conn = $conns[ $server_id ][ 'conn' ];
		$status = $conns[ $server_id ][ 'stat' ];

		// Status tells us, if we can use the same bind
		if( !is_null($status) && $status == $anonymous )
			return $conn;
	} else {
		$host = $servers[$server_id]['host'];

		$port = isset( $servers[$server_id]['port'] ) ? $servers[ $server_id ][ 'port' ] : false;

		if( $port )
			$conn = @ldap_connect( $host, $port );
		else
			$conn = @ldap_connect( $host );

		$conn or pla_error( sprintf( $lang['could_not_connect_to_host_on_port'], htmlspecialchars( $host ),  htmlspecialchars( $port ) ) );

		// go with LDAP version 3 if possible (needed for renaming and Novell schema fetching)
		@ldap_set_option( $conn, LDAP_OPT_PROTOCOL_VERSION, 3 );
		// Disabling this makes it possible to browse the tree for Active Directory, and seems
		// to not affect other LDAP servers (tested with OpenLDAP) as phpLDAPadmin explicitly
		// specifies deref behavior for each ldap_search operation.
		@ldap_set_option( $conn, LDAP_OPT_REFERRALS, 0);

		// try to fire up TLS is specified in the config
		if( tls_enabled( $server_id ) ) {
			function_exists( 'ldap_start_tls' ) or pla_error( $lang['php_install_not_supports_tls'] );
			@ldap_start_tls( $conn ) or pla_error( $lang['could_not_start_tls']);
		}

		// store the cached connection resource
		$conns[$server_id]['conn'] = $conn;
		$conns[$server_id]['stat'] = null;
	}

	if( $anonymous == true ) {
		$login_dn = null;
		$login_pass = null;
	} // grab the auth info based on the auth_type for this server
	elseif( $servers[ $server_id ][ 'auth_type' ] == 'config' ) {
		$login_dn = $servers[$server_id]['login_dn'];
		$login_pass = $servers[$server_id]['login_pass'];
		$login_dn = expand_dn_with_base( $server_id, $login_dn, $conn, false );
	} else {
		$login_dn = get_logged_in_dn( $server_id );
		$login_pass = get_logged_in_pass( $server_id );

		// Was this an anonyous bind (the cookie stores 0 if so)?
		if( 'anonymous' == $login_dn ) {
			$login_dn = null;
			$login_pass = null;
		}
	}

	$res = @ldap_bind( $conn, $login_dn, $login_pass );

	if( ! $res )
		return ldap_errno( $conn );

	// store the bind status
	$conns[$server_id]['stat'] = $anonymous;

	return $conn;
}

/**
 * Convenient function to handle pla_ldap_connect results
 * @see pla_ldap_connect
 *
 * @param resource $ds The pla_ldap_connect result
 * @param bool $process_error Defines, if you want do run pla_error
 * @return Returns false if the connection ($ds) is ok, or true otherwise.
 */
function pla_ldap_connection_is_error( $ds, $process_error = true )
{
	if ( ! $process_error )
		return ( ! is_resource( $ds ) );
	else {
		if ( ! is_resource( $ds ) ) {
			global $lang;

			if( is_numeric( $ds ) ) {
				switch( $ds ) {
				case -1: pla_error( $lang['bad_server_id'] ); break;
				case -2: pla_error( $lang['not_enough_login_info'] ); break;
				default: pla_error( $lang['ferror_error'] ); break;
				}
				return true;
			}
		
			switch( $ds ) {
			case 0x31:
				pla_error( $lang['bad_user_name_or_password'] );
				break;
			case 0x32:
				pla_error( $lang['insufficient_access_rights'] );
				break;
			case 0x5b:
				pla_error( $lang['could_not_connect'] );
				break;
			default:
				pla_error( $lang['could_not_bind'], ldap_err2str( $ds ), $ds );
				break;
			}
		}
		return false;
	}
}

/**
 * Gets a list of child entries for an entry. Given a DN, this function fetches the list of DNs of
 * child entries one level beneath the parent. For example, for the following tree:
 *
 * <code>
 * dc=example,dc=com
 *   ou=People
 *      cn=Dave
 *      cn=Fred
 *      cn=Joe
 *      ou=More People
 *         cn=Mark
 *         cn=Bob
 * </code>
 *
 * Calling <code>get_container_contents( $server_id, "ou=people,dc=example,dc=com" )</code>
 * would return the following list:
 * 
 * <code>
 *  cn=Dave
 *  cn=Fred
 *  cn=Joe
 *  ou=More People
 * </code>
 * 
 * @param int $server_id The ID of the server housing the entry of interest
 * @param string $dn The DN of the entry whose children to return.
 * @param int $size_limit (optional) The maximum number of entries to return. 
 *             If unspecified, no limit is applied to the number of entries in the returned.
 * @param string $filter (optional) An LDAP filter to apply when fetching children, example: "(objectClass=inetOrgPerson)"
 * @return array An array of DN strings listing the immediate children of the specified entry.
 */
function get_container_contents( $server_id, $dn, $size_limit=0, $filter='(objectClass=*)', $deref=LDAP_DEREF_ALWAYS )
{
	$conn = pla_ldap_connect( $server_id );
	if( pla_ldap_connection_is_error( $conn, false ) )
		return false;

//	echo "get_container_contents( $server_id, $dn, $size_limit, $filter, $deref )\n";
	$search = @ldap_list( $conn, $dn, $filter, array( 'dn' ), 1, $size_limit, 0, $deref );
	if( ! $search )
		return array();
	$search = ldap_get_entries( $conn, $search );

	$return = array();
	for( $i=0; $i<$search['count']; $i++ ) {
		$entry = $search[$i];
		$dn = $entry['dn'];
		$return[] = $dn;
	}

	return $return;
}

/**
 * Builds the initial tree that is stored in the session variable 'tree'.
 * Simply returns an array with an entry for each active server in
 * config.php. The structure of the returned array is simple, and looks like
 * this:
 * <code>
 *   Array ( 
 *      0 => Array ( )
 *      1 => Array ( )
 *   )
 * </code>
 * This function is not meant as a user callable function, but rather a convenient,
 * automated method for setting up the initial structure for the tree viewer.
 */
function build_initial_tree()
{
	global $servers;
	$tree = array();
	foreach( $servers as $id => $server ) {
		if( $server['host'] == '' ) {
			continue;
		}

		$tree[$id] = array();
	}

	return $tree;
}

/**
 * Builds the initial array that stores the icon-lookup for each server's DN in the tree browser. The returned
 * array is then stored in the current session. The structure of the returned array is simple, and looks like
 * this:
 * <code>
 *   Array 
 *    ( 
 *      [0] => Array 
 *          (
 *             [dc=example,dc=com] => "dcobject.png"
 *          )
 *      [1] => Array 
            (
 *            [o=Corporation] => "o.png"
 *          )
 *     )
 * </code>
 * This function is not meant as a user-callable function, but rather a convenient, automated method for 
 * setting up the initial data structure for the tree viewer's icon cache.
 */
function build_initial_tree_icons()
{
	global $servers;
	$tree_icons = array();

	// initialize an empty array for each server
	foreach( $servers as $id => $server ) {
		if( $server['host'] == '' )
			continue;
		$tree_icons[ $id ] = array();
		$tree_icons[ $id ][ $server['base'] ] = get_icon( $id, $server['base'] );
	}

	return $tree_icons;
}

/*
 * Checks and fixes an initial session's tree cache if needed.
 *
 * This function is not meant as a user-callable function, but rather a convenient,
 * automated method for checking the initial data structure of the session.
 */
function initialize_session_tree()
{
	// From the PHP manual: If you use $_SESSION don't use
	// session_register(), session_is_registered() or session_unregister()!
	if( ! array_key_exists( 'tree',  $_SESSION ) )
		$_SESSION['tree'] = build_initial_tree();
	if( ! array_key_exists( 'tree_icons', $_SESSION ) )
		$_SESSION['tree_icons'] = build_initial_tree_icons();

    // Make sure that the tree index is indeed well formed.
    if( ! is_array( $_SESSION['tree'] ) )
		$_SESSION['tree'] = build_initial_tree();
    if( ! is_array( $_SESSION['tree_icons'] ) )
		$_SESSION['tree_icons'] = build_initial_tree_icons();
        
}

/** 
 * Gets the operational attributes for an entry. Given a DN, this function fetches that entry's
 * operational (ie, system or internal) attributes. These attributes include "createTimeStamp", 
 * "creatorsName", and any other attribute that the LDAP server sets automatically. The returned
 * associative array is of this form:
 * <code>
 *  Array 
 *  (
 *    [creatorsName] => Array 
 *        (
 *           [0] => "cn=Admin,dc=example,dc=com"
 *        )
 *    [createTimeStamp]=> Array 
 *        (
 *           [0] => "10401040130"
 *        )
 *    [hasSubordinates] => Array 
 *        (
 *           [0] => "FALSE"
 *        )
 *  )
 * </code>
 *
 * @param int $server_id the ID of the server of interest.
 * @param string $dn The DN of the entry whose interal attributes are desired.
 * @param int $deref For aliases and referrals, this parameter specifies whether to 
 *            follow references to the referenced DN or to fetch the attributes for
 *            the referencing DN. See http://php.net/ldap_search for the 4 valid
 *            options.
 * @return array An associative array whose keys are attribute names and whose values
 *              are arrays of values for the aforementioned attribute.
 */
function get_entry_system_attrs( $server_id, $dn, $deref=LDAP_DEREF_NEVER )
{
	$conn = pla_ldap_connect( $server_id );
	if( pla_ldap_connection_is_error( $conn, false ) ) 
		return false;

	$attrs = array( 'creatorsname', 'createtimestamp', 'modifiersname', 
			'structuralObjectClass', 'entryUUID',  'modifytimestamp', 
			'subschemaSubentry', 'hasSubordinates', '+' );
	$search = @ldap_read( $conn, $dn, '(objectClass=*)', $attrs, 0, 0, 0, $deref );
	if( ! $search )
		return false;
	$entry = ldap_first_entry( $conn, $search );
	if( ! $entry)
	    return false;
	$attrs = ldap_get_attributes( $conn, $entry );
	if( ! $attrs )
		return false;
	if( ! isset( $attrs['count'] ) )
		return false;
	$count = $attrs['count'];
	unset( $attrs['count'] );
	$return_attrs = array();
	for( $i=0; $i<$count; $i++ ) {
		$attr_name = $attrs[$i];
		unset( $attrs[$attr_name]['count'] );
		$return_attrs[$attr_name] = $attrs[$attr_name];
	}
	return $return_attrs;
}

/**
 * Gets the attributes/values of an entry. Returns an associative array whose
 * keys are attribute value names and whose values are arrays of values for
 * said attribute. Optionally, callers may specify true for the parameter 
 * $lower_case_attr_names to force all keys in the associate array (attribute 
 * names) to be lower case. 
 * 
 * Sample return value of <code>get_object_attrs( 0, "cn=Bob,ou=pepole,dc=example,dc=com" )</code>
 *
 * <code>
 * Array
 *  (
 *   [objectClass] => Array
 *       (
 *           [0] => person
 *           [1] => top
 *       )
 *   [cn] => Array
 *       (
 *           [0] => Bob
 *       )
 *   [sn] => Array
 *       (
 *           [0] => Jones
 *       )
 *   [dn] => Array
 *       (
 *            [0] => cn=Bob,ou=pepole,dc=example,dc=com
 *       )
 *  )
 * </code>
 *
 * @param int $server_id The ID of the server of interest
 * @param string $dn The distinguished name (DN) of the entry whose attributes/values to fetch.
 * @param bool $lower_case_attr_names (optional) If true, all keys of the returned associative
 *              array will be lower case. Otherwise, they will be cased as the LDAP server returns
 *              them.
 * @param int $deref For aliases and referrals, this parameter specifies whether to 
 *            follow references to the referenced DN or to fetch the attributes for
 *            the referencing DN. See http://php.net/ldap_search for the 4 valid
 *            options.
 * @return array
 * @see get_entry_system_attrs
 * @see get_object_attr
 */
function get_object_attrs( $server_id, $dn, $lower_case_attr_names=false, $deref=LDAP_DEREF_NEVER )
{
	//echo "get_object_attrs( $server_id, $dn, $lower_case_attr_names )<br />";
	$conn = pla_ldap_connect( $server_id );
	if( pla_ldap_connection_is_error( $conn, false ) )
		return false;

	$search = @ldap_read( $conn, $dn, '(objectClass=*)', array( ), 0, 0, 0, $deref );

	if( ! $search )
		return false;

	$entry = ldap_first_entry( $conn, $search );

	if( ! $entry )
		return false;
	
	$attrs = ldap_get_attributes( $conn, $entry );

	if( ! $attrs || $attrs['count'] == 0 )
		return false;

	$num_attrs = $attrs['count'];
	unset( $attrs['count'] );

	// strip numerical inices
	for( $i=0; $i<$num_attrs; $i++ )
		unset( $attrs[$i] );

	$return_array = array();
	foreach( $attrs as $attr => $vals ) {
		if( $lower_case_attr_names )
			$attr = strtolower( $attr );
		if( is_attr_binary( $server_id, $attr ) )
			$vals = ldap_get_values_len( $conn, $entry, $attr );
		unset( $vals['count'] );
		$return_array[ $attr ] = $vals;
	}

	ksort( $return_array );

	return $return_array;
}

/**
 * Returns true if the passed string $temp contains all printable
 * ASCII characters. Otherwise (like if it contains binary data),
 * returns false.
 */
function is_printable_str($temp) {
	$len = strlen($temp);
	for ($i=0; $i<$len; $i++) {
		$ascii_val = ord( substr( $temp,$i,1 ) );
		if( $ascii_val < 32 || $ascii_val > 126 )
			return false;
	}

	return true;
}

/**
 * Much like get_object_attrs(), but only returns the values for
 * one attribute of an object. Example calls:
 *
 * <code>
 * print_r( get_object_attr( 0, "cn=Bob,ou=people,dc=example,dc=com", "sn" ) );
 * // prints:
 * //  Array 
 * //    ( 
 * //       [0] => "Smith"
 * //    )
 *
 * print_r( get_object_attr( 0, "cn=Bob,ou=people,dc=example,dc=com", "objectClass" ) );
 * // prints:
 * //  Array 
 * //    ( 
 * //       [0] => "top"
 * //       [1] => "person"
 * //    )
 * </code>
 * 
 * @param int $server_id The ID of the server of interest
 * @param string $dn The distinguished name (DN) of the entry whose attributes/values to fetch.
 * @param string $attr The attribute whose value(s) to return (ie, "objectClass", "cn", "userPassword")
 * @param bool $lower_case_attr_names (optional) If true, all keys of the returned associative
 *              array will be lower case. Otherwise, they will be cased as the LDAP server returns
 *              them.
 * @param int $deref For aliases and referrals, this parameter specifies whether to 
 *            follow references to the referenced DN or to fetch the attributes for
 *            the referencing DN. See http://php.net/ldap_search for the 4 valid
 *            options.
 * @see get_object_attrs
 */
function get_object_attr( $server_id, $dn, $attr, $deref=LDAP_DEREF_NEVER )
{
	/**
	$attr = strtolower( $attr );
	$attrs = get_object_attrs( $server_id, $dn, true );
	if( isset( $attrs[$attr] ) )
		return $attrs[$attr];
	else
		return false;
		*/

	//echo "get_object_attr( $server_id, $dn, $attr )<br />";
	$conn = pla_ldap_connect( $server_id );
	if( pla_ldap_connection_is_error( $conn, false ) ) 
		return false;

	$search = @ldap_read( $conn, $dn, '(objectClass=*)', array( $attr ), 0, 0, 0, $deref );

	if( ! $search )
		return false;

	$entry = ldap_first_entry( $conn, $search );

	if( ! $entry )
		return false;
	
	$attrs = ldap_get_attributes( $conn, $entry );

	if( ! $attrs || $attrs['count'] == 0 )
		return false;

	if( is_attr_binary( $server_id, $attr ) )
		$vals = ldap_get_values_len( $conn, $entry, $attr );
	else
		$vals = ldap_get_values( $conn, $entry, $attr );
	unset( $vals['count'] );
	return $vals;
}

/**
 * A handy ldap searching function very similar to PHP's ldap_search() with the 
 * following exceptions: Callers may specify a search scope and the return value 
 * is an array containing the search results rather than an LDAP result resource.
 *
 * Example usage:
 * <code>
 * $samba_users = ldap_search( 0, "(&(objectClass=sambaAccount)(objectClass=posixAccount))", 
 *                              "ou=People,dc=example,dc=com", array( "uid", "homeDirectory" ) );
 * print_r( $samba_users );
 * // prints (for example): 
 * //  Array 
 * //    ( 
 * //       [uid=jsmith,ou=People,dc=example,dc=com] => Array
 * //           (
 * //               [dn] => "uid=jsmith,ou=People,dc=example,dc=com"
 * //               [uid] => "jsmith"
 * //               [homeDirectory] => "\\server\jsmith"
 * //           )
 * //       [uid=byoung,ou=People,dc=example,dc=com] => Array
 * //           (
 * //               [dn] => "uid=byoung,ou=Samba,ou=People,dc=example,dc=com"
 * //               [uid] => "byoung"
 * //               [homeDirectory] => "\\server\byoung"
 * //           )
 * //    )
 * </code>
 * 
 * WARNING: This function will use a lot of memory on large searches since the entire result set is
 * stored in a single array. For large searches, you should consider sing the less memory intensive 
 * PHP LDAP API directly (ldap_search(), ldap_next_entry(), ldap_next_attribute(), etc).
 *
 * @param int $server_id The ID of the server to search on.
 * @param string $filter The LDAP filter to use when searching (example: "(objectClass=*)") (see RFC 2254)
 * @param string $base_dn The DN of the base of search. 
 * @param array $attrs An array of attributes to include in the search result (example: array( "objectClass", "uid", "sn" )).
 * @param string $scope The LDAP search scope. Must be one of "base", "one", or "sub". Standard LDAP search scope.
 * @param bool $sort_results Specify false to not sort results by DN or true to have the 
 *                  returned array sorted by DN (uses ksort)
 * @param int $deref When handling aliases or referrals, this specifies whether to follow referrals. Must be one of 
 *                  LDAP_DEREF_ALWAYS, LDAP_DEREF_NEVER, LDAP_DEREF_SEARCHING, or LDAP_DEREF_FINDING. See the PHP LDAP API for details.
 */
function pla_ldap_search( $server_id, $filter, $base_dn=null, $attrs=array(), $scope='sub', $sort_results=true, $deref=LDAP_DEREF_ALWAYS )
{
	global $servers;

	if( ! check_server_id( $server_id ) )
		return false;

	if( $base_dn == null )
		$base_dn = $servers[$server_id]['base'];

	$ds = pla_ldap_connect( $server_id );
	if( pla_ldap_connection_is_error( $ds, false ) )
		return false;

	switch( $scope ) {
		case 'base':
			$search = @ldap_read( $ds, $base_dn, $filter, $attrs, 0, 0, 0, $deref );
			break;
		case 'one':
			$search = @ldap_list( $ds, $base_dn, $filter, $attrs, 0, 0, 0, $defef );
			break;
		case 'sub':
		default:
			$search = @ldap_search( $ds, $base_dn, $filter, $attrs, 0, 0, 0, $deref );
			break;
	}

	if( ! $search )
		return array();

	$return = array();
	//get the first entry identifier
	if( $entry_id = ldap_first_entry($ds,$search) )

		//iterate over the entries
		while($entry_id) {

			//get the distinguished name of the entry
			$dn = ldap_get_dn($ds,$entry_id);

			//get the attributes of the entry
			$attrs = ldap_get_attributes($ds,$entry_id);
			$return[$dn]['dn'] = $dn;

			//get the first attribute of the entry
			if($attr = ldap_first_attribute($ds,$entry_id,$attrs))

				//iterate over the attributes
				while($attr){
				  if( is_attr_binary($server_id,$attr))
						$values = ldap_get_values_len($ds,$entry_id,$attr);
					else
						$values = ldap_get_values($ds,$entry_id,$attr);

					//get the number of values for this attribute
					$count = $values['count'];
					unset($values['count']);
					if($count==1)
						$return[$dn][$attr] = $values[0];
					else
						$return[$dn][$attr] = $values;

					$attr = ldap_next_attribute($ds,$entry_id,$attrs);
				}// end while attr

			$entry_id = ldap_next_entry($ds,$entry_id);

		} // end while entry_id

	if( $sort_results && is_array( $return ) )
		ksort( $return );

	return $return;
}

/**
 * Reads the query, checks all values and sets defaults.
 *
 * @param int $query_id The ID of the predefined query.
 *
 * @return array The fixed query or null on error
 */
function get_cleaned_up_predefined_search( $query_id )
{
	global $queries;

	if( ! isset( $queries[$query_id] ) )
		return null;

	$query = $queries[$query_id];

	if( isset( $query['server'] ) && ( is_numeric( $query['server'] ) ) )
		$server_id = $query['server'];
	else $server_id = 0;

	$base = ( isset( $query['base'] ) ) ? $query['base'] : null;
	$base = expand_dn_with_base( $server_id, $base );

	if( isset( $query['filter'] ) && strlen( trim( $query['filter'] ) ) > 0 )
		$filter = $query['filter'];
	else
        $filter = 'objectclass=*';

	$scope = isset( $query['scope'] )
		&& ( in_array( $query['scope'], array( 'base', 'sub', 'one' ) ) )
		? $query['scope'] : 'sub';

	if( isset( $query['attributes'] ) && strlen( trim( $query['filter'] ) ) > 0 )
		$attrib = $query['attributes'];
	else 
        $attrib = "dn, cn, sn, objectClass";

	return array ( 'server' => $server_id, 'base' => $base,
		'filter' => $filter, 'scope' => $scope, 'attributes' => $attrib );
}

/**
 * Transforms the user-configured search lists into arrays for use by other components of phpLDAPadmin. 
 * This may seem a little strange, and that's because it is strange.
 * 
 * The function takes the comma-separated lists (like the search result attribute list) in config.php
 * and turns them into arrays. Only call this ONCE per script. Any subsequent call will
 * mess up the arrays. This function operates on global variables defined in config.php and is currently
 * only used by search_form_simple.php
 * 
 * For more details, just read the function's code. It's short and pretty straightforward.
 */
function process_config()
{
	global $search_result_attributes;
	$search_result_attributes = explode( ",", $search_result_attributes );
	array_walk( $search_result_attributes, "trim_it" );

	global $search_attributes_display;
	$search_attributes_display = explode( ",", $search_attributes_display );
	array_walk( $search_attributes_display, "trim_it" );

	global $search_attributes;
	$search_attributes= explode( ",", $search_attributes);
	array_walk( $search_attributes, "trim_it" );

    if( count( $search_attributes ) != count( $search_attributes_display ) )
        pla_error( $lang['search_Attrs_wrong_count'] );
}

/**
 * Trim a string in place (call by reference) Used to filter empty entries out of the arrays
 * that we generate in process_config().
 *
 * @see process_config
 */
function trim_it( &$str )
{
	$str = trim($str);
}

/**
 * Checks the specified server id for sanity. Ensures that the server is indeed in the configured 
 * list and active. This is used by many many scripts to ensure that valid server ID values 
 * are passed in POST and GET.
 */
function check_server_id( $server_id )
{
	global $servers;
	if( ! is_numeric( $server_id ) || ! isset( $servers[$server_id] ) || ! isset( $servers[$server_id]['host'] ) || $servers[$server_id]['host'] == '' )
		return false;
	else
		return true;
}

/**
 * Used to generate a random salt for crypt-style passwords. Salt strings are used 
 * to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses 
 * not only the user's password but also a randomly generated string. The string is 
 * stored as the first N characters of the hash for reference of hashing algorithms later.
 *
 * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
 * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
 *
 * @param int $length The length of the salt string to generate.
 * @return string The generated salt string.
 */
function random_salt( $length )
{
        $possible = '0123456789'.
                        'abcdefghijklmnopqrstuvwxyz'.
                        'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
                        './';
        $str = "";
        mt_srand((double)microtime() * 1000000);
        while( strlen( $str ) < $length )
        {
                $str .= substr( $possible, ( rand() % strlen( $possible ) ), 1 );
        }
	/**
	 * Commented out following line because of problem
	 * with crypt function in update.php
	 * --- 20030625 by S C Rigler <srigler@houston.rr.com> ---
	 */
        //$str = "\$1\$".$str."\$";
        return $str;
}

/**
 * Goes through the user-configured server list and looks for an available server_id,
 * one that has specified enough information to login. This is for choosing the
 * server to display in the drop-down box in search.php.
 *
 * @return int The first available server ID found.
 */
function get_avail_server_id()
{
	global $servers;

	for( $i=0; $i<count($servers); $i++ )
		if( check_server_id( $i ) &&  have_auth_info( $i ) )
			return $i;
	return false;
}

/**
 * Given a DN string, this returns the 'RDN' portion of the string.
 * For example. given 'cn=Manager,dc=example,dc=com', this function returns
 * 'cn=Manager' (it is really the exact opposite of get_container()).
 *
 * @param string $dn The DN whose RDN to return.
 * @param bool $include_attrs If true, include attributes in the RDN string. 
 *               See http://php.net/ldap_explode_dn for details
 *
 * @return string The RDN
 * @see get_container
 */
function get_rdn( $dn, $include_attrs=0 )
{
	if( $dn == null )
		return null;
	$rdn = pla_explode_dn( $dn, $include_attrs );
	if( 0 == count($rdn) )
		return $dn;
	if( ! isset( $rdn[0] ) )
		return $dn;
	$rdn = $rdn[0];
	return $rdn;
}

/**
 * Given a DN string, this returns the parent container portion of the string.
 * For example. given 'cn=Manager,dc=example,dc=com', this function returns
 * 'dc=example,dc=com'.
 * 
 * @param string $dn The DN whose container string to return.
 *
 * @return string The container
 * @see get_rdn
 */
function get_container( $dn )
{
	$parts = pla_explode_dn( $dn );
    if( count( $parts ) <= 1 )
        return null;
	$container = $parts[1];
	for( $i=2; $i<count($parts); $i++ )
		$container .= ',' . $parts[$i];
	return $container;
}

/**
 * Given an LDAP error number, returns a verbose description of the error.
 * This function parses ldap_error_codes.txt and looks up the specified
 * ldap error number, and returns the verbose message defined in that file.
 *
 * @param string $err_no The hex error number (ie, "0x42") of the LDAP error of interest.
 * @return array An associative array contianing the error title and description like so:
 *   <code>
 *  Array 
 *    (
 *       [title] => "Invalid Credentials"
 *       [description] => "An invalid username and/or password was supplied to the LDAP server."
 *    )
 *   </code>
 */
function pla_verbose_error( $err_no )
{
	static $err_codes;
	if( count($err_codes) > 0 ) {
        if( isset( $err_codes[ $err_no ] ) )
            return $err_codes[ $err_no ];
        else
            return array( 'title' => null, 'desc' => null );
	} 

	$err_codes_file = 'ldap_error_codes.txt';

	if( ! file_exists( realpath( $err_codes_file ) ) )
		return false;
	if( ! is_readable( realpath( $err_codes_file ) ) )
		return false;
	if( ! ($f = fopen( realpath( $err_codes_file ), 'r' ) ) )
		return false;

	$contents = fread( $f, filesize( $err_codes_file ) );
    fclose( $f );
	$entries = array();
	preg_match_all( "/0x[A-Fa-f0-9][A-Za-z0-9]\s+[0-9A-Za-z_]+\s+\"[^\"]*\"\n/", $contents, $entries );
	$err_codes = array();
	foreach( $entries[0] as $e ) {
		$entry = array();
		preg_match( "/(0x[A-Za-z0-9][A-Za-z0-9])\s+([0-9A-Za-z_]+)\s+\"([^\"]*)\"/", $e, $entry );
		$hex_code = isset( $entry[1] ) ? $entry[1] : null;
		$title    = isset( $entry[2] ) ? $entry[2] : null;
		$desc     = isset( $entry[3] ) ? $entry[3] : null;
		$desc     = preg_replace( "/\s+/", " ", $desc );
		$err_codes[ "$hex_code" ] = array( 'title' => $title, 'desc' => $desc );
	}

    // Sanity check
    if( isset( $err_codes[ $err_no ] ) )
    	return $err_codes[ $err_no ];
    else
        return array( 'title' => null, 'desc' => null );
}

/**
 * Prints an HTML-formatted error string. If you specify the optional
 * parameters $ldap_err_msg and $ldap_err_no, this function will 
 * lookup the error number and display a verbose message in addition 
 * to the message you pass it.
 * 
 * @param string $msg The error message to display.
 * @param string $ldap_err_msg (optional) The error message supplied by the LDAP server 
 * @param string $ldap_err_no (optional) The hexadecimal error number string supplied by the LDAP server 
 * @param bool $fatal (optional) If true, phpLDAPadmin will terminate execution with the PHP die() function.
 *
 * @see die
 * @see ldap_errno
 * @see pla_verbose_error
 */
function pla_error( $msg, $ldap_err_msg=null, $ldap_err_no=-1, $fatal=true )
{
	@include_once 'header.php';
	global $lang;

	?>
	<center>
	<table class="error"><tr><td class="img"><img src="images/warning.png" /></td>
	<td><center><h2><?php echo $lang['ferror_error'];?></h2></center>
	<?php echo $msg; ?>
	<br />
	<br />
	<?php

	if( $ldap_err_msg ) {
		echo sprintf($lang['ldap_said'], htmlspecialchars( $ldap_err_msg ));
		echo '<br />';
		}

	if( $ldap_err_no != -1 ) {
		$ldap_err_no = ( '0x' . str_pad( dechex( $ldap_err_no ), 2, 0, STR_PAD_LEFT ) );
		$verbose_error = pla_verbose_error( $ldap_err_no );

		if( $verbose_error ) {
			echo sprintf( $lang['ferror_number'], $ldap_err_no, $verbose_error['title']);
			echo '<br />';
			echo sprintf( $lang['ferror_discription'], $verbose_error['desc']);
		} else {
			echo sprintf($lang['ferror_number_short'], $ldap_err_no);
			echo '<br />';
			echo $lang['ferror_discription_short'];
		}
	}
	?>
	<br />
	<!-- Commented out due to too many false bug reports. :)
	<br />
	<center>
	<small>
		<?php echo sprintf($lang['ferror_submit_bug'] , get_href( 'add_bug' ));?>
	</small>
	</center>
	-->
	</td></tr></table>
	</center>
	<?php

	if( $fatal )
		echo "</body>\n</html>";
		die();
}

/**
 * phpLDAPadmin's custom error handling function. When a PHP error occurs,
 * PHP will call this function rather than printing the typical PHP error string. 
 * This provides phpLDAPadmin the ability to format an error message more "pretty"
 * and provide a link for users to submit a bug report. This function is not to
 * be called by users. It is exclusively for the use of PHP internally. If this
 * function is called by PHP from within a context where error handling has been
 * disabled (ie, from within a function called with "@" prepended), then this
 * function does nothing.
 *
 * @param int $errno The PHP error number that occurred (ie, E_ERROR, E_WARNING, E_PARSE, etc).
 * @param string $errstr The PHP error string provided (ie, "Warning index "foo" is undefined)
 * @param string $file The file in which the PHP error ocurred.
 * @param int $lineno The line number on which the PHP error ocurred
 *
 * @see set_error_handler
 */
function pla_error_handler( $errno, $errstr, $file, $lineno )
{
	global $lang;

	// error_reporting will be 0 if the error context occurred
	// within a function call with '@' preprended (ie, @ldap_bind() );
	// So, don't report errors if the caller has specifically
	// disabled them with '@'
	if( 0 == ini_get( 'error_reporting' ) || 0 == error_reporting() )
			return;

	$file = basename( $file );
	$caller = basename( $_SERVER['PHP_SELF'] );
	$errtype = "";
	switch( $errno ) {
        case E_STRICT: $errtype = "E_STRICT"; break;
		case E_ERROR: $errtype = "E_ERROR"; break;
		case E_WARNING: $errtype = "E_WARNING"; break;
		case E_PARSE: $errtype = "E_PARSE"; break;
		case E_NOTICE: $errtype = "E_NOTICE"; break;
		case E_CORE_ERROR: $errtype = "E_CORE_ERROR"; break;
		case E_CORE_WARNING: $errtype = "E_CORE_WARNING"; break;
		case E_COMPILE_ERROR: $errtype = "E_COMPILE_ERROR"; break;
		case E_COMPILE_WARNING: $errtype = "E_COMPILE_WARNING"; break;
		case E_USER_ERROR: $errtype = "E_USER_ERROR"; break;
		case E_USER_WARNING: $errtype = "E_USER_WARNING"; break;
		case E_USER_NOTICE: $errtype = "E_USER_NOTICE"; break;
		case E_ALL: $errtype = "E_ALL"; break;
		default: $errtype = $lang['ferror_unrecognized_num'] . $errno;
	}

	if( $errno == E_NOTICE ) {
		echo sprintf($lang['ferror_nonfatil_bug'], $errstr, $errtype, $file,
                             $lineno, $caller, pla_version(), phpversion(), php_sapi_name(),
                             $_SERVER['SERVER_SOFTWARE'], get_href('add_bug'));
		return;
	}

	$server = isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : 'undefined';
	$phpself = isset( $_SERVER['PHP_SELF'] ) ? basename( $_SERVER['PHP_SELF'] ) : 'undefined';
	pla_error( sprintf($lang['ferror_congrats_found_bug'], $errstr, $errtype, $file, 
							$lineno, $phpself, pla_version(), 
							phpversion(), php_sapi_name(), $server ));
}

/**
 * Reads the friendly_attrs array as defined in config.php and lower-cases all
 * the keys. Will return an empty array if the friendly_attrs array is not defined
 * in config.php. This is simply used so we can more easily lookup user-friendly
 * attributes configured by the admin.
 */
function process_friendly_attr_table()
{
	require 'config.php';
	global $friendly_attrs;
	$attrs_table = array();
	if( isset( $friendly_attrs ) && is_array( $friendly_attrs ) )
		foreach( $friendly_attrs as $old_name => $new_name )
			$attrs_table[ strtolower( $old_name ) ] = $new_name;
	else
		return array();

	return $attrs_table;
}

/**
 * Gets whether an entry exists based on its DN. If the entry exists, 
 * returns true. Otherwise returns false.
 *
 * @param int $server_id The ID of the server of interest
 * @param string $dn The DN\of the entry of interest.
 *
 * @return bool
 */
function dn_exists( $server_id, $dn )
{
	if( ! check_server_id( $server_id ) )
		return false;

	$ds = pla_ldap_connect( $server_id );
	if( pla_ldap_connection_is_error( $ds, false ) )
		return false;

	$search_result = @ldap_read( $ds, $dn, 'objectClass=*', array('dn') );

	if( ! $search_result )
		return false;

	$num_entries = ldap_count_entries( $ds, $search_result );

	if( $num_entries > 0 )
		return true;
	else
		return false;
}

/**
 * Draw the jpegPhoto image(s) for an entry wrapped in HTML. Many options are available to 
 * specify how the images are to be displayed.
 *
 * Usage Examples:
 *  <code>
 *    draw_jpeg_photos( 0, "cn=Bob,ou=People,dc=example,dc=com", "jpegPhoto" true, false, "border: 1px; width: 150px" );
 *    draw_jpeg_photos( 1, "cn=Fred,ou=People,dc=example,dc=com" );
 *  </code>
 *
 * @param int $server_id The ID of the server of interest.
 * @param string $dn The DN of the entry that contains the jpeg attribute you want to draw.
 * @param string $attr_name The name of the attribute containing the jpeg data (usually 'jpegPhoto').
 * @param bool $draw_delete_buttons If true, draws a button beneath the image titled 'Delete' allowing the user
 *                  to delete the jpeg attribute by calling JavaScript function deleteAttribute() provided
 *                  in the default modification template.
 * @param bool $draw_bytes_and_size If true, draw text below the image indicating the byte size and dimensions.
 * @param string $table_html_attrs Specifies optional CSS style attributes for the table tag.
 *
 * @return void
 */
function draw_jpeg_photos( $server_id, $dn, $attr_name='jpegPhoto', $draw_delete_buttons=false,
				$draw_bytes_and_size=true, $table_html_attrs='align="left"', $img_html_attrs='' )
{
	global $jpeg_temp_dir;
	global $jpeg_tmp_keep_time;
	global $lang;

	$conn = pla_ldap_connect( $server_id );
	if( pla_ldap_connection_is_error( $conn, false ) )
		return;
	$search_result = ldap_read( $conn, $dn, 'objectClass=*', array( $attr_name ) );
	$entry = ldap_first_entry( $conn, $search_result );

	echo "<table $table_html_attrs><td><center>\n\n";
	// for each jpegPhoto in the entry, draw it (there may be only one, and that's okay)
	$jpeg_data = @ldap_get_values_len( $conn, $entry, $attr_name );
    if( ! is_array( $jpeg_data ) ) {
        echo "Could not fetch jpeg data from LDAP server for attribute " . htmlspecialchars( $attr_name );
        return;
    }
	for( $i=0; $i<$jpeg_data['count']; $i++ )
	{
		// ensures that the photo is written to the specified jpeg_temp_dir
		$jpeg_temp_dir = realpath($jpeg_temp_dir.'/');
        if( ! is_writable( $jpeg_temp_dir ) )
            pla_error( 'Please set $jpeg_temp_dir to a writable directory in the phpLDAPadmin config.php' );
		$jpeg_filename = tempnam($jpeg_temp_dir.'/', 'pla');
		$outjpeg = @fopen($jpeg_filename, "wb");
        if( ! $outjpeg )
            pla_error( 'Could not write to the $jpeg_temp_dir directory (' . $jpeg_temp_dir . '). Please verify that your web server can write files there.' );
		fwrite($outjpeg, $jpeg_data[$i]);
		fclose ($outjpeg);
		$jpeg_data_size = filesize( $jpeg_filename );
		if( $jpeg_data_size < 6 && $draw_delete_buttons ) {
			echo $lang['jpeg_contains_errors'];
			echo '<a href="javascript:deleteAttribute( \'' . $attr_name . '\' );" style="color:red; font-size: 75%">'. $lang['delete_photo'] .'</a>';
			continue;
		}

        if( function_exists( 'getimagesize' ) ) {
            $jpeg_dimensions = @getimagesize( $jpeg_filename );
            $width = $jpeg_dimensions[0];
            $height = $jpeg_dimensions[1];
        } else {
            $width = 0; 
            $height = 0;
        }
		if( $width > 300 ) {
			$scale_factor = 300 / $width;
			$img_width = 300;
			$img_height = $height * $scale_factor;
		} else {
			$img_width = $width;
			$img_height = $height;
		}
		echo "<img width=\"$img_width\" height=\"$img_height\" $img_html_attrs
			src=\"view_jpeg_photo.php?file=" . basename($jpeg_filename) . "\" /><br />\n";
		if( $draw_bytes_and_size ) {
			echo "<small>" . number_format($jpeg_data_size) . " bytes. ";
			echo "$width x $height pixels.<br /></small>\n\n";
		}

		if( $draw_delete_buttons )
		{ ?>
			<!-- JavaScript function deleteJpegPhoto() to be defined later by calling script -->
			<a href="javascript:deleteAttribute( '<?php echo $attr_name; ?>' );" style="color:red; font-size: 75%">Delete Photo</a>
		<?php }
	}
	echo "</center></td></table>\n\n";

	// If they have misconfigured their config.php, use default values
	if( ! isset( $jpeg_tmp_keep_time ) )
		$jpeg_tmp_keep_time = 120;

	// If they set keep time to 0, we up it to 10 to allow the browser to fetch it before it is deleted.
	if( $jpeg_tmp_keep_time == 0 )
		$jpeg_tmp_keep_time = 10;

	// delete old jpeg files.
	$jpegtmp_wildcard = "/^pla/";
	$handle = opendir($jpeg_temp_dir);
	while( ($file = readdir($handle) ) != false ) {
		if( preg_match( $jpegtmp_wildcard, $file ) ) {
			$file = "$jpeg_temp_dir/$file";
			if( (time() - filemtime($file) ) > $jpeg_tmp_keep_time )
				@unlink( $file );
		}
	}
	closedir($handle);
}

/**
 * Gets the root DN of the specified server_id, or false if it
 * can't find it (ie, the server won't give it to us). This is 
 * used when the user leaves the $servers[$i]['base'] value empty
 * to auto-determine the root DN.
 *
 * Tested with OpenLDAP 2.0, Netscape iPlanet, and Novell eDirectory 8.7 (nldap.com)
 * Please report any and all bugs!!
 *
 * @param int $server_id The ID of the server whose root DN to fetch.
 * @return mixed The root DN of the server on success (string) or false on error.
 */
function try_to_get_root_dn( $server_id, $ds = null )
{
	if( is_null( $ds ) ) {
		if( ! check_server_id( $server_id ) )
			return false;

		if( isset( $_SESSION[ "pla_root_dn_$server_id" ] ) )
			return $_SESSION[ "pla_root_dn_$server_id" ];

		if( ! have_auth_info( $server_id ) )
			return false;

		$ds = pla_ldap_connect( $server_id );
		if ( pla_ldap_connection_is_error( $ds, false ) )
			return false;
	}

	$r = @ldap_read( $ds, '', 'objectClass=*', array( 'namingContexts' ) );
	if( ! $r )
		return false;

	$r = @ldap_get_entries( $ds, $r );
	if( isset( $r[0]['namingcontexts'][0] ) ) {
		$root_dn = $r[0]['namingcontexts'][0];
		$_SESSION[ "pla_root_dn_$server_id" ] = $root_dn;
		return $root_dn;
	} else {
		return false;
	}
}

/**
 * Hashes a password and returns the hash based on the specified enc_type. 
 *
 * @param string $password_clear The password to hash in clear text.
 * @param string $enc_type Standard LDAP encryption type which must be one of
 *          crypt, md5, md5crypt, sha, smd5, ssha, or clear.
 * @return string The hashed password.
 */
function password_hash( $password_clear, $enc_type )
{
	global $lang;
    $enc_type = strtolower( $enc_type );
    switch( $enc_type )
    {
        case 'crypt':
            $new_value = '{CRYPT}' . crypt( $password_clear, random_salt(2) );
            break;
        case 'md5':
            $new_value = '{MD5}' . base64_encode( pack( 'H*' , md5( $password_clear) ) );
            break;
        case 'md5crypt':
            if( ! defined( 'CRYPT_MD5' ) || 0 == CRYPT_MD5 )
                pla_error( $lang['install_not_support_md5crypt'] );
            $new_value = '{CRYPT}' . crypt( $password_clear , '$1$' . random_salt(9) );
            break;
        case 'blowfish':
            if( ! defined( 'CRYPT_BLOWFISH' ) || 0 == CRYPT_BLOWFISH )
                pla_error( $lang['install_not_support_blowfish'] );
            $new_value = '{CRYPT}' . crypt( $password_clear , '$2$' . random_salt(13) );
            break;
        case 'sha':
            if( function_exists( 'mhash' ) ) {
                $new_value = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $password_clear) );
            } else {
                pla_error( $lang['install_no_mash'] );
            }
            break;
        case 'ssha':
            if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
                mt_srand( (double) microtime() * 1000000 );
                $salt = mhash_keygen_s2k( MHASH_SHA1, $password_clear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
                $new_value = "{SSHA}".base64_encode( mhash( MHASH_SHA1, $password_clear.$salt ).$salt );
            } else {
                pla_error( $lang['install_no_mash'] );
            }
            break;
        case 'smd5':
            if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
                mt_srand( (double) microtime() * 1000000 );
                $salt = mhash_keygen_s2k( MHASH_MD5, $password_clear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
                $new_value = "{SMD5}".base64_encode( mhash( MHASH_MD5, $password_clear.$salt ).$salt );
            } else {
                pla_error( $lang['install_no_mash'] );
            }
            break;
        case 'clear':
        default:
            $new_value = $password_clear;
	}
	return $new_value;
}

/**
 * Given a clear-text password and a hash, this function determines if the clear-text password
 * is the password that was used to generate the hash. This is handy to verify a user's password
 * when all that is given is the hash and a "guess".
 * @param String $hash The hash.
 * @param String $clear The password in clear text to test.
 * @return Boolean True if the clear password matches the hash, and false otherwise.
 */
function password_check( $cryptedpassword, $plainpassword )
{
    //echo "password_check( $cryptedpassword, $plainpassword )\n";
    if( preg_match( "/{([^}]+)}(.*)/", $cryptedpassword, $cypher ) ) {
        $cryptedpassword = $cypher[2];
        $_cypher = strtolower($cypher[1]);
    } else  {
        $_cypher = NULL;
    }

    switch( $_cypher )
    {
        // SSHA crypted passwords
        case 'ssha':
            $hash = base64_decode($cryptedpassword);
            $salt = substr($hash, -4);
            $new_hash = base64_encode( mhash( MHASH_SHA1, $plainpassword.$salt).$salt );
            if( strcmp( $cryptedpassword, $new_hash ) == 0 )
                return true;
            else
                return false;
            break;
        // Salted MD5
        case 'smd5':
            $hash = base64_decode($cryptedpassword);
            $salt = substr($hash, -4);
            $new_hash = base64_encode( mhash( MHASH_MD5, $plainpassword.$salt).$salt );
            if( strcmp( $cryptedpassword, $new_hash ) == 0)
                return true;
            else
                return false;
            break;
        // SHA crypted passwords
        case 'sha':
            if( 0 == strcasecmp( password_hash($plainpassword,'sha' ), "{SHA}".$cryptedpassword ) )
                return true;
            else
                return false;
            break;
        // MD5 cryped passwords
        case 'md5':
            if( 0 == strcasecmp( password_hash( $plainpassword,'md5' ), "{MD5}".$cryptedpassword ) )
                return true;
            else
                return false;
            break;
        // Crypt passwords
        case 'crypt':
            // Check if it's an crypted md5
            if( strstr( $cryptedpassword, '$1$' ) ) {
                list(,$type,$salt,$hash) = explode('$',$cryptedpassword);
                if( crypt( $plainpassword, '$1$' .$salt ) == $cryptedpassword )
                    return true;
                else
                    return false;
            } 
            // Password is plain crypt
            else {
                if( crypt($plainpassword, $cryptedpassword ) == $cryptedpassword )
                    return true;
                else
                    return false;
            }
            break;
        // No crypt is given assume plaintext passwords are used
        default:
            if( $plainpassword == $cryptedpassword )
                return true;
            else
                return false;
            break;
    }
}

function get_enc_type( $user_password )
{
    /* Capture the stuff in the { } to determine if this is crypt, md5, etc. */
    $enc_type = null;
    if( preg_match( "/{([^}]+)}/", $user_password, $enc_type) ) 
        $enc_type = strtolower( $enc_type[1] ); 
    else
        return null;

    /* handle crypt types */
    if( 0 == strcasecmp( $enc_type, 'crypt') ) {
        $salt = null;
        if( preg_match( "/{[^}]+}\\$(.)\\$/", $user_password, $salt) )
            $salt = $salt[1];
        else
            $salt = null;
        switch( $salt ) {
            case '':   // CRYPT_STD_DES
                $enc_type = "crypt";
                break;
            case '1':   // CRYPT_MD5
                $enc_type = "md5crypt";
                break;
            case '2':   // CRYPT_BLOWFISH
                $enc_type = "blowfish";
                break;
            default:
                $enc_type = "crypt";
        }
    }
    return $enc_type;
}

/**
 * Gets the default enc_type configured in config.php for the server indicated by $server_id;
 * @param int $server_id The ID of the server of interest.
 * @return String The enc_type, like 'sha', 'md5', 'ssha', 'md5crypt', for example.
 */
function get_default_hash( $server_id )
{
    global $servers;
    if( isset( $servers[$server_id]['default_hash'] ) )
        return $servers[$server_id]['default_hash'];
    else
        return null;
}

/**
 * Returns the phpLDAPadmin version currently running. The version
 * is read from the file named VERSION.
 *
 * @return string The current version as read from the VERSION file.
 */
function pla_version()
{
	if( ! file_exists( realpath( 'VERSION' ) ) )
		return 'unknown version';

	$f = fopen( realpath( 'VERSION' ), 'r' );
	$version = fread( $f, filesize( realpath( 'VERSION' ) ) );
	fclose( $f );
	return $version;
}

/** 
 * Draws an HTML browse button which, when clicked, pops up a DN chooser dialog.
 * @param string $form_element The name of the form element to which this chooser
 *         dialog will publish the user's choice. The form element must be a member
 *         of a form with the "name" or "id" attribute set in the form tag, and the element
 *         must also define "name" or "id" for JavaScript to uniquely identify it.
 *         Example $form_element values may include "creation_form.container" or 
 *         "edit_form.member_uid". See /templates/modification/default.php for example usage.
 * @param bool $include_choose_text (optional) If true, the function draws the localized text "choose" to the right of the button.
 */
function draw_chooser_link( $form_element, $include_choose_text=true )
{
	global $lang;
	$href = "javascript:dnChooserPopup('$form_element');";
	$title = $lang['chooser_link_tooltip'];
	echo "<nobr><a href=\"$href\" title=\"$title\"><img class=\"chooser\" src=\"images/find.png\" /></a>";
	if( $include_choose_text )
		echo "<span class=\"x-small\"><a href=\"$href\" title=\"$title\">". $lang['fbrowse'] ."</a></span>";
	echo "</nobr>";
}

/**
 * Explode a DN into an array of its RDN parts. This function is UTF-8 safe
 * and replaces the buggy PHP ldap_explode_dn() which does not properly
 * handle UTF-8 DNs and also causes segmentation faults with some inputs.
 *
 * @param string $dn The DN to explode.
 * @param int $with_attriutes (optional) Whether to include attribute names (see http://php.net/ldap_explode_dn for details)
 *
 * @return array An array of RDN parts of this format:
 * <code>
 *   Array
 *    (
 *       [0] => uid=ppratt
 *       [1] => ou=People
 *       [2] => dc=example
 *       [3] => dc=com
 *    )
 * </code>
 */
function pla_explode_dn( $dn, $with_attributes=0 )
{
  // replace "\," with the hexadecimal value for safe split
  $var = preg_replace("/\\\,/","\\\\\\\\2C",$dn);

  // split the dn
  $result = explode(",",$var);
  
  //translate hex code into ascii for display
  foreach( $result as $key => $value )
    $result[$key] = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);
  
  return $result;
}

/**
 * Fetches the URL for the specified item. This is a convenience function for 
 * fetching project HREFs (like bugs)
 *
 * @param string $type One of "open_bugs", "add_bug", "donate", or "add_rfe"
 *            (rfe = request for enhancement)
 * @return string The URL to the requested item.
 */
function get_href( $type )
{
    /* We don't use SourceForge IDs any more
	$group_id = "61828";
	$bug_atid = "498546";
	$rfe_atid = "498549";
    */
	switch( $type ) {
	case 'open_bugs': return "http://www.phpldapadmin.com/bugs/";
	case 'add_bug': return "http://www.phpldapadmin.com/bugs/bug_report_page.php";
	case 'add_rfe': return get_href( 'add_bug' );
    case 'donate': return "donate.php";
	default: return null;
	}
}

/**
 * Returns the current time as a double (including micro-seconds).
 *
 * @return double The current time in seconds since the beginning of the UNIX epoch (Midnight Jan. 1, 1970)
 */
function utime ()
{
	$time = explode( " ", microtime());
 	$usec = (double)$time[0];
 	$sec = (double)$time[1];
 	return $sec + $usec;
}

/**
 * Converts an array to a query-string with the option to exclude certain variables 
 * from the returned query string. This is convenient if callers want to convert the
 * current GET query string or POST array into a string and replace certain 
 * variables with their own.
 * 
 * @param array $array The associate array to convert whose form is such that the keys are the 
 *          names of the variables and the values are said variables' values like this:
 *          <code>
 *             Array
 *                (
 *                   [server_id] = 0,
 *                   [dn] = "dc=example,dc=com",
 *                   [attr] = "sn"
 *                 )
 *          </code>
 *          This will produce a string like this: "server_id=0&dn=dc=example,dc=com&attr=sn"
 * @param array $exclude_vars (optional) An array of variables to exclude in the resulting string
 * @param bool $url_encode_ampersands (optional) By default, this function encodes all ampersand-separators
 *             as &amp; but callers may dislabe this by specifying false here. For example, URLs on HTML
 *             pages should encode the ampersands but URLs in header( "Location: http://example.com" ) should
 *             not be encoded.
 * @return string The string created from the array.
 */
function array_to_query_string( $array, $exclude_vars=array(), $url_encode_ampersands=true )
{
	if( ! is_array( $array ) )
		return '';
	if( ! $array )
		return '';
	$str = '';
	$i=0;
	foreach( $array as $name => $val ) {
		if( ! in_array( $name, $exclude_vars ) ) {
			if( $i>0 )
				if( $url_encode_ampersands )
					$str .= '&amp;';
				else
					$str .= '&';
			$str .= urlencode( $name ) . '=' . urlencode( $val );
			$i++;
		}
	}
	return $str;
}

/**
 * Gets whether the admin has configured phpLDAPadmin to show the "Create New" link in the tree viewer.
 * If $servers[$server_id]['show_create'] is NOT set, then default to show the Create New item.
 * If $servers[$server_id]['show_create'] IS set, then return the value (it should be true or false).
 *
 * @param int $server_id The ID of the server of interest
 * @return bool True if the feature is enabled and false otherwise.
 */
function show_create_enabled( $server_id )
{
	global $servers;
	if( isset( $servers[$server_id]['show_create'] )) 
		return $servers[$server_id]['show_create'];
	else
		return true;
}

/**
 * Reverses a DN such that the top-level RDN is first and the bottom-level RDN is last
 * For example:
 * <code>
 *   cn=Brigham,ou=People,dc=example,dc=com
 * </code>
 * Becomes: 
 * <code>
 *   dc=com,dc=example,ou=People,cn=Brigham
 * </code>
 * This makes it possible to sort lists of DNs such that they are grouped by container.
 *
 * @param string $dn The DN to reverse
 *
 * @return string The reversed DN
 *
 * @see pla_compare_dns
 */
function pla_reverse_dn($dn)
{
	foreach (pla_explode_dn($dn) as $key => $branch) {

		// pla_expode_dn returns the array with an extra count attribute, we can ignore that.
		if ( $key === "count" ) continue;

		if (isset($rev)) {
			$rev = $branch.",".$rev;
		} else {
			$rev = $branch;
		}
	}
	return $rev;
}

/**
 * Determins if the specified attribute is contained in the $unique_attrs list
 * configured in config.php.
 * @return Bool True if the specified attribute is in the $unique_attrs list and false
 *                  otherwise.
 */
function is_unique_attr( $attr_name )
{
    global $unique_attrs;
    if( isset( $unique_attrs ) && is_array( $unique_attrs ) ) {
        foreach( $unique_attrs as $attr )
            if( 0 === strcasecmp( $attr_name, $attr ) )
                return true;
    }
    return false;
}

/*
 * This function will check whether the value for an attribute being changed
 * is already assigned to another DN.
 *
 * Inputs:
 * - server_id
 * - dn that is being changed
 * - attribute being changed
 * - new values for the attribute
 *
 * Returns the bad value, or null if all values are OK
 */
function checkUniqueAttr( $server_id, $dn, $attr_name, $new_value )
{
	global $servers, $lang;
    $server_name = $servers[ $server_id ][ 'name' ];

	// Is this attribute in the unique_attrs list?
	if ( is_unique_attr( $attr_name ) ) {

		// Search the tree and make sure that attribute doesnt already exist to somebody else.

		// Check see and use our alternate uid_dn and password if we have it.
		$unique_attrs_dn = $servers[ $server_id ][ 'unique_attrs_dn' ];
		$unique_attrs_pass = $servers[ $server_id ][ 'unique_attrs_dn_pass' ];
		$need_to_unbind = false;

		if ( isset( $unique_attrs_dn ) && $unique_attrs_dn != '' && isset( $uniqe_attrs_pass ) )
		{
			$con = @ldap_connect( $servers[$server_id]['host'], $servers[$server_id]['port'] );

 			@ldap_set_option( $con, LDAP_OPT_PROTOCOL_VERSION, 3 );

			// Bind with the alternate ID.
			$res = @ldap_bind( $con, $unuque_attrs_dn, $unique_attrs_pass );

			if (! $res) pla_error( sprintf( $lang['unique_attrs_invalid_credential'] , $server_name ) );

			$need_to_unbind = true;

		} else {
			$con = pla_ldap_connect($server_id);
		}

		// Should this be in a function?
		$base_dn = $servers[ $server_id ][ 'base' ];
		if( ! $base_dn )
			$base_dn = try_to_get_root_dn( $server_id );

		// Build our search filter to double check each attribute.
		$searchfilter = "(|";
		foreach ($new_value as $val) {
			$searchfilter .= "($attr_name=$val)";
		}
		$searchfilter .= ")";

		// Do we need a sanity check to just in case $new_value was null and hence the search string is bad?

		// Do the search
		$search = @ldap_search( $con, $base_dn, $searchfilter, array('dn'), 0, 0, 0, LDAP_DEREF_ALWAYS);
		$search = ldap_get_entries( $con, $search );

		foreach ($search as $result) {
			// Skip the count result and go to the array.
			if (! is_array($result)) continue;

			// If one of the attributes is owned to somebody else, then we may as well die here.
			if ($result['dn'] != $dn) {
				return $val;
			}
		}

		if ( $need_to_unbind ) {
			$res = @ldap_unbind( $con );
		}

		// If we get here, then it must be OK?
		return;

	} else {
		return;
	}
}

function sortAttrs($a,$b) {
	global $friendly_attrs;

	$a = strtolower( (isset($friendly_attrs[ strtolower( $a ) ]) ? $friendly_attrs[ strtolower( $a ) ] : $a));
	$b = strtolower( (isset($friendly_attrs[ strtolower( $b ) ]) ? $friendly_attrs[ strtolower( $b ) ] : $b));
	return strcmp ($a, $b);
}

function userIsMember($server_id,$user,$group) {
	$group = get_object_attrs( $server_id, $group, $deref=LDAP_DEREF_NEVER );
	return (is_array($group) ? (in_array($user,$group['uniqueMember'])) : false);
}

function arrayLower($array) {
	foreach ($array as $key => $value) {
		$newarray[$key] = strtolower($value);
	}
	return $newarray;
}

/**
 * Strips all slashes from the specified array in place (pass by ref).
 * @param Array $array The array to strip slashes from, typically one of 
 *             $_GET, $_POST, or $_COOKIE.
 */
function array_stripslashes(&$array)
{
    if( is_array( $array ) )
        while ( list( $key ) = each( $array ) ) 
            if ( is_array( $array[$key] ) && $key != $array ) 
                array_stripslashes( $array[$key] );
            else 
                $array[$key] = stripslashes( $array[$key] );
}

/**
 * Gets a HTTP value via $_GET or $_POST
 *
 * @param string $val The HTTP value too look for
 * @param any $default The default return value, if failed to get (default = false)
 * @param bool $trim Trim a string value (default = true)
 * @return string The HTTP value or the $default
 */
function http_get_value( $val, $default = false, $trim = true )
{
	$result = $default;
	if( array_key_exists( $val, $_GET ) )
		$result = $_GET[ $val ];
	elseif( array_key_exists( $val, $_POST ) )
		$result = $_POST[ $val ];
	if( ( $result !== $default ) && ( $trim === true ) && is_string( $result ) )
		$result = trim( $result );
	return $result;
}

/**
 * Gets the USER_AGENT string from the $_SERVER array, all in lower case in
 * an E_NOTICE safe manner.
 * @return String The user agent string as reported by the browser.
 */
function get_user_agent_string()
{
    if( isset( $_SERVER['HTTP_USER_AGENT'] ) )
        return strtolower( $_SERVER['HTTP_USER_AGENT'] );
    else
        return false;
}

/**
 * Determines whether the browser's operating system is UNIX (or something like UNIX).
 * @return boolean True if the brower's OS is UNIX, false otherwise.
 */
function is_browser_os_unix()
{
    $agent = get_user_agent_string();
    if( ! $agent )
        return false;
    $unix_agent_strs = array(
            'sunos',
            'sunos 4',
            'sunos 5',
            'i86',
            'irix',
            'irix 5',
            'irix 6',
            'irix6',
            'hp-ux',
            '09.',
            '10.',
            'aix',
            'aix 1',
            'aix 2',
            'aix 3',
            'aix 4',
            'inux',
            'sco',
            'unix_sv',
            'unix_system_v',
            'ncr',
            'reliant',
            'dec',
            'osf1',
            'dec_alpha' ,
            'alphaserver' ,
            'ultrix' ,
            'alphastation',
            'sinix',
            'freebsd',
            'bsd',
            'x11',
            'vax',
            'openvms'
                );
            foreach( $unix_agent_strs as $agent_str )
                if( strpos( $agent, $agent_str ) !== false )
                    return true;
            return false;
}

/**
 * Determines whether the browser's operating system is Windows.
 * @return boolean True if the brower's OS is Windows, false otherwise.
 */
function is_browser_os_windows()
{
    $agent = get_user_agent_string();
    if( ! $agent )
        return false;
    $win_agent_strs = array(
            'win',
            'win95',
            'windows 95',
            'win16',
            'windows 3.1',
            'windows 16-bit',
            'windows',
            'win31',
            'win16',
            'winme',
            'win2k',
            'winxp',
            'win98',
            'windows 98',
            'win9x',
            'winnt',
            'windows nt',
            'win32',
            'win32',
            '32bit'
            );
    foreach( $win_agent_strs as $agent_str )
        if( strpos( $agent, $agent_str ) !== false )
            return true;
    return false;
}

/**
 * Determines whether the browser's operating system is Macintosh.
 * @return boolean True if the brower's OS is mac, false otherwise.
 */
function is_browser_os_mac()
{
    $agent = get_user_agent_string();
    if( ! $agent )
        return false;
    $mac_agent_strs = array(
            'mac',
            '68000',
            'ppc',
            'powerpc'
            );
    foreach( $mac_agent_strs as $agent_str )
        if( strpos( $agent, $agent_str ) !== false )
            return true;
    return false;
}

/**
 * Return posix group entries.
 * @return Array An associative array of posix group entries with attributes as keys, and values as values.
 * @param int $server_id The ID of the server to search.
 * @param string $base_dn The base of the search.
 */
function get_posix_groups( $server_id , $base_dn = NULL ){
  global $servers;
  if( is_null( $base_dn ) )
    $base_dn = isset( $servers[$server_id]['base'] ) ? $servers[$server_id]['base'] : try_to_get_root_dn( $server_id );
  
  $results = pla_ldap_search( $server_id, "objectclass=posixGroup", $base_dn, array() );
  if( !$results )
    return array();
  else
    return $results;
}

function get_default_search_display()
{
    global $default_search_display;
    if( ! isset( $default_search_display ) || is_null( $default_search_display ) )
        return 'list';
    elseif( 0 == strcasecmp( $default_search_display, 'list' ) )
        return 'list';
    elseif( 0 == strcasecmp( $default_search_display, 'table' ) )
        return 'table';
    else
        pla_error( sprintf( $lang['bad_search_display'], htmlspecialchars( $default_search_display ) ) );
}


/**
 * Checks if a string exists in an array, ignoring case.
 */
function in_array_ignore_case( $needle, $haystack )
{
    if( ! is_array( $haystack ) )
        return false;
    if( ! is_string( $needle ) )
        return false;
    foreach( $haystack as $element )
        if( is_string( $element ) && 0 == strcasecmp( $needle, $element ) )
            return true;
    return false;
}

/**
 * String padding
 *
 * @param   string  input string
 * @param   integer length of the result
 * @param   string  the filling string
 * @param   integer padding mode
 *
 * @return  string  the padded string
 *
 * @access  public (taken from the phpMyAdmin source)
 */
function full_str_pad($input, $pad_length, $pad_string = '', $pad_type = 0) {
    $str = '';
    $length = $pad_length - strlen($input);
    if ($length > 0) { // str_repeat doesn't like negatives
        if ($pad_type == STR_PAD_RIGHT) { // STR_PAD_RIGHT == 1
            $str = $input.str_repeat($pad_string, $length);
        } elseif ($pad_type == STR_PAD_BOTH) { // STR_PAD_BOTH == 2
            $str = str_repeat($pad_string, floor($length/2));
            $str .= $input;
            $str .= str_repeat($pad_string, ceil($length/2));
        } else { // defaults to STR_PAD_LEFT == 0
            $str = str_repeat($pad_string, $length).$input;
        }
    } else { // if $length is negative or zero we don't need to do anything
        $str = $input;
    }
    return $str;
}

/**
 * Gets the user configured $blowfish_secret from config.php.
 */
function get_blowfish_secret()
{
    global $blowfish_secret;
    if( isset( $blowfish_secret ) ) {
        if( trim( $blowfish_secret ) == '' ) 
            return null;
        else
            return $blowfish_secret;
    } else
        return null;
}

/**
 * Encryption using blowfish algorithm
 *
 * @param   string  original data
 * @param   string  the secret
 *
 * @return  string  the encrypted result
 *
 * @access  public
 *
 * @author  lem9 (taken from the phpMyAdmin source)
 */
function pla_blowfish_encrypt( $data, $secret=null ) 
{
    include_once './blowfish.php';
    if( null === $secret ) {
        $secret = get_blowfish_secret();
        if( null === $secret )
            pla_error( 'phpLDAPadmin cannot safely encrypt your sensitive information, because $blowfish_secret is not set in config.php. You need to edit config.php and set $blowfish_secret to some secret string now.' );
    }
    $pma_cipher = new Horde_Cipher_blowfish;
    $encrypt = '';
    for ($i=0; $i<strlen($data); $i+=8) {
        $block = substr($data, $i, 8);
        if (strlen($block) < 8) {
            $block = full_str_pad($block,8,"\0", 1);
        }
        $encrypt .= $pma_cipher->encryptBlock($block, $secret);
    }
    return base64_encode($encrypt);
}

/**
 * Decryption using blowfish algorithm
 *
 * @param   string  encrypted data
 * @param   string  the secret
 *
 * @return  string  original data
 *
 * @access  public
 *
 * @author  lem9 (taken from the phpMyAdmin source)
 */
function pla_blowfish_decrypt( $encdata, $secret=null )
{
    // This cache gives major speed up for stupid callers :)
    static $cache = array();
    if( isset( $cache[$encdata] ) )
        return $cache[$encdata];

    include_once './blowfish.php';
    if( null === $secret ) {
        $secret = get_blowfish_secret();
        if( null === $secret )
            pla_error( 'phpLDAPadmin cannot safely decrypt your sensitive information, because $blowfish_secret is not set in config.php. You need to edit config.php and set $blowfish_secret to some secret string now.' );
    }
    $pma_cipher = new Horde_Cipher_blowfish;
    $decrypt = '';
    $data = base64_decode($encdata);
    for ($i=0; $i<strlen($data); $i+=8) {
        $decrypt .= $pma_cipher->decryptBlock(substr($data, $i, 8), $secret);
    }
    $return = trim($decrypt);
    $cache[$encdata] = $return;
    return $return;
}

/**
 * Gets the user configured $tree_display_format from config.php
 */
function get_tree_display_format()
{
    global $tree_display_format;
    if( ! isset( $tree_display_format ) || '' == trim( $tree_display_format ) )
        $tree_display_format = "%rdn";
    return $tree_display_format;
}

/**
 * Gets a DN string using the user-configured tree_display_format string to format it.
 */
function draw_formatted_dn( $server_id, $dn )
{
    $format = get_tree_display_format();
    preg_match_all( "/%[a-zA-Z_0-9]+/", $format, $tokens );
    $tokens = $tokens[0];
    foreach( $tokens as $token ) {
        if( 0 == strcasecmp( $token, '%dn' ) )
            $format = str_replace( $token, pretty_print_dn( $dn ), $format );
        elseif( 0 == strcasecmp( $token, '%rdn' ) )
            $format = str_replace( $token, pretty_print_dn( get_rdn( $dn ) ), $format );
        elseif( 0 == strcasecmp( $token, '%rdnvalue' ) ) {
            $rdn = get_rdn( $dn );
            $rdn_value = explode( '=', $rdn, 2 );
            $rdn_value = $rdn_value[1];
            $format = str_replace( $token, $rdn_value, $format );
        } else {
            $attr_name = str_replace( '%', '', $token );
            $attr_values = get_object_attr( $server_id, $dn, $attr_name );
            if( null == $attr_values )
                $display = 'none';
            elseif( is_array( $attr_values ) )
                $display = htmlspecialchars( implode( ', ',  $attr_values ) );
            else
                $display = htmlspecialchars( $attr_values );
            $format = str_replace( $token, $display, $format );
        }
    }
    echo $format;
}

?>