File: entrydisplay.c

package info (click to toggle)
389-dsgw 1.1.11-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 6,348 kB
  • sloc: ansic: 20,048; sh: 11,896; makefile: 257; cpp: 6
file content (3159 lines) | stat: -rw-r--r-- 94,308 bytes parent folder | download | duplicates (2)
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
/** --- BEGIN COPYRIGHT BLOCK ---
 * This Program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 2 of the License.
 * 
 * This Program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA.
 * 
 * 
 * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
  --- END COPYRIGHT BLOCK ---  */
/*
 * entrydisplay.c --  output entries one at a time or in a list -- HTTP gateway 
 */

#include "dsgw.h"
#include "dbtdsgw.h"
#include <ldap.h> /* ldap_utf8* */
#include <unicode/udat.h>
#include <unicode/utypes.h>
#include <unicode/unum.h>
#include <unicode/ucal.h>

/*
 * Note: the value of the following DSGW_ATTRHTML_XXX #defines must match
 * their position in the attrhtmltypes[] and attrhtmlvals[] arrays.
 */
#define DSGW_ATTRHTML_HIDDEN		0
#define DSGW_ATTRHTML_TEXT		1
#define DSGW_ATTRHTML_TEXTAREA		2
#define DSGW_ATTRHTML_RADIO		3
#define DSGW_ATTRHTML_CHECKBOX		4
#define DSGW_ATTRHTML_PASSWORD		5
static char *attrhtmltypes[] = {
	"hidden",
	"text",
	"textarea",
	"radio",
	"checkbox",
	"password",
	NULL
};
static int attrhtmlvals[] = {
	DSGW_ATTRHTML_HIDDEN,
	DSGW_ATTRHTML_TEXT,
	DSGW_ATTRHTML_TEXTAREA,
	DSGW_ATTRHTML_RADIO,
	DSGW_ATTRHTML_CHECKBOX,
	DSGW_ATTRHTML_PASSWORD,
};

#define DSGW_ATTROPT_SORT	0x00000001
#define DSGW_ATTROPT_NOLINK	0x00000002
#define DSGW_ATTROPT_DNTAGS	0x00000004
#define DSGW_ATTROPT_DATEONLY	0x00000008	/* only for syntax=time */
#define DSGW_ATTROPT_READONLY	0x00000010	/* over-rides ..._EDITABLE */
#define DSGW_ATTROPT_DNPICKER	0x00000020	/* display dns for find-n-add */
#define DSGW_ATTROPT_UNIQUE	0x00000040	/* attr values must be unique */
#define DSGW_ATTROPT_LINK	0x00000080	/* link to attribute value */
#define DSGW_ATTROPT_TYPEONLY	0x00000100	/* retrieve attr. type only */
#define DSGW_ATTROPT_NO_ENTITIES  0x00000200	/* don't use entities */
#define DSGW_ATTROPT_HEX		0x00000400	/* display as hex value */
#define DSGW_ATTROPT_DECIMAL	0x00000800	/* display as decimal value */
#define DSGW_ATTROPT_QUOTED	0x00001000	/* quote the result */
#define DSGW_ATTROPT_ENTITIES   0x00002000	/* force the use of entities e.g. urls in javascript */
#define DSGW_ATTROPT_EDITABLE	0x10000000	/* not exposed in HTML */
#define DSGW_ATTROPT_ADDING	0x20000000	/* not exposed in HTML */
#define DSGW_ATTROPT_LINK2EDIT	0x40000000	/* not exposed in HTML */
static char *attroptions[] = {
	"sort",
	"nolink",
	"dntags",
	"dateonly",
	"readonly",
	"dnpicker",
	"unique",
	"link",
	"typeonly",
	"noentities",
	"hex",
	"decimal",
	"quoted",
	"entities",
	NULL
};

static unsigned long attroptvals[] = {
	DSGW_ATTROPT_SORT,
	DSGW_ATTROPT_NOLINK,
	DSGW_ATTROPT_DNTAGS,
	DSGW_ATTROPT_DATEONLY,
	DSGW_ATTROPT_READONLY,
	DSGW_ATTROPT_DNPICKER,
	DSGW_ATTROPT_UNIQUE,
	DSGW_ATTROPT_LINK,
	DSGW_ATTROPT_TYPEONLY,
	DSGW_ATTROPT_NO_ENTITIES,
	DSGW_ATTROPT_HEX,
	DSGW_ATTROPT_DECIMAL,
	DSGW_ATTROPT_QUOTED,
	DSGW_ATTROPT_ENTITIES,
};

#define DSGW_ATTRARG_DN		"dn"
#define DSGW_ATTRARG_ATTR	"attr"
#define DSGW_ATTRARG_SYNTAX	"syntax"
#define DSGW_ATTRARG_HTMLTYPE	"type"
#define DSGW_ATTRARG_OPTIONS	"options"
#define DSGW_ATTRARG_DEFAULT	"defaultvalue"
#define DSGW_ATTRARG_WITHIN	"within"	/* overrides href & hrefextra */
#define DSGW_ATTRARG_HREF	"href"
#define DSGW_ATTRARG_HREFEXTRA	"hrefextra"
#define DSGW_ATTRARG_LABEL	"label"		/* only used with syntax=dn */
#define DSGW_ATTRARG_DNCOMP	"dncomponents"	/* only used with syntax=dn */
#define DSGW_ATTRARG_TRUESTR	"true"		/* only used with syntax=bool */
#define DSGW_ATTRARG_FALSESTR	"false"		/* only used with syntax=bool */
#define DSGW_ATTRARGS_SIZE	"size"
#define DSGW_ATTRARGS_ROWS	"rows"
#define DSGW_ATTRARGS_COLS	"cols"
#define DSGW_ATTRARGS_NUMFIELDS	"numfields"
#define DSGW_ATTRARGS_VALUE	"value"
#define DSGW_ATTRARG_MIMETYPE	"mimetype"
#define	DSGW_ATTRARG_SCRIPT	"script"

#define DSGW_ARG_BUTTON_PROMPT		"prompt"
#define DSGW_ARG_BUTTON_TEMPLATE	"template"
#define DSGW_ARG_BUTTON_CHECKSUBMIT	"checksubmit"
#define DSGW_ARG_BUTTON_TOPIC		"topic"
#define DSGW_ARG_DNEDIT_LABEL		"label"
#define DSGW_ARG_DNEDIT_TEMPLATE	"template"
#define DSGW_ARG_DNEDIT_ATTR		"attr"
#define DSGW_ARG_DNEDIT_DESC		"desc"

#define	DSGW_ARG_FABUTTON_LABEL		"label"
#define	DSGW_ARG_FABUTTON_ATTRNAME	"attr"
#define	DSGW_ARG_FABUTTON_ATTRDESC	"attrdesc"

#define DSGW_ARG_AVSET_SET		"set"

/*
 * structure used simply to avoid passing a lot of parameters in call to
 * the attribute syntax handlers
 */
struct dsgw_attrdispinfo {
    struct attr_handler	*adi_handlerp;
    char		*adi_attr;
    int			adi_argc;
    char		**adi_argv;
    struct berval	**adi_vals;
    struct berval	*adi_rdn; /* a copy of adi_vals[i] (possibly NULL) */
    int			adi_htmltype;
    unsigned long	adi_opts;
};
/* adi_rdn should be generalized, to support an RDN
   that contains several values of one attribute type.
*/

typedef void (*attrdisplay)( struct dsgw_attrdispinfo *adip );
typedef void (*attredit)( struct dsgw_attrdispinfo *adip );

struct attr_handler {
    char		*ath_syntax;	/* dn, tel, cis, etc. */
    attrdisplay		ath_display;	/* function to display values */
    attredit		ath_edit;	/* function to display for editing */
    int			ath_compare;	/* compare function */
};

/* functions local to this file */
static void append_to_array( char ***ap, int *countp, char *s );
static unsigned long get_attr_options( int argc, char **argv );
static void output_prelude( dsgwtmplinfo *tip );
static void output_nonentry_line( dsgwtmplinfo *tip, char *line );
static struct attr_handler *syntax2attrhandler( char *syntax );
static int numfields( int argc, char **argv, int valcount );
static void element_sizes( int argc, char **argv, struct berval **vals, 
	int valcount, int *rowsp, int *colsp );
#define DSGW_TEXTOPT_FOCUSHANDLERS	0x0001
#define DSGW_TEXTOPT_CHANGEHANDLERS	0x0002
static void output_text_elements( int argc, char **argv, char *attr, 
	struct berval **vals, const char* rdn, char *prefix, int htmltype, 
	unsigned long opts );
static void output_textarea( int argc, char **argv, char *attr, 
	struct berval **vals, int valcount, char *prefix, unsigned long opts );
static void emit_value( char *val, int quote_html_specials );
static void output_text_checkbox_or_radio( struct dsgw_attrdispinfo *adip,
	char *prefix, int htmltype );
static void do_attribute( dsgwtmplinfo *tip, char *dn, unsigned long dispopts,
	int argc, char **argv );
static void do_orgchartlink( dsgwtmplinfo *tip, char *dn, unsigned long dispopts,
	int argc, char **argv );
static void do_attrvalset( dsgwtmplinfo *tip, char *dn, unsigned long dispopts,
	int argc, char **argv );
static void do_editbutton( char *dn, char *encodeddn, int argc, char **argv );
static void do_savebutton( unsigned long dispopts, int argc, char **argv );
static void do_deletebutton( int argc, char **argv );
static void do_editasbutton( int argc, char **argv );
static void do_dneditbutton( unsigned long dispopts, int argc, char **argv );
static void do_searchdesc( dsgwtmplinfo *tip, int argc, char **argv );
static void do_passwordfield( unsigned long dispopts, int argc, char **argv,
	char *fieldname );
static void do_helpbutton( unsigned long dispopts, int argc, char **argv );
static void do_closebutton( unsigned long dispopts, int argc, char **argv );
static void do_viewswitcher( char *template, char *dn, int argc, char **argv );
static int did_output_as_special( int argc, char **argv, struct berval *label,
	struct berval *val );
static char *time2text( char *ldtimestr, int dateonly );
static long gtime( struct tm *tm );
static int looks_like_dn( char *s );
static void do_std_completion_js( char *template, int argc, char **argv );
static int condition_is_true( int argc, char **argv, void *arg );
static struct berval ** dsgw_get_values( LDAP *ld, LDAPMessage *entry, 
				const char *target );
static char *dsgw_time(time_t secs_since_1970);

/* attribute syntax handler routines */
#if NEEDED_FOR_DEBUGGING
static void ntdomain_display( struct dsgw_attrdispinfo *adip );
#endif
static void ntuserid_display( struct dsgw_attrdispinfo *adip );
static void str_display( struct dsgw_attrdispinfo *adip );
static void str_edit( struct dsgw_attrdispinfo *adip );
static void dn_display( struct dsgw_attrdispinfo *adip );
static void dn_edit( struct dsgw_attrdispinfo *adip );
static void mail_display( struct dsgw_attrdispinfo *adip );
static void mls_display( struct dsgw_attrdispinfo *adip );
static void mls_edit( struct dsgw_attrdispinfo *adip );
static void binvalue_display( struct dsgw_attrdispinfo *adip );
static void url_display( struct dsgw_attrdispinfo *adip );
static void bool_display( struct dsgw_attrdispinfo *adip );
static void bool_edit( struct dsgw_attrdispinfo *adip );
static void time_display( struct dsgw_attrdispinfo *adip );


/* static variables */
#define DSGW_MOD_PREFIX_NORMAL	0
#define DSGW_MOD_PREFIX_UNIQUE	1
static char *replace_prefixes[] = { "replace_", "replace_unique_" };
static char *replace_mls_prefixes[] = { "replace_mls_", "replace_mls_unique_" };
static char *add_prefixes[] = { "add_", "add_unique_" };
static char *add_mls_prefixes[] = { "add_mls_", "add_mls_unique_" };

struct attr_handler attrhandlers[] = {
    { "cis",	str_display,	str_edit,	CASE_INSENSITIVE	},
    { "dn",	dn_display,	dn_edit,	CASE_INSENSITIVE	},
    { "mail",	mail_display,	str_edit,	CASE_INSENSITIVE	},
    { "mls",	mls_display,	mls_edit,	CASE_INSENSITIVE	},
    { "tel",	str_display,	str_edit,	CASE_INSENSITIVE	},
    { "url",	url_display,	str_edit,	CASE_EXACT       	},
    { "ces",	str_display,	str_edit,	CASE_EXACT       	},
    { "bool",	bool_display,	bool_edit,	CASE_INSENSITIVE	},
    { "time",	time_display,	str_edit,	CASE_INSENSITIVE	},
    { "ntuserid", ntuserid_display, str_edit,	CASE_INSENSITIVE	},
    { "ntgroupname", ntuserid_display, str_edit,	CASE_INSENSITIVE	},
    { "binvalue", binvalue_display, str_edit, CASE_INSENSITIVE	},
};
#define DSGW_AH_COUNT ( sizeof( attrhandlers ) / sizeof( struct attr_handler ))


static char *
template_filename( int tmpltype, char *template )
{
    char	*fn, *prefix, *suffix = ".html";

    if ( tmpltype == DSGW_TMPLTYPE_LIST ) {
	prefix = DSGW_CONFIG_LISTPREFIX;
    } else if ( tmpltype == DSGW_TMPLTYPE_EDIT ) {
	prefix = DSGW_CONFIG_EDITPREFIX;
    } else if ( tmpltype == DSGW_TMPLTYPE_ADD ) {
	prefix = DSGW_CONFIG_ADDPREFIX;
    } else {
	prefix = DSGW_CONFIG_DISPLAYPREFIX;
    }

    fn = dsgw_ch_malloc( strlen( prefix ) + strlen( template )
	    + strlen( suffix ) + 1 );
    sprintf( fn, "%s%s%s", prefix, template, suffix );

    return( fn );
}

static void
do_postedvalue( int argc, char **argv )
{
    dsgw_emits( "VALUE=\"" );
    dsgw_emit_cgi_var( argc, argv );
    dsgw_emits( "\"\n" );
}

static int
dsgw_display_line( dsgwtmplinfo *tip, char *line, int argc, char **argv )
{
    if ( dsgw_directive_is( line, DRCT_DS_POSTEDVALUE )) {
	do_postedvalue( argc, argv );
    } else if ( dsgw_directive_is( line, DRCT_DS_HELPBUTTON )) {
	do_helpbutton( tip->dsti_options, argc, argv );
    } else if ( dsgw_directive_is( line, DRCT_DS_CLOSEBUTTON )) {
	do_closebutton( tip->dsti_options, argc, argv );
    } else if ( dsgw_directive_is( line, DRCT_DS_OBJECTCLASS )) {
	/* omit objectClass lines */
    } else if ( dsgw_directive_is( line, DRCT_HEAD )) {
	dsgw_head_begin();
	dsgw_emits ("\n");
    } else {
	return 0;
    }
    return 1;
}

dsgwtmplinfo *
dsgw_display_init( int tmpltype, char *template, unsigned long options )
{
    dsgwtmplinfo	*tip;
    int			argc, attrcount, attrsonlycount, skip_line, in_entry;
    char		**argv, *attr, *filename, line[ BIG_LINE ];
    unsigned long	aopts;

    /* template is passed in from the user - make sure it looks like a valid name */
    if (!dsgw_valid_docname(template)) {
        dsgw_error( DSGW_ERR_BADFILEPATH, template, 
                    DSGW_ERROPT_EXIT, 0, NULL );
    }

    tip = (dsgwtmplinfo *)dsgw_ch_malloc( sizeof( dsgwtmplinfo ));
    memset( tip, 0, sizeof( dsgwtmplinfo ));
    tip->dsti_type = tmpltype;
    tip->dsti_options = options;
    tip->dsti_template = dsgw_ch_strdup( template );

    if (( options & DSGW_DISPLAY_OPT_ADDING ) != 0 ) {
	options |= DSGW_DISPLAY_OPT_EDITABLE;	/* add implies editable */

	if ( tmpltype != DSGW_TMPLTYPE_ADD ) {
	    /*
	     * if we are going to display an "add" view of an entry and
	     * an add template has not been explicitly requested, first look
	     * for a file called "add-TEMPLATE.html" and fall back on using
	     * whatever we would use if just editing an existing entry.
	     */
	    filename = template_filename( DSGW_TMPLTYPE_ADD, template );
	    tip->dsti_fp = dsgw_open_html_file( filename, DSGW_ERROPT_IGNORE );
	    free( filename );
	}
    }

    if ( tip->dsti_fp == NULL && ( options & DSGW_DISPLAY_OPT_EDITABLE ) != 0
	    && tmpltype != DSGW_TMPLTYPE_EDIT ) {
	/*
	 * if we are going to display an editable view of an entry and
	 * an edit template has not been explicitly requested, first look
	 * for a file called "edit-TEMPLATE.html" and fall back on using
	 * "list-TEMPLATE.html" or "display-TEMPLATE.html", as indicated by
	 * the value of tmpltype.
	 */
	filename = template_filename( DSGW_TMPLTYPE_EDIT, template );
	tip->dsti_fp = dsgw_open_html_file( filename, DSGW_ERROPT_IGNORE );
	free( filename );
    }

    if ( tip->dsti_fp == NULL ) {
	filename = template_filename( tmpltype, template );
	tip->dsti_fp = dsgw_open_html_file( filename, DSGW_ERROPT_EXIT );
	free( filename );
    }

    tip->dsti_preludelines = dsgw_savelines_alloc();
    tip->dsti_entrylines = dsgw_savelines_alloc();
    in_entry = 0;

    /* prime attrs array so we always retrieve objectClass values */
    attrcount = 1;
    tip->dsti_attrs = (char **)dsgw_ch_realloc( tip->dsti_attrs,
	    2 * sizeof( char * ));
    tip->dsti_attrs[ 0 ] = dsgw_ch_strdup( DSGW_ATTRTYPE_OBJECTCLASS );
    tip->dsti_attrs[ 1 ] = NULL;
    attrsonlycount = 0;
    tip->dsti_attrsonly_attrs = NULL;

    while ( dsgw_next_html_line( tip->dsti_fp, line )) {
	skip_line = 0;
	if ( dsgw_parse_line( line, &argc, &argv, 1, condition_is_true, tip )) {
	    if ( in_entry && dsgw_directive_is( line, DRCT_DS_ENTRYEND )) {
		dsgw_argv_free( argv );
		break;	/* the rest is read inside dsgw_display_done */
	    }
	    if ( dsgw_directive_is( line, DRCT_DS_ENTRYBEGIN )) {
		in_entry = skip_line = 1;
	    } else if ( dsgw_directive_is( line, DRCT_DS_ATTRIBUTE ) ||
		    dsgw_directive_is( line, DRCT_DS_ATTRVAL_SET )) {
		aopts = get_attr_options( argc, argv );
		if (( attr = get_arg_by_name( DSGW_ATTRARG_ATTR, argc,
			argv )) != NULL && strcasecmp( attr, "dn" ) != 0 &&
		    (strcasecmp(attr,DSGW_ATTRTYPE_AIMSTATUSTEXT) != 0 || gc->gc_aimpresence == 1) &&
			( aopts & DSGW_ATTROPT_LINK ) == 0 ) {
		    if (( aopts & DSGW_ATTROPT_TYPEONLY ) == 0 ) {
			append_to_array( &tip->dsti_attrs, &attrcount, attr );
		    } else {
			append_to_array( &tip->dsti_attrsonly_attrs,
				&attrsonlycount, attr );
		    }
		}
	    } else if ( dsgw_directive_is( line, DRCT_DS_ORGCHARTLINK )) {
		aopts = get_attr_options( argc, argv );
		if (( aopts & DSGW_ATTROPT_TYPEONLY ) == 0 ) {
		    append_to_array( &tip->dsti_attrs, &attrcount, gc->gc_orgchartsearchattr );
		} else {
		    append_to_array( &tip->dsti_attrsonly_attrs,
				     &attrsonlycount, gc->gc_orgchartsearchattr);
		}
	    } else if ( dsgw_directive_is( line, DRCT_DS_SORTENTRIES )) {
		if (( attr = get_arg_by_name( DSGW_ATTRARG_ATTR, argc,
			argv )) == NULL ) {
		    tip->dsti_sortbyattr = NULL;  /* no attr=, so sort by DN */
		} else {
		    tip->dsti_sortbyattr = dsgw_ch_strdup( attr );
		} 
		skip_line = 1;	/* completely done with directive */
	    }
	    dsgw_argv_free( argv );
	}

	if ( !skip_line ) {
	    if ( in_entry ) {	/* in entry */
		dsgw_savelines_save( tip->dsti_entrylines, line );
	    } else {		/* in prelude */
		dsgw_savelines_save( tip->dsti_preludelines, line );
	    }
	}
    }

    if ( attrcount > 0 ) {
	tip->dsti_attrflags = (unsigned long *)dsgw_ch_malloc( attrcount
		* sizeof( unsigned long ));
	memset( tip->dsti_attrflags, 0, attrcount * sizeof( unsigned long ));
    }

    /*
     * Add the sortattr to the list of attrs retrieved, if it's not
     * already in the list.
     */
    if ( tip->dsti_sortbyattr != NULL ) {
	int i, found = 0;
	for ( i = 0; i < attrcount; i++ ) {
	    if ( !strcasecmp( tip->dsti_sortbyattr, tip->dsti_attrs[ i ])) {
		found = 1;
		break;
	    }
	}
	if ( !found ) {
	    append_to_array( &tip->dsti_attrs, &attrcount,
		    tip->dsti_sortbyattr );
	}
    }

    return( tip );
}


void
dsgw_display_entry( dsgwtmplinfo *tip, LDAP *ld, LDAPMessage *entry,
	LDAPMessage *attrsonly_entry, char *dn )
{
    int		argc, editable, adding;
    char        **argv, *encodeddn, *line;

    editable = (( tip->dsti_options & DSGW_DISPLAY_OPT_EDITABLE ) != 0 );
    adding = (( tip->dsti_options & DSGW_DISPLAY_OPT_ADDING ) != 0 );

    if ( entry == NULL && !adding ) {
	dsgw_error( DSGW_ERR_MISSINGINPUT, NULL, DSGW_ERROPT_EXIT, 0, NULL );
    }

    tip->dsti_ld = ld;
    tip->dsti_entry = entry;
    tip->dsti_attrsonly_entry = attrsonly_entry;

    if ( dn == NULL ) {
	if ( entry == NULL ) {
	    dn = "dn=unknown";
	} else if (( dn = ldap_get_dn( ld, entry )) == NULL ) {
	    dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
	}
    }
    tip->dsti_entrydn = dsgw_ch_strdup( dn );
    encodeddn = dsgw_strdup_escaped( dn );

    if ( adding ) {
	tip->dsti_rdncomps = dsgw_rdn_values( dn );
    }

    if ( tip->dsti_preludelines != NULL ) {
	output_prelude( tip );
    }


    dsgw_savelines_rewind( tip->dsti_entrylines );
    while (( line = dsgw_savelines_next( tip->dsti_entrylines )) != NULL ) {
	if ( dsgw_parse_line( line, &argc, &argv, 0, condition_is_true, tip )) {
	    if ( dsgw_directive_is( line, DRCT_DS_ATTRIBUTE )) {
		do_attribute( tip, dn, tip->dsti_options, argc, argv );

	    } else if ( dsgw_directive_is( line, DRCT_DS_ATTRVAL_SET )) {
		do_attrvalset( tip, dn, tip->dsti_options, argc, argv );

	    } else if ( dsgw_directive_is( line, DRCT_DS_ORGCHARTLINK )) {
		do_orgchartlink( tip, dn, tip->dsti_options, argc, argv );

	    } else if ( dsgw_directive_is( line, DRCT_DS_EMIT_BASE_HREF )) {
		char *p;
		char *sname = dsgw_ch_strdup( getenv( "SCRIPT_NAME" ));
		if (( p = strrchr( sname, '/' )) != NULL ) {
		    *p = '\0';
		}
		dsgw_emitf( "<BASE HREF=\"%s%s/\">\n",
                           dsgw_server_url(), sname );

	    } else if ( dsgw_directive_is( line, DRCT_DS_BEGIN_DNSEARCHFORM )) {
		dsgw_form_begin ( "searchForm", "action=\"%s\" %s %s",
				 dsgw_getvp( DSGW_CGINUM_DOSEARCH ),
				 "target=stagingFrame",
				 "onSubmit=\"return parent.processSearch(searchForm);\"" );
		dsgw_emitf( "\n<INPUT TYPE=\"hidden\" NAME=\"dn\" VALUE=\"%s\">\n", encodeddn );

	    } else if ( dsgw_directive_is( line, DRCT_DS_BEGIN_ENTRYFORM )) {
		if ( editable ) {
		    dsgw_form_begin("modifyEntryForm","ACTION=\"%s\"",
				    dsgw_getvp( DSGW_CGINUM_DOMODIFY ));
		    dsgw_emits( "\n<INPUT TYPE=hidden NAME=\"changetype\">\n" );
		    dsgw_emitf( "<INPUT TYPE=hidden NAME=\"dn\" VALUE=\"%s\">\n",
				encodeddn );
		    dsgw_emits( "<INPUT TYPE=hidden NAME=\"changed_DN\" VALUE=false>\n");
		    dsgw_emits( "<INPUT TYPE=hidden NAME=\"deleteoldrdn\" VALUE=true>\n");

		} else {
		    dsgw_form_begin("editEntryForm", "action=\"%s\" %s",
				    dsgw_getvp( DSGW_CGINUM_AUTH ),
				    "target=\"_blank\"" );
		    dsgw_emits( "\n" );
		}

	    } else if ( dsgw_directive_is( line, DRCT_DS_END_ENTRYFORM )) {
		dsgw_emitf( "</FORM>\n" );
		dsgw_emit_confirmForm();

	    } else if ( dsgw_directive_is( line, DRCT_DS_END_DNSEARCHFORM )) {
		dsgw_emitf( "</FORM>\n" );
		dsgw_emit_alertForm();
		dsgw_emit_confirmForm();

	    } else if ( dsgw_directive_is( line, DRCT_DS_EDITBUTTON )) {
		if ( !editable ) do_editbutton( dn, encodeddn, argc, argv );

	    } else if ( dsgw_directive_is( line, DRCT_DS_DELETEBUTTON )) {
		if ( editable && !adding ) do_deletebutton( argc, argv );

	    } else if ( dsgw_directive_is( line, DRCT_DS_RENAMEBUTTON )) {
		/* if ( editable && !adding ) do_renamebutton( dn, argc, argv ); */

	    } else if ( dsgw_directive_is( line, DRCT_DS_EDITASBUTTON )) {
		if ( editable ) do_editasbutton( argc, argv );

	    } else if ( dsgw_directive_is( line, DRCT_DS_SAVEBUTTON )) {
		if ( editable ) do_savebutton( tip->dsti_options, argc, argv );

	    } else if ( dsgw_display_line( tip, line, argc, argv )) {

	    } else if ( dsgw_directive_is( line, DRCT_DS_NEWPASSWORD )) {
		if ( editable ) do_passwordfield( tip->dsti_options, argc,
			argv, "newpasswd" );

	    } else if ( dsgw_directive_is( line, DRCT_DS_CONFIRM_NEWPASSWORD )) {
		if ( editable ) do_passwordfield( tip->dsti_options, argc,
			argv, "newpasswdconfirm" );

	    } else if ( dsgw_directive_is( line, DRCT_DS_OLDPASSWORD )) {
		if ( editable ) do_passwordfield( tip->dsti_options, argc,
			argv, "passwd" );

	    } else if ( dsgw_directive_is( line, DRCT_DS_DNATTR )) {
		if ( dsgw_dnattr != NULL ) dsgw_emits( dsgw_dnattr );

	    } else if ( dsgw_directive_is( line, DRCT_DS_DNDESC )) {
		if ( dsgw_dndesc != NULL ) dsgw_emits( dsgw_dndesc );
	    
	    } else if ( dsgw_directive_is( line, DRCT_DS_DNEDITBUTTON )) {
		if ( editable ) {
		    do_dneditbutton( tip->dsti_options, argc, argv );
		}

	    } else if ( dsgw_directive_is( line, "DS_DNADDBUTTON" )) {
		dsgw_emits ("<INPUT TYPE=SUBMIT");
		{
		    auto char* v = get_arg_by_name (DSGW_ATTRARGS_VALUE, argc, argv);
		    if (v) dsgw_emitf (" VALUE=\"%s\"", v);
		}
		dsgw_emits (">\n");

	    } else if ( dsgw_directive_is( line, "DS_DNREMOVEBUTTON" )) {
		dsgw_emits ("<INPUT TYPE=BUTTON");
		{
		    auto char* v = get_arg_by_name (DSGW_ATTRARGS_VALUE, argc, argv);
		    if (v) dsgw_emitf (" VALUE=\"%s\"", v);
		}
		dsgw_emits (" onClick=\"if (parent.processSearch(searchForm)) {"
			               "searchForm.faMode.value='remove';"
			               "searchForm.submit();"
			               "searchForm.searchstring.select();"
			               "searchForm.searchstring.focus();"
			    "}\">\n");

	    } else if ( dsgw_directive_is( line, DRCT_DS_VIEW_SWITCHER ) &&
		    tip->dsti_entry != NULL ) {
		do_viewswitcher( tip->dsti_template, tip->dsti_entrydn,
			argc, argv );

	    } else if ( dsgw_directive_is( line, DRCT_DS_STD_COMPLETION_JS )) {
		do_std_completion_js( tip->dsti_template, argc, argv );

	    } else {
		dsgw_emits( line );
	    }

	    dsgw_argv_free( argv );
	}
    }

    free( encodeddn );
}

static void
dsgw_setstr (char** into, const char* from)
{
    if (from) {
	auto const size_t len = strlen (from) + 1;
	*into = dsgw_ch_realloc (*into, len);
	memmove (*into, from, len);
    } else if (*into) {
	free (*into);
	*into = NULL;
    }
}

void
dsgw_set_searchdesc( dsgwtmplinfo *tip, char *s2, char *s3, char *s4 )
{
    dsgw_setstr( &(tip->dsti_search2s), s2 );
    dsgw_setstr( &(tip->dsti_search3s), s3 );
    dsgw_setstr( &(tip->dsti_search4s), s4 );
}

void
dsgw_set_search_result( dsgwtmplinfo *tip, int entrycount, char *searcherror,
	char *lderrtxt )
{
    tip->dsti_entrycount = entrycount;
    dsgw_setstr( &(tip->dsti_searcherror), searcherror );
    dsgw_setstr( &(tip->dsti_searchlderrtxt), lderrtxt );
}


void
dsgw_display_done( dsgwtmplinfo *tip, char *dn )
{
    char	line[ BIG_LINE ], *jscomp;

    if ( tip->dsti_preludelines != NULL ) {
	output_prelude( tip );
    }

    /*
     * check for "completion_javascript" form var and
     * execute it if present.
     */ 
    jscomp = dsgw_get_cgi_var( "completion_javascript",
	    DSGW_CGIVAR_OPTIONAL );
    if ( jscomp != NULL ) {
	dsgw_emit_completion_javascript(jscomp, dn ? dn : "");
    }

    while ( dsgw_next_html_line( tip->dsti_fp, line )) {
	output_nonentry_line( tip, line );
    }

    fflush( stdout );
    fflush( stdout );

    dsgw_savelines_free( tip->dsti_entrylines );
    fclose( tip->dsti_fp );
    if ( tip->dsti_attrs != NULL ) {
	dsgw_charray_free( tip->dsti_attrs );
    }
    if ( tip->dsti_attrflags != NULL ) {
	free( tip->dsti_attrflags );
    }
    if ( tip->dsti_rdncomps != NULL ) {
	dsgw_charray_free( tip->dsti_rdncomps );
    }
    free( tip );
}

static void
output_prelude_script( dsgwtmplinfo *tip )
{
    int		editable, adding;
    char	*encodeddn;

    /* output any JavaScript functions we want to include before the entry */
    dsgw_emits( "<SCRIPT type=\"text/javascript\">\n" );
    dsgw_emits( "<!-- Hide from non-JavaScript-capable browsers\n" );
    dsgw_emits( "var emptyFrame = '';\n" );
    editable = ( tip->dsti_options & DSGW_DISPLAY_OPT_EDITABLE ) != 0;
    adding = ( tip->dsti_options & DSGW_DISPLAY_OPT_ADDING ) != 0;

    if ( !editable ) {
	char *urlprefix = dsgw_ch_malloc( strlen(gc->gc_urlpfxmain) + 128);
	sprintf(urlprefix, "%semptyFrame.html", gc->gc_urlpfxmain);
	unescape_entities(urlprefix);

	/* include the functions used to support "Edit" buttons */
	/* function haveAuthCookie() */
	dsgw_emits( "function haveAuthCookie()\n{\n" );
	dsgw_emitf( "    return ( document.cookie.indexOf( '%s=' ) >= 0 "
		"&& document.cookie.indexOf( '%s=%s' ) < 0 );\n}\n\n",
		DSGW_AUTHCKNAME, DSGW_AUTHCKNAME, DSGW_UNAUTHSTR );

	/* function authOrEdit() -- calls haveAuthCookie() */
	dsgw_emits( "function authOrEdit(encodeddn)\n{\n" );
	dsgw_emitf( "    editURL = '%s?context=%s&dn=' + encodeddn;\n",
		dsgw_getvp( DSGW_CGINUM_EDIT ), context);
	dsgw_emits( "    if ( haveAuthCookie()) {\n" );
	dsgw_emits( "\tnw = open(editURL, \"_blank\");\n" );
	dsgw_emits( "\twindow.location.href = " );
	dsgw_quote_emits (QUOTATION_JAVASCRIPT, urlprefix);
	dsgw_emits( ";\n"
		"    } else {\n"
		"\tdocument.editEntryForm.authdesturl.value = 'edit';\n"
		"\tdocument.editEntryForm.authdestdn.value = encodeddn;\n"
		"\ta = open(");
	dsgw_quote_emits (QUOTATION_JAVASCRIPT, urlprefix);

	free(urlprefix);
	urlprefix = NULL;
	dsgw_emits(", 'AuthWin');\n"
		"\ta.opener = self;\n"
		"\ta.closewin = true;\n"
		"\tdocument.editEntryForm.target = 'AuthWin';\n"
		"\tdocument.editEntryForm.submit();\n"
		"    }\n}\n" );

    } else {
	/* include variables and functions used to support edit mode */
	dsgw_emits( "var changesHaveBeenMade = 0;\n\n" );
	dsgw_emits( "var possiblyChangedAttr = null;\n\n" );

	/* function aChg() -- called from onChange and onClick handlers */
	dsgw_emits( "function aChg(attr)\n{\n" );
	if ( !adding ) {
	    dsgw_emits( "    cmd = 'document.modifyEntryForm.changed_' + "
		    "attr + '.value = \"true\"';\n" );
	    dsgw_emits( "    eval( cmd );\n    possiblyChangedAttr = null;\n" );
	}
	dsgw_emits( "    changesHaveBeenMade = 1;\n}\n\n" );


	if ( !adding ) {
	    /* function aFoc() -- called when text area gets focus. */
	    dsgw_emits( "function aFoc(attr)\n{\n"
		    "   possiblyChangedAttr = attr;\n}\n\n" );
	}

	/* function submitModify() */
	dsgw_emits( "function submitModify(changetype)\n{\n" );
	if ( !adding ) {
	    dsgw_emits( "\tif ( possiblyChangedAttr != null ) "
		    "aChg(possiblyChangedAttr);\n" );
	}
	dsgw_emits( "\tdocument.modifyEntryForm.changetype.value = changetype;\n" );
	dsgw_emits( "\tdocument.modifyEntryForm.submit();\n}\n" );

	/* function confirmModify() */
	dsgw_emits( "var changetype = '';\n\n" );
	dsgw_emits( "function confirmModify(ctype, prompt)\n{\n" );
	dsgw_emits( "	changetype = ctype;\n" );
	dsgw_emit_confirm (NULL, "CONFIRMVALUE2", NULL/*no*/,
			   NULL /* options */, 0, "prompt");
	dsgw_emits( "}\n" );

	/* function EditEntryAs() */
/*
	dsgw_emits( "function EditEntryAs(template)\n{\n" );
	dsgw_emits( "    newurl = window.location.protocol + '//' +\n"
		"\twindow.location.host +\n"
		"\twindow.location.pathname + '?' + template;\n" );
	dsgw_emits( "\twindow.location.href = newurl;\n}\n" );
*/

	if ( tip->dsti_entrydn != NULL ) {
	    encodeddn = dsgw_strdup_escaped( tip->dsti_entrydn );
	    dsgw_emits( "function EditEntryAs(template)\n{\n" );
	    dsgw_emitf( "    newurl = '%s?tmplname=' + template + '&context=%s&dn=%s';\n",
		    dsgw_getvp( DSGW_CGINUM_EDIT ), context, encodeddn );
	    dsgw_emits( "\twindow.location.href = newurl;\n}\n" );
	}

	/* function DNEdit() */
	if ( tip->dsti_entrydn != NULL ) {
	    encodeddn = dsgw_strdup_escaped( tip->dsti_entrydn );
	    dsgw_emits( "var DNEditURL;\n" );
	    dsgw_emits( "function DNEdit(template, attr, desc)\n{\n" );
	    dsgw_emitf( "    DNEditURL = '%s?template=' + template + "
	                               "'&dn=%s&context=%s&ATTR=' + attr + '&DESC=' + escape(desc);\n", 
	                               dsgw_getvp( DSGW_CGINUM_DNEDIT ), encodeddn, context );
	    dsgw_emits( "    if( !changesMade() ) window.location.href = DNEditURL;\n"
		        "    else {\n");
	    dsgw_emit_confirm( NULL, "CONFIRMVALUE3", NULL/*no*/,
			       XP_GetClientStr(DBT_continueWithoutSavingWindow_), 1,
			       "%s", XP_GetClientStr(DBT_continueWithoutSaving_));
	    dsgw_emits( "    }\n");
	    dsgw_emits( "}\n" );
	}

	/* function changesMade() */
	dsgw_emits( "function changesMade()\n{\n" );
	if ( !adding ) {
	    dsgw_emits( "\tif ( possiblyChangedAttr != null ) "
		    "aChg(possiblyChangedAttr);\n" );
	}
	dsgw_emits( "    return( changesHaveBeenMade );\n}\n" );

	/* function closeIfOK() */
	dsgw_emits( "function closeIfOK()\n{\n"
		    "    if ( !changesMade() ) top.close();\n"
		    "    else {\n" );
	dsgw_emit_confirm( NULL, "CONFIRMVALUE4", NULL/*no*/,
			   XP_GetClientStr(DBT_discardChangesWindow_), 1,
			   "%s", XP_GetClientStr(DBT_discardChanges_));
	dsgw_emits( "    }\n}\n" );

	/* set unload handler to catch unsaved changes */
	dsgw_emits( "document.onUnload = \""
		"return ( !changesMade() || prompt( 'Discard Changes?' ));\"\n" );
    }

    dsgw_emits( "// End hiding -->\n</SCRIPT>\n" );
}

/*
  Try to output our prelude javascript with any other javascript defined
  in the template prelude section - if there is none, just output
  the javascript prelude at the end of the prelude section
*/
static void
output_prelude( dsgwtmplinfo *tip )
{
    char	*line;

    if ( tip->dsti_preludelines != NULL ) {	/* output the prelude */
	int did_output_prelude_script = 0;
	dsgw_savelines_rewind( tip->dsti_preludelines );
	while (( line = dsgw_savelines_next( tip->dsti_preludelines ))
		!= NULL ) {
	    if (!did_output_prelude_script && PL_strcasestr(line, "<script")) {
		output_prelude_script( tip );
		did_output_prelude_script = 1;
	    }
	    output_nonentry_line( tip, line );
	}
	dsgw_savelines_free( tip->dsti_preludelines );
	tip->dsti_preludelines = NULL;
	if (!did_output_prelude_script) {
	    output_prelude_script( tip );
	}
    }
}


static void
output_nonentry_line( dsgwtmplinfo *tip, char *line )
{
    int		argc;
    char	**argv;

    if ( dsgw_parse_line( line, &argc, &argv, 0, condition_is_true, tip )) {
	if ( dsgw_directive_is( line, DRCT_DS_SEARCHDESC )) {
	    do_searchdesc( tip, argc, argv );
	} else if ( dsgw_display_line ( tip, line, argc, argv )) {
	} else {
	    dsgw_emits( line );
	}
	dsgw_argv_free( argv );
    }
}

static struct berval *
find_RDN (char* DN, char* attr, struct berval** vals)
     /* Return a pointer to the vals[i] that is
	part of the RDN of the given DN.
     */
{
    if (DN && *DN && vals && *vals) {
	auto char** RDNs = dsgw_ldap_explode_dn (DN, 0);
	auto char** AVAs = dsgw_ldap_explode_rdn (RDNs[0], 0);
	dsgw_charray_free (RDNs);
	if (AVAs) {
	    struct berval **val = NULL;
	    auto char** AVA;
	    for (AVA = AVAs; *AVA; ++AVA) {
		auto char* RDN = strchr (*AVA, '=');
		if (RDN) {
		    *RDN++ = '\0';
		    if (!strcasecmp (*AVA, attr)) {
			for (val = vals; *val && (*val)->bv_val; ++val) {
			    if (!strcmp (RDN, (*val)->bv_val)) {
				break;
			    }
			}
			if (*val && (*val)->bv_val) break;
			/* bug: what if there are other AVAs
			   that also match attr and one of vals?
			   Even if this algorithm could find them,
			   it couldn't return them (the function
			   return value can't express multiple
			   values).
			*/
		    }
		}
	    }
	    dsgw_charray_free (AVAs);
	    if (val) return *val;
	}
    }
    return NULL;
}

static void
do_orgchartlink( dsgwtmplinfo *tip, char *dn, unsigned long dispopts,
	int argc, char **argv )
{
  struct berval **ldvals = dsgw_get_values(tip->dsti_ld, tip->dsti_entry, gc->gc_orgchartsearchattr);
  char *escaped_value;

  if (gc->gc_orgcharturl == NULL || ldvals == NULL || *ldvals == NULL ||
      (*ldvals)->bv_val == NULL || strcmp((*ldvals)->bv_val, "") == 0) {
    dsgw_emits("\"javascript:void(0)\"");
    return;
  }
  dsgw_emits("\"");
  dsgw_emits(gc->gc_orgcharturl);
  escaped_value = dsgw_ch_malloc( 3 * strlen( ldvals[0]->bv_val ) + 1 );
  *escaped_value = '\0';
  dsgw_strcat_escaped( escaped_value, ldvals[0]->bv_val);
  dsgw_emits(escaped_value);
  dsgw_emits("\"\n");

  return;
}

static void
do_attribute( dsgwtmplinfo *tip, char *dn, unsigned long dispopts,
	int argc, char **argv )
{
    char			*attr, *syntax, *defval, *s;
    struct berval		**ldvals, **vals, tmpval, *tmpvals[ 2 ];
    unsigned long		options;
    int				i, len, attrindex, htmltype;
    struct dsgw_attrdispinfo	adi;
    int                         editable = 0;
    
    if (( attr = get_arg_by_name( DSGW_ATTRARG_ATTR, argc, argv )) == NULL ) {
	dsgw_emitf( XP_GetClientStr(DBT_missingS_), DSGW_ATTRARG_ATTR );
	return;
    }
    if (( syntax = get_arg_by_name( DSGW_ATTRARG_SYNTAX, argc, argv ))
	    == NULL ) {
	syntax = "cis";
    }

    if (( s = get_arg_by_name( DSGW_ATTRARG_HTMLTYPE, argc, argv )) == NULL ) {
	htmltype = DSGW_ATTRHTML_TEXT;
    } else {
	for ( i = 0; attrhtmltypes[ i ] != NULL; ++i ) {
	    if ( strcasecmp( s, attrhtmltypes[ i ] ) == 0 ) {
		htmltype = attrhtmlvals[ i ];
		break;
	    }
	}
	if ( attrhtmltypes[ i ] == NULL ) {
	    dsgw_emitf( XP_GetClientStr(DBT_unknownSS_), DSGW_ATTRARG_HTMLTYPE, s );
	    return;
	}
    }

    options = get_attr_options( argc, argv );

    if (( options & DSGW_ATTROPT_TYPEONLY ) != 0 ) {
	return;	/* don't actually display attr. if we only retrieved types */
    }

    if (( options & DSGW_ATTROPT_LINK ) != 0 ) {
	/*
	 * Output a "dosearch" URL that will retrieve this attribute.
	 * These used to look like:
	 *   .../dosearch/<host>:<port>?dn=<encodeddn>&<attr>&<mimetype>&<valindex>
	 *
	 * Now, thanks to me, they look like:
	 *   .../dosearch?context=<blah>&hp=<host>:<port>&dn=<encodeddn>&ldq=<the rest>
	 *     - RJP
	 *
	 * richm 20080201 - removed hp - search will always use the configured LDAP server
	 * instead of passing the host:port to use
	 */
	char    *urlprefix, *escapeddn, *mimetype, *prefix, *suffix;
	const char *amp = (options & DSGW_ATTROPT_ENTITIES) ? "&" : "&amp;";

	urlprefix = dsgw_build_urlprefix_ext(options & DSGW_ATTROPT_ENTITIES);
	escapeddn = dsgw_strdup_escaped( dn );
	mimetype = get_arg_by_name( DSGW_ATTRARG_MIMETYPE, argc, argv );
	if (( prefix = get_arg_by_name( "prefix", argc, argv )) == NULL ) {
	    prefix = "";
	}
	if (( suffix = get_arg_by_name( "suffix", argc, argv )) == NULL ) {
	    suffix = "";
	}

	/* XXXmcs
	 * always reference first value for now ( "&0" ) unless returning
	 * link to a vCard (in which case we leave the &0 off)
	 * have to encode & in ldq as %26
	 */
	dsgw_emitf("%s\"%s%s%sldq=%s%%26%s%s\"%s\n", prefix, urlprefix, escapeddn, amp,
		   attr,
		   ( mimetype == NULL ) ? "" : mimetype,
		    ( strcasecmp( "_vcard", attr ) == 0 ) ? "" : "%260", suffix );
	free( urlprefix );
	free( escapeddn );
	return;
    }

    if (( dispopts & DSGW_DISPLAY_OPT_EDITABLE ) != 0
	    && ( options & DSGW_ATTROPT_READONLY ) == 0 ) {
	options |= DSGW_ATTROPT_EDITABLE;
	editable = 1;
	if ((  dispopts & DSGW_DISPLAY_OPT_ADDING ) != 0 ) {
	    options |= DSGW_ATTROPT_ADDING;
	}
    }

    if (( dispopts & DSGW_DISPLAY_OPT_LINK2EDIT ) != 0 ) {
	options |= DSGW_ATTROPT_LINK2EDIT;
    }
    if ((options & DSGW_ATTROPT_QUOTED ) != 0 ) {
      options &= ~DSGW_ATTROPT_EDITABLE;/* always read-only */
      options &= ~DSGW_ATTROPT_ADDING;  /* always read-only */
      options |= DSGW_ATTROPT_READONLY;
    }

    ldvals = vals = NULL;

    if ( strcasecmp( attr, "dn" ) == 0 ) {	/* dn pseudo-attribute */
	tmpval.bv_val = dn;
	tmpval.bv_len = strlen(dn);
	tmpvals[ 0 ] = &tmpval;
	tmpvals[ 1 ] = NULL;
	vals = tmpvals;
	options &= ~DSGW_ATTROPT_EDITABLE;	/* always read-only */
	options &= ~DSGW_ATTROPT_ADDING;	/* always read-only */
	options |= DSGW_ATTROPT_READONLY;
    } else if( (strcasecmp( syntax, "binvalue" ) == 0) || (tip->dsti_entry != NULL) )  {
	/* Only display tagged stuff on searches */
	if (editable){
	    ldvals = ldap_get_values_len(tip->dsti_ld, tip->dsti_entry, attr);
	} else {
	    ldvals = dsgw_get_values(tip->dsti_ld, tip->dsti_entry, attr);
	}

	if (ldvals != NULL) {
	    vals = ldvals;
	}
    }

    if (vals == NULL && (options & DSGW_ATTROPT_QUOTED ) != 0 ) {
      dsgw_emits( "\"\"" );
      return;
    }

    if ( vals == NULL && tip->dsti_rdncomps != NULL
	    && ( options & DSGW_ATTROPT_ADDING ) != 0 ) {
	/*
	 * include values from the DN of new entry being added
	 */
	len = strlen( attr );
	ldvals = NULL;

	for ( i = 0; tip->dsti_rdncomps[ i ] != NULL; ++i ) {
	    if (( s = strchr( tip->dsti_rdncomps[ i ], '=' )) != NULL &&
		    s - tip->dsti_rdncomps[ i ] == len &&
		    strncasecmp( attr, tip->dsti_rdncomps[ i ], len ) == 0 ) {
		tmpval.bv_val = ++s;
		tmpval.bv_len = strlen(tmpval.bv_val);
		tmpvals[ 0 ] = &tmpval;
		tmpvals[ 1 ] = NULL;
		vals = tmpvals;
		break;
	    }
	}
    }

    if ( vals == NULL && ( defval = get_arg_by_name( DSGW_ATTRARG_DEFAULT,
	    argc, argv )) != NULL ) {
	tmpval.bv_val = defval;
	tmpval.bv_len = strlen(tmpval.bv_val);
	tmpvals[ 0 ] = &tmpval;
	tmpvals[ 1 ] = NULL;
	vals = tmpvals;
    }

    if ( vals == NULL && ( options & DSGW_ATTROPT_EDITABLE ) == 0 ) {
	if ( htmltype != DSGW_ATTRHTML_HIDDEN ) {
	    dsgw_HTML_emits( DSGW_UTF8_NBSP );
	}
    } else {
	if (( adi.adi_handlerp = syntax2attrhandler( syntax )) == NULL ) {
	    dsgw_emitf( XP_GetClientStr(DBT_unknownSyntaxSN_), syntax );
	} else {
	    if ( vals != NULL && vals[1] != NULL
			&& ( options & DSGW_ATTROPT_SORT ) != 0 ) {
		dsgw_sort_values( vals,
				  dsgw_valcmp (adi.adi_handlerp->ath_compare));
	    }
	    adi.adi_attr = attr;
	    adi.adi_argc = argc;
	    adi.adi_argv = argv;
	    adi.adi_vals = vals;
	    adi.adi_rdn = NULL;
	    adi.adi_htmltype = htmltype;
	    adi.adi_opts = options;

	    if (( options & DSGW_ATTROPT_EDITABLE ) == 0 ) {
		(*adi.adi_handlerp->ath_display)( &adi );
	    } else {
		if (( options & DSGW_ATTROPT_ADDING ) == 0 ) {
		    /* set flag to track attrs. we have seen */
		    for ( attrindex = 0; tip->dsti_attrs[ attrindex ] != NULL;
			    ++attrindex ) {
			if ( strcasecmp( attr, tip->dsti_attrs[ attrindex ] )
				== 0 ) {
			    break;
			}
		    }
		    if ( tip->dsti_attrs[ attrindex ] != NULL ) {
			if ( ! (tip->dsti_attrflags[ attrindex ] & DSGW_DSTI_ATTR_SEEN)) {
			    tip->dsti_attrflags[ attrindex ] |= DSGW_DSTI_ATTR_SEEN;
			    dsgw_emitf( "<INPUT TYPE=hidden NAME=\"changed_%s\" VALUE=false>\n",
				        attr );
			}
			adi.adi_rdn = find_RDN( dn, attr, vals );
		    }
		}

		/* display for editing */
		(*adi.adi_handlerp->ath_edit)( &adi );
	    }
	}
    }

    ldap_value_free_len(ldvals);
}

static void
append_to_array( char ***ap, int *countp, char *s )
{
    char	**a;
    int		count;

    a = *ap;
    count = *countp;

    a = (char **)dsgw_ch_realloc( a, ( count + 2 ) * sizeof( char * ));
    a[ count++ ] = dsgw_ch_strdup( s );
    a[ count ] = NULL;

    *ap = a;
    *countp = count;
}


static unsigned long
get_attr_options( int argc, char **argv )
{
    int			i;
    unsigned long	opts;
    char		*s;

    opts = 0;

    if (( s = get_arg_by_name( DSGW_ATTRARG_OPTIONS, argc, argv )) != NULL ) {
	char	*p, *q;

	for ( p = dsgw_ch_strdup( s ); p != NULL; p = q ) {
	    if (( q = strchr( p, ',' )) != NULL ) {
		*q++ = '\0';
	    }
	    for ( i = 0; attroptions[ i ] != NULL; ++i ) {
		if ( strcasecmp( p, attroptions[ i ] ) == 0 ) {
		    opts |= attroptvals[ i ];
		    break;
		}
	    }
	    if ( attroptions[ i ] == NULL ) {
		dsgw_emitf( XP_GetClientStr(DBT_unknownOptionS_), p );
		break;
	    }
	}
	free( p );
    }

    return( opts );
}


static struct attr_handler *
syntax2attrhandler( char *syntax )
{
    int		i;

    for ( i = 0; i < DSGW_AH_COUNT; ++i ) {
	if ( strcasecmp( syntax, attrhandlers[ i ].ath_syntax ) == 0 ) {
	    return( &attrhandlers[ i ] );
	}
    }

    return( NULL );
}


static int
numfields( int argc, char **argv, int valcount )
{
    char	*s;
    int		fields;

    if (( s = get_arg_by_name( DSGW_ATTRARGS_NUMFIELDS, argc,
	    argv )) == NULL ) {
	fields = 1;
    } else {
	if ( *s == '+' || *s == ' ') {
	    /* "numfields=+N" means show N more than number of values */
	    fields = valcount + atoi( s + 1 );
	} else {
	    if ( *s == '>' ) ++s;
	    /* "numfields=N" or "=>N" means show at least N fields */
	    fields = atoi( s );
	}
    }

    if ( fields < 1 ) {
	fields = 1;
    } else if ( fields < valcount ) {
	fields = valcount;
    }

    return( fields );
}

/*
 * calculate size of TEXT or TEXTAREA elements based on arguments,
 * the number of values, and the length of longest value.
 */
static void
element_sizes( int argc, char **argv, struct berval **vals, int valcount,
	int *rowsp, int *colsp )
{
    int		i, len, maxlen;
    char	*s;

    /* set *colsp (number of columns in each input item) */
    if ( colsp != NULL ) {
	/*
	 * columns are set using the "cols=N" or "size=N" argument
	 * "cols=>N" can be used to indicate at least N columns should be shown
	 * "cols=+N" can be used to size to N more than longest value
	 * in the absence of any of these, we set columns to one more than
	 * the longest value in the "vals" array
	 */
	if (( s = get_arg_by_name( DSGW_ATTRARGS_COLS, argc, argv )) == NULL ) {
	    s = get_arg_by_name( DSGW_ATTRARGS_SIZE, argc, argv );
	}

	if ( s != NULL && *s != '+' && *s != ' ' && *s != '>' ) {
	    *colsp = atoi( s );	/* extact width specified */
	} else if ( valcount == 0 ) {
	    if ( s != NULL && *s == '>' ) {
		*colsp = atoi( s + 1 );
	    } else {
		*colsp = 0;	/* use default width */
	    }
	} else {
	    /* determine ( length of longest value ) + 1  */
	    maxlen = 0;
	    for ( i = 0; i < valcount; ++i ) {
		if (( len = strlen( vals[ i ]->bv_val )) > maxlen ) {
		    maxlen = len;
		}
	    }
	    ++maxlen;

	    if ( s != NULL ) {
		i = atoi( s + 1 );
		if ( *s == ' ' || *s == '+' ) {
		    maxlen += i;
		} else {	/* '>' */
		    if ( maxlen < i ) {
			maxlen = i;
		    }
		}
	    }
	    *colsp = maxlen;
	}
    }

    /* set *rowsp (number of rows in each input item) */
    if ( rowsp != NULL ) {
	/*
	 * rows are set using "rows=M" ("=>M" and "=+M" are supported also)
	 * in the absense of this, we set it to the number of values in the
         * "vals" array
	 */
	if (( s = get_arg_by_name( DSGW_ATTRARGS_ROWS, argc, argv )) == NULL ) {
	    *rowsp = valcount;
	} else if ( *s == ' ' || *s == '+' ) {
	    *rowsp = valcount + atoi( s + 1 );
	} else if ( *s == '>' ) {
	    if (( *rowsp = atoi( s + 1 )) < valcount ) {
		*rowsp = valcount;
	    }
	} else {
	    *rowsp = atoi( s );
	}
    }
}


static void
output_text_elements( int argc, char **argv, char *attr, struct berval **vals,
	const char* rdn, char *prefix, int htmltype, unsigned long opts )
{
    int		i, valcount, fields, cols;

    if ( vals == NULL ) {
	valcount = 0;
    } else {
	for ( valcount = 0; vals[ valcount ] && vals[ valcount ]->bv_val; ++valcount ) {
		/* just count vals  */
	}
    }

    fields = numfields( argc, argv, valcount );
    element_sizes( argc, argv, vals, valcount, NULL, &cols );

    for ( i = 0; i < fields; ++i ) {
	auto const int is_rdn = (i < valcount && vals[ i ]->bv_val == rdn);

	dsgw_emitf( "<INPUT TYPE=\"%s\"", attrhtmltypes[ htmltype ] );

	dsgw_emitf( " NAME=\"%s%s%s\"", prefix, is_rdn ? "DN_" : "", attr );
	if ( cols > 0 ) {
	    dsgw_emitf( " SIZE=%d", cols );
	}
	
	if ( i < valcount ) {
	    dsgw_emitf( " VALUE=\"%s\"", vals[ i ]->bv_val );
	}
	
	if (( opts & DSGW_TEXTOPT_CHANGEHANDLERS ) != 0 ) {
	    dsgw_emitf( " onChange=\"aChg('%s')\"", is_rdn ? "DN" : attr );
	}
	if (( opts & DSGW_TEXTOPT_FOCUSHANDLERS ) != 0 ) {
	    dsgw_emitf( " onFocus=\"aFoc('%s')\"", is_rdn ? "DN" : attr );
	}

	dsgw_emitf( ">%s\n%s",
		is_rdn ? " DN" : "",
		( i < fields - 1 &&
		htmltype != DSGW_ATTRHTML_HIDDEN ) ? "<BR>\n" : "" );
    }
}


static void
output_textarea( int argc, char **argv, char *attr, struct berval **vals,
	int valcount, char *prefix, unsigned long opts )
{
    int		i, rows, cols;

    element_sizes( argc, argv, vals, valcount, &rows, &cols );

    dsgw_emits( "<TEXTAREA" );
    dsgw_emitf( " NAME=\"%s%s\"", prefix, attr );
    if ( rows > 0 ) {
	if ( rows == 1 ) {
	    rows = 2;	/* one line TEXTAREAs are ugly! */
	}
	dsgw_emitf( " ROWS=%d", rows );
    }

    if ( cols > 0 ) {
	dsgw_emitf( " COLS=%d", cols );
    }

    if (( opts & DSGW_TEXTOPT_CHANGEHANDLERS ) != 0 ) {
	dsgw_emitf( " onChange=\"aChg('%s')\"", attr );
    }
    if (( opts & DSGW_TEXTOPT_FOCUSHANDLERS ) != 0 ) {
	dsgw_emitf( " onFocus=\"aFoc('%s')\"", attr );
    }

    dsgw_emits( ">\n" );

    for ( i = 0; i < valcount; ++i ) {
	dsgw_emits( vals[ i ]->bv_val );
	dsgw_emits( "\n" );
    }

    dsgw_emits( "</TEXTAREA>\n" );
}


static void
output_text_checkbox_or_radio( struct dsgw_attrdispinfo *adip, char *prefix,
	int htmltype )
{
    int		i, checked;
#if 0
    char	*value;
#else
    struct berval value;
    struct berval *valuep = &value;
#endif

    /*
     * for checkboxes or radio buttons that are associated with string values,
     * we "check the box" if the value found in the "value=XXX" parameter is
     * present.
     */
    checked = 0;
    if (( value.bv_val = get_arg_by_name( DSGW_ATTRARGS_VALUE, adip->adi_argc,
	    adip->adi_argv )) == NULL ) {
	value.bv_val = "TRUE";	/* assume LDAP Boolean value */
    }
    /* value.bv_val never be NULL */
    value.bv_len = strlen(value.bv_val);
    if ( adip->adi_vals == NULL ) {
	if ( *(value.bv_val) == '\0' ) {
	    /*
	     * There are no existing values in the entry and this checkbox or
	     * radio button has a zero-length value associated with it.  We
	     * check this box/enable this radio button as a special case to
	     * support an "off" or "none of the rest" scenario. 
	     */
	    checked = 1;
	}

    } else {
	for ( i = 0; adip->adi_vals[ i ] && adip->adi_vals[ i ]->bv_val; ++i ) {
	    if ( dsgw_valcmp(adip->adi_handlerp->ath_compare)( 
		       (const struct berval **)&valuep,
		       (const struct berval **)&(adip->adi_vals[ i ]) ) == 0 ) {
		checked = 1;
		break;
	    }
	}
    }
    dsgw_emitf( "<INPUT TYPE=\"%s\" NAME=\"%s%s\" "
	    "VALUE=\"%s\"%s onClick=\"aChg('%s')\">\n",
	    ( htmltype == DSGW_ATTRHTML_RADIO ) ? "radio" : "checkbox",
	    prefix, adip->adi_attr, value.bv_val, checked ? " CHECKED" : "",
	    adip->adi_attr );
}


static void
emit_value( char *val, int quote_html_specials )
{
    int		freeit;

    if ( quote_html_specials ) {
	val = strdup_escape_entities( val, &freeit );
    } else {
	freeit = 0;
    }

    dsgw_emits( val );

    if ( freeit ) {
	free( val );
    }
}


/*
 * Default display handler for binary values
 */
static void
binvalue_display( struct dsgw_attrdispinfo *adip )
{
	int		i;
	struct berval **list_of_binvals;
	char *checked = " CHECKED";
	char *selected = " SELECTED";
	int		iValue;

	list_of_binvals = adip->adi_vals;

	for ( i = 0; list_of_binvals[ i ] != NULL; ++i ) 
	{
		char szFlags[512], szFormat[512];
		struct berval bin_data = *list_of_binvals[i];

		if( !bin_data.bv_val  || !bin_data.bv_len )
			continue;

		/* Now interpret the binary value if it has NT semantics */
		if( !strcasecmp( adip->adi_attr, "ntuserpriv") )
		{

			memcpy( &iValue, bin_data.bv_val, sizeof( iValue ) );
			fprintf( stdout, "<INPUT TYPE=\"radio\" NAME=\"%s\" "
			"VALUE=\"TRUE\"%s>%s<BR>\n", adip->adi_attr,
			(iValue == USER_PRIV_GUEST) ? checked : "", DSGW_NT_UP_GUEST);
			fprintf( stdout, "<INPUT TYPE=\"radio\" NAME=\"%s\" "
			"VALUE=\"TRUE\"%s>%s<BR>\n", adip->adi_attr,
			(iValue == USER_PRIV_USER) ? checked : "", DSGW_NT_UP_USER);
			fprintf( stdout, "<INPUT TYPE=\"radio\" NAME=\"%s\" "
			"VALUE=\"TRUE\"%s>%s<BR>\n", adip->adi_attr,
			(iValue == USER_PRIV_ADMIN) ? checked : "", DSGW_NT_UP_ADMIN);
		}
		else if ( strcasecmp( adip->adi_attr, "ntuserflags" ) == 0 ) 
		{
			memcpy( &iValue, bin_data.bv_val, sizeof( iValue ) );
			fprintf( stdout, "<FONT size=-1><SELECT MULTIPLE name=\"%s\" size=5>\n", adip->adi_attr);

			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_SCRIPT,
				(iValue & UF_SCRIPT) ? selected : "", DSGW_NT_UF_SCRIPT );
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_ACCOUNT_DISABLED,
				(iValue & UF_ACCOUNTDISABLE) ? selected : "", 
							DSGW_NT_UF_ACCOUNT_DISABLED);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_HOMEDIR_REQD,
				(iValue & UF_HOMEDIR_REQUIRED) ? selected : "", 
							DSGW_NT_UF_HOMEDIR_REQD);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_PASSWD_NOTREQD,
				(iValue & UF_PASSWD_NOTREQD) ? selected : "", 
							DSGW_NT_UF_PASSWD_NOTREQD);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_PASSWD_CANT_CHANGE,
				(iValue & UF_PASSWD_CANT_CHANGE) ? selected : "", 
							DSGW_NT_UF_PASSWD_CANT_CHANGE);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_LOCKOUT,
				(iValue & UF_LOCKOUT) ? selected : "", DSGW_NT_UF_LOCKOUT);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_DONT_EXPIRE_PASSWORD,
				(iValue & UF_DONT_EXPIRE_PASSWD) ? selected : "", 
							DSGW_NT_UF_DONT_EXPIRE_PASSWORD);

			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_NORMAL_ACCOUNT,
				(iValue & UF_NORMAL_ACCOUNT) ? selected : "", 
							DSGW_NT_UF_NORMAL_ACCOUNT);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_TEMP_DUPLICATE_ACCOUNT,
				(iValue & UF_TEMP_DUPLICATE_ACCOUNT) ? selected : "", 
							DSGW_NT_UF_TEMP_DUPLICATE_ACCOUNT);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_TEMP_WRKSTN_TRUST_ACCOUNT,
				(iValue & UF_WORKSTATION_TRUST_ACCOUNT) ? selected : "", 
							DSGW_NT_UF_TEMP_WRKSTN_TRUST_ACCOUNT);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_TEMP_SERVER_TRUST_ACCOUNT,
				(iValue & UF_SERVER_TRUST_ACCOUNT) ? selected : "", 
							DSGW_NT_UF_TEMP_SERVER_TRUST_ACCOUNT);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_UF_TEMP_INTERDOMAIN_TRUST_ACCOUNT,
				(iValue & UF_INTERDOMAIN_TRUST_ACCOUNT) ? selected : "", 
							DSGW_NT_UF_TEMP_INTERDOMAIN_TRUST_ACCOUNT);

			fprintf( stdout, "</SELECT><FONT size=+1>\n" );
		}
		else if ( strcasecmp( adip->adi_attr, "ntuserauthflags" ) == 0 ) 
		{
			memcpy( &iValue, bin_data.bv_val, sizeof( iValue ) );
			fprintf( stdout, "<FONT size=-1><SELECT MULTIPLE name=\"%s\" "
				"size=4>\n", adip->adi_attr);

			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_AF_OP_PRINT,
				(iValue & AF_OP_PRINT) ? selected : "", DSGW_NT_AF_OP_PRINT);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_AF_OP_COMM,
				(iValue & AF_OP_COMM) ? selected : "", DSGW_NT_AF_OP_COMM);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_AF_OP_SERVER,
				(iValue & AF_OP_SERVER) ? selected : "", DSGW_NT_AF_OP_SERVER);
			fprintf( stdout, "<OPTION value=\"%s\" %s>%s\n", DSGW_NT_AF_OP_ACCOUNTS,
				(iValue & AF_OP_ACCOUNTS) ? selected : "", DSGW_NT_AF_OP_ACCOUNTS);

			fprintf( stdout, "</SELECT><FONT size=+1>\n" );			
		}
		else if ( bin_data.bv_val  && ( bin_data.bv_len != 0 ))
		{
			if( bin_data.bv_len == 4 )
			{
				memcpy( &iValue, bin_data.bv_val, sizeof( iValue ) );

				if(( adip->adi_opts & DSGW_ATTROPT_DECIMAL ) != 0 ) 
					PR_snprintf( szFormat, sizeof(szFormat), "%%lu" );
				else
					PR_snprintf( szFormat, sizeof(szFormat), "%%#0%lu.%lux", bin_data.bv_len*2, bin_data.bv_len*2 );
				PR_snprintf( szFlags, sizeof(szFlags), szFormat, iValue );

				fputs( szFlags, stdout );

				if ( list_of_binvals[ i + 1 ] != NULL ) 
				{
					fputs( "<BR>\n", stdout );
				}
			}
		}
	}
}

#if NEEDED_FOR_DEBUGGING
/*
 * display handler for NT Domain Identifier string
 */
static void
ntdomain_display( struct dsgw_attrdispinfo *adip )
{
    int		i;

    /* Write values with a break (<BR>) separating them, 
	removing all after ":" */
    for ( i = 0; adip->adi_vals[ i ] && adip->adi_vals[ i ]->bv_val; ++i ) {
	if ( !did_output_as_special( adip->adi_argc, adip->adi_argv, 
		adip->adi_vals[ i ], adip->adi_vals[ i ] )) {
            char *pch = strchr( adip->adi_vals[ i ]->bv_val, DSGW_NTDOMAINID_SEP );
            if( pch )
               *pch = (char )NULL;
	    if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		dsgw_emits( "\"" );
	    }
	    
	    fputs( adip->adi_vals[ i ]->bv_val, stdout );
	    if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		dsgw_emits( "\"" );
	    }
	}

	if ( adip->adi_vals[ i + 1 ] && adip->adi_vals[ i + 1 ]->bv_val ) {
	    fputs( "<BR>\n", stdout );
	}
    }

}
#endif


/*
 * display handler for simple strings
 */
static void
str_display( struct dsgw_attrdispinfo *adip )
{
    int		i;

    if ( adip->adi_htmltype == DSGW_ATTRHTML_CHECKBOX ||
	    adip->adi_htmltype == DSGW_ATTRHTML_RADIO ) {
	output_text_checkbox_or_radio( adip, "", adip->adi_htmltype );
	return;
    }

    /* just write values with a break (<BR>) separating them */
    for ( i = 0; adip->adi_vals[ i ] && adip->adi_vals[ i ]->bv_val; ++i ) {

	if ( !did_output_as_special( adip->adi_argc, adip->adi_argv,
		adip->adi_vals[ i ], adip->adi_vals[ i ] ) &&
		adip->adi_htmltype != DSGW_ATTRHTML_HIDDEN ) {
	  if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
	    dsgw_emits( "\"" );
	  }
	  emit_value( adip->adi_vals[ i ]->bv_val, 
		    (( adip->adi_opts & DSGW_ATTROPT_NO_ENTITIES ) == 0 ));
	  if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
	    dsgw_emits( "\"" );
	  }
	}

	if ( adip->adi_htmltype != DSGW_ATTRHTML_HIDDEN &&
		adip->adi_vals[ i + 1 ] && adip->adi_vals[ i + 1 ]->bv_val ) {
	    dsgw_emits( "<BR>\n" );
	}
    }

}


static void
ntuserid_display( struct dsgw_attrdispinfo *adip )
{
    int		i;

    for ( i = 0; adip->adi_vals[ i ] && adip->adi_vals[ i ]->bv_val; ++i ) {
	if ( !did_output_as_special( adip->adi_argc, adip->adi_argv, 
		  adip->adi_vals[ i ], adip->adi_vals[ i ] )) {
            char *pch = adip->adi_vals[ i ]->bv_val;
            if( pch ) {

		if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		    dsgw_emits( "\"" );
		}
		
		fputs( pch, stdout );
		if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		    dsgw_emits( "\"" );
		}
	    }
	}

	if ( adip->adi_vals[ i + 1 ] && adip->adi_vals[ i + 1 ]->bv_val ) {
	    fputs( "<BR>\n", stdout );
	}
    }

}



/*
 * edit handler for simple strings
 */
static void
str_edit( struct dsgw_attrdispinfo *adip )
{
    int			valcount, adding, pre_idx;
    char		*prefix;
    unsigned long	textopts;

    adding = (( adip->adi_opts & DSGW_ATTROPT_ADDING ) != 0 );
    if (( adip->adi_opts & DSGW_ATTROPT_UNIQUE ) == 0 ) {
	pre_idx = DSGW_MOD_PREFIX_NORMAL;
    } else {
	pre_idx = DSGW_MOD_PREFIX_UNIQUE;
    }
    prefix = adding ? add_prefixes[ pre_idx ] : replace_prefixes[ pre_idx ];

    textopts = DSGW_TEXTOPT_CHANGEHANDLERS;
    if ( !adding ) {
	textopts |= DSGW_TEXTOPT_FOCUSHANDLERS;
    }

    switch( adip->adi_htmltype ) {
    case DSGW_ATTRHTML_TEXTAREA:
	if ( adip->adi_vals == NULL ) {
	    valcount = 0;
	} else {
	    for ( valcount = 0; adip->adi_vals[ valcount ] && 
	                     adip->adi_vals[ valcount ]->bv_val; ++valcount ) {
		;
	    }
	}
	output_textarea( adip->adi_argc, adip->adi_argv, adip->adi_attr,
		adip->adi_vals, valcount, prefix, textopts );
	break;

    case DSGW_ATTRHTML_TEXT:
    case DSGW_ATTRHTML_HIDDEN:
	output_text_elements( adip->adi_argc, adip->adi_argv, adip->adi_attr,
	                      adip->adi_vals,
			      adip->adi_rdn ? adip->adi_rdn->bv_val : NULL,
	                      prefix, adip->adi_htmltype, textopts );
	break;

    case DSGW_ATTRHTML_CHECKBOX:
    case DSGW_ATTRHTML_RADIO:
	output_text_checkbox_or_radio( adip, prefix, adip->adi_htmltype );
	break;

    default:
	dsgw_emitf( XP_GetClientStr(DBT_HtmlTypeSNotSupportedBrN_),
		attrhtmltypes[ adip->adi_htmltype ] );
    }
}


/*
 * display handler for multi-line strings, e.g. postalAddress
 * these are funny in that over LDAP, lines are separated by " $ "
 * this only support "htmltype=text"
 */
static void
mls_display( struct dsgw_attrdispinfo *adip )
{
    int		i;

    for ( i = 0; adip->adi_vals[ i ] != NULL; ++i ) {
	if ( !did_output_as_special( adip->adi_argc, adip->adi_argv,
		adip->adi_vals[ i ], adip->adi_vals[ i ] )) {
	    (void)dsgw_mls_convertlines( adip->adi_vals[ i ], "<BR>\n", NULL,
		    1, ( adip->adi_opts & DSGW_ATTROPT_NO_ENTITIES ) == 0 );
	}

	if ( adip->adi_vals[ i + 1 ] != NULL ) {
	    dsgw_emits( "<BR><BR>\n" );
	}
    }
}


/*
 * edit handler for multi-line strings
 */
static void
mls_edit( struct dsgw_attrdispinfo *adip )
{
    char		*prefix;
    struct berval       **valscopy, *tval[ 2 ];
    int			i, valcount, adding, pre_idx, *lines;
    unsigned long	textopts;

    adding = (( adip->adi_opts & DSGW_ATTROPT_ADDING ) != 0 );
    textopts = DSGW_TEXTOPT_CHANGEHANDLERS;
    if ( !adding ) {
	textopts |= DSGW_TEXTOPT_FOCUSHANDLERS;
    }

    if (( adip->adi_opts & DSGW_ATTROPT_UNIQUE ) == 0 ) {
	pre_idx = DSGW_MOD_PREFIX_NORMAL;
    } else {
	pre_idx = DSGW_MOD_PREFIX_UNIQUE;
    }
    prefix = adding ? add_mls_prefixes[ pre_idx ] :
	    replace_mls_prefixes[ pre_idx ];

    if ( adip->adi_vals == NULL ) {
	valscopy = NULL;
    } else {
	for ( valcount = 0; adip->adi_vals[ valcount ] != NULL; ++valcount ) {
	    ;
	}
	valscopy = (struct berval **)dsgw_ch_malloc( (valcount + 1) * sizeof( char * ));
	lines = (int *)dsgw_ch_malloc( valcount * sizeof( int ));
	for ( i = 0; i < valcount; ++i ) {
	    valscopy[ i ]->bv_val = dsgw_mls_convertlines( adip->adi_vals[ i ],
	                                             "\n", &lines[ i ], 0, 0 );
	    valscopy[ i ]->bv_len = strlen(valscopy[ i ]->bv_val);
	}
	valscopy[ valcount ] = NULL;
    }

    if ( adip->adi_htmltype == DSGW_ATTRHTML_TEXTAREA ) {
	if ( adip->adi_vals == NULL ) {
	    output_textarea( adip->adi_argc, adip->adi_argv, adip->adi_attr,
		    NULL, 0, prefix, textopts );
	} else {
	    tval[ 1 ] = NULL;
	    for ( i = 0; i < valcount; ++i ) {
		tval[ 0 ] = valscopy[ i ];
		output_textarea( adip->adi_argc, adip->adi_argv,
			adip->adi_attr, tval, 1, prefix, textopts );
		if ( i < valcount - 1 ) {
		    dsgw_emits( "<BR>\n" );
		}
	    }
	}
    } else {
	output_text_elements( adip->adi_argc, adip->adi_argv, adip->adi_attr,
		valscopy, NULL, prefix, adip->adi_htmltype, textopts );
	/* Bug: what if adip->adi_rdn != NULL?  In this case,
	   the element of valscopy that is a copy of adi_rdn
	   should be passed to output_text_elements (as the rdn).
	*/
    }

    if ( valscopy != NULL ) {
	ldap_value_free_len( valscopy );
	free( lines );
    }
}


/*
 * convert all occurrences of "$" in val to sep
 * un-escape any \HH sequences
 * if linesp != NULL, set *linesp equal to number of lines in val
 * if emitlines is zero, a malloc'd string is returned. 
 * if emitlines is non-zero, values are written to stdout (respecting the
 *    quote_html_specials flag) and NULL is returned.
 */
char *
dsgw_mls_convertlines( struct berval *val, char *sep, int *linesp, 
                       int emitlines, int quote_html_specials )
{
    char	*valcopy, *p, *q, *curline;
    int		i, c, lines, seplen;

    if ( val == NULL ) {
	return NULL;
    }

    if ( sep == NULL ) {
	sep = "";
	seplen = 0;
    } else {
	seplen = strlen( sep );
    }

    lines = 0;
    for ( q = val->bv_val; *q != '\0'; ++q ) {
	if ( *q == '$' ) {
	    ++lines;
	}
    }

    if ( linesp != NULL ) {
	*linesp = lines;
    }

    valcopy = dsgw_ch_malloc( strlen( val->bv_val ) + lines * seplen + 1 );

    /*
     * p points to the place we are copying to
     * q points to the place within the original value that we are examining
     * curline points to the start of the current line
     */
    p = curline = valcopy;
    for ( q = val->bv_val; *q != '\0'; ++q ) {
	if ( *q == '$' ) {		/* line separator */
	    if ( emitlines ) {
		*p = '\0';
		emit_value( curline, quote_html_specials );
		emit_value( sep, 0 );
	    }
	    strcpy( p, sep );
	    p += seplen;
	    curline = p;
	} else if ( *q == '\\' ) {	/* undo hex escapes */
	    if ( *++q == '\0' ) {
		break;
	    }
	    c = toupper( *q );
	    i = ( c >= 'A' ? ( c - 'A' + 10 ) : c - '0' );
	    i <<= 4;
	    if ( *++q == '\0' ) {
		break;
	    }
	    c = toupper( *q );
	    i += ( c >= 'A' ? ( c - 'A' + 10 ) : c - '0' );
	    *p++ = i;
	} else {
	    *p++ = *q;
	}
    }

    *p = '\0';

    if ( emitlines ) {
	if ( p > curline ) {
	    emit_value( curline, quote_html_specials );
	}
	free( valcopy );
	valcopy = NULL;
    }

    return( valcopy );
}


static void
dn_edit( struct dsgw_attrdispinfo *adip )
{
    if (( adip->adi_opts & DSGW_ATTROPT_DNPICKER ) != 0 ) {
	dn_display( adip );
    } else {
	str_edit( adip );
    }
    return;
}
    

static void
dn_display( struct dsgw_attrdispinfo *adip )
{
    int		i, j, len, dncomps;
    char	*p, *staticlabel, *tmps = NULL, *urlprefix, **rdns = NULL;
    struct berval *label = NULL;
    struct berval blabel;

    staticlabel = get_arg_by_name( DSGW_ATTRARG_LABEL, adip->adi_argc,
	    adip->adi_argv );

    if (( p = get_arg_by_name( DSGW_ATTRARG_DNCOMP, adip->adi_argc,
		adip->adi_argv )) == NULL ) { 
	dncomps = 1;
    } else {
	dncomps = atoi( p );	/* 0 or "all" means show all components */
    }

    if (( adip->adi_opts & DSGW_ATTROPT_LINK2EDIT ) != 0 ) {
	urlprefix = PR_smprintf("%s?context=%s&amp;dn=",
				dsgw_getvp( DSGW_CGINUM_EDIT ), context);
    } else {
	urlprefix = dsgw_build_urlprefix();
    }
#ifdef DSGW_DEBUG
    dsgw_log( "dn_display: urlprefix is %s\n", urlprefix );
#endif

    for ( i = 0; adip->adi_vals && adip->adi_vals[ i ] && 
                 adip->adi_vals[ i ]->bv_val; ++i ) {
	if ( staticlabel != NULL ) {
	    blabel.bv_val = staticlabel;
	    blabel.bv_len = strlen(staticlabel);
	    label = &blabel;
	} else if ( !looks_like_dn( adip->adi_vals[ i ]->bv_val ) || 
		( rdns = dsgw_ldap_explode_dn( adip->adi_vals[ i ]->bv_val ,
		( adip->adi_opts & DSGW_ATTROPT_DNTAGS ) == 0 )) == NULL ) {
	    /* explode DN failed -- show entire DN */
	    label = adip->adi_vals[ i ];
	    tmps = NULL;
	} else {
	    len = 1;	/* room for zero-termination */
	    for ( j = 0; rdns[ j ] != NULL && ( dncomps == 0 || j < dncomps );
		    ++ j ) {
		len += ( 2 + strlen( rdns[ j ] ));	/* rdn + ", " */
	    }
	    blabel.bv_val = p = tmps = dsgw_ch_malloc( len );
	    blabel.bv_len = len;
	    label = &blabel;
	    for ( j = 0; rdns[ j ] != NULL && ( dncomps == 0 || j < dncomps );
		    ++ j ) {
		if ( j > 0 ) {
		    strcpy( p, ", " );
		    p += 2;
		}
		strcpy( p, rdns[ j ] );
		p += strlen( p );
	    }
	}

	if ( !did_output_as_special( adip->adi_argc, adip->adi_argv, label,
		adip->adi_vals[ i ] )) {
	    if (( adip->adi_opts & DSGW_ATTROPT_NOLINK ) == 0 &&
		    looks_like_dn( adip->adi_vals[ i ]->bv_val  )) {
		if (( adip->adi_opts & DSGW_ATTROPT_DNPICKER ) != 0 ) {
		    dsgw_emits( "<TR><TD>" );
		}
		/* Don't display a link for the rootdn */
		if ( gc->gc_rootdn && dsgw_dn_cmp(adip->adi_vals[i]->bv_val, gc->gc_rootdn)) {
		  if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		    dsgw_emits( "\"" );
		  }
		  dsgw_emits( label->bv_val );
		  if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		    dsgw_emits( "\"" );
		  }
		} else {
		  dsgw_html_href( urlprefix, adip->adi_vals[ i ]->bv_val, 
				 label->bv_val, adip->adi_vals[ i ]->bv_val,
				 get_arg_by_name( DSGW_ATTRARG_HREFEXTRA,
						 adip->adi_argc, adip->adi_argv ));
		}
		if (( adip->adi_opts & DSGW_ATTROPT_DNPICKER ) != 0 ) {
		    dsgw_emits( "</TD>\n<TD ALIGN=CENTER><INPUT TYPE=CHECKBOX " );
		    dsgw_emitf( "VALUE=\"%s\" NAME=delete_%s ",
			   adip->adi_vals[ i ]->bv_val, adip->adi_attr );
		    dsgw_emitf( "onClick=\"aChg('%s');\"</TD>\n</TR>\n",
			    adip->adi_attr );
		}
	    } else {
	      if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		dsgw_emits( "\"" );
	      }
    
	      emit_value( label->bv_val,
			(( adip->adi_opts & DSGW_ATTROPT_NO_ENTITIES ) == 0 ));
	      if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		dsgw_emits( "\"" );
	      }
	    }
	}

	if ( !( adip->adi_opts & DSGW_ATTROPT_DNPICKER ) &&
		adip->adi_vals[ i + 1 ] != NULL ) {
	    dsgw_emits( "<BR>\n" );
	}

	if ( tmps != NULL ) {
	    free( tmps );
	}

	if ( rdns != NULL ) {
	    dsgw_charray_free( rdns );
	}
    }


    /* Output a javascript array of values for this attribute */
    if (( adip->adi_opts & DSGW_ATTROPT_DNPICKER ) != 0 ) {
	dsgw_emits( "<SCRIPT type=\"text/javascript\">\n" );
	dsgw_emits( "<!-- Hide from non-JavaScript-capable browsers\n" );
	dsgw_emitf( "var %s_values = new Object;\n", adip->adi_attr );
	for ( i = 0; adip->adi_vals != NULL && adip->adi_vals[ i ] != NULL; ++i ) {
	    char *edn;
	    edn = dsgw_strdup_escaped( adip->adi_vals[ i ]->bv_val );
	    dsgw_emitf( "%s_values[%d] = \"%s\";\n", adip->adi_attr, i,
		    edn );
	    free( edn );
	}
	dsgw_emitf( "%s_values.count = %d;\n", adip->adi_attr, i );
	dsgw_emits( "// End hiding -->\n" );
	dsgw_emits( "</SCRIPT>\n" );
    }

    PR_smprintf_free( urlprefix );
}


static void
mail_display( struct dsgw_attrdispinfo *adip )
{
    int		i;

    for ( i = 0; adip->adi_vals[ i ] && adip->adi_vals[ i ]->bv_val; ++i ) {
	if ( !did_output_as_special( adip->adi_argc, adip->adi_argv,
		    adip->adi_vals[ i ], adip->adi_vals[ i ] )) {
	    if (( adip->adi_opts & DSGW_ATTROPT_NOLINK ) == 0 ) {
		dsgw_html_href( "mailto:", adip->adi_vals[ i ]->bv_val,
			adip->adi_vals[ i ]->bv_val, NULL,
			get_arg_by_name( DSGW_ATTRARG_HREFEXTRA,
				adip->adi_argc, adip->adi_argv ));
	    } else {
	      if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		dsgw_emits( "\"" );
	      }
	      
	      emit_value( adip->adi_vals[ i ]->bv_val,
			  (( adip->adi_opts & DSGW_ATTROPT_NO_ENTITIES ) == 0 ));
	      if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		dsgw_emits( "\"" );
	      }

	    }
	}

	if ( adip->adi_vals[ i + 1 ] != NULL ) {
	    dsgw_emits( "<BR>\n" );
	}
    }

}


static void
url_display( struct dsgw_attrdispinfo *adip )
{
    int		i;
    char	*savep, *label;
    struct berval blabel;

    for ( i = 0; adip->adi_vals[ i ] && adip->adi_vals[ i ]->bv_val; ++i ) {
	if (( label = strchr( adip->adi_vals[ i ]->bv_val, ' ' )) == NULL ) {
	    label = adip->adi_vals[ i ]->bv_val;
	    savep = NULL;
	} else {
	    savep = label;
	    *label++ = '\0';
	}
	blabel.bv_val = label;
	blabel.bv_len = strlen(label);

	if ( !did_output_as_special( adip->adi_argc, adip->adi_argv, &blabel,
		adip->adi_vals[ i ] )) {
	    if (( adip->adi_opts & DSGW_ATTROPT_NOLINK ) == 0 ) {
		dsgw_html_href( NULL, adip->adi_vals[ i ]->bv_val, label, NULL,
			get_arg_by_name( DSGW_ATTRARG_HREFEXTRA,
				adip->adi_argc, adip->adi_argv ));
	    } else {
		if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		    dsgw_emits( "\"" );
		}
		
		emit_value( adip->adi_vals[ i ]->bv_val,
			(( adip->adi_opts & DSGW_ATTROPT_NO_ENTITIES ) == 0 ));
		if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		    dsgw_emits( "\"" );
		}

	    }
	}

	if ( savep != NULL ) {
	    *savep = ' ';
	}

	if ( adip->adi_vals[ i + 1 ] != NULL ) {
	    dsgw_emits( "<BR>\n" );
	}
    }

}


static void
bool_display( struct dsgw_attrdispinfo *adip )
{
    int		boolval, pre_idx;
    char	*usestr, *truestr, *falsestr, *checked;
    char	*nameprefix, *onclick;
    struct berval busestr;

    if ( adip->adi_vals == NULL || adip->adi_vals[ 0 ] == NULL ) {
      return;
    }

    checked = " CHECKED";

    if (( adip->adi_opts & DSGW_ATTROPT_EDITABLE ) == 0 ) {
	nameprefix = onclick = "";
    } else {
	char *onclickfmt = " onClick=\"aChg('%s')\"";

	if (( adip->adi_opts & DSGW_ATTROPT_UNIQUE ) == 0 ) {
	    pre_idx = DSGW_MOD_PREFIX_NORMAL;
	} else {
	    pre_idx = DSGW_MOD_PREFIX_UNIQUE;
	}
	nameprefix = (( adip->adi_opts & DSGW_ATTROPT_ADDING ) == 0 ) ?
		replace_prefixes[ pre_idx ] : add_prefixes[ pre_idx ];
	onclick = dsgw_ch_malloc( strlen( onclickfmt ) +
		strlen( adip->adi_attr ) + 1 );
	sprintf( onclick, onclickfmt, adip->adi_attr );
    }

    if (( truestr = get_arg_by_name( DSGW_ATTRARG_TRUESTR, adip->adi_argc,
	    adip->adi_argv )) == NULL ) {
	truestr = DSGW_ATTRARG_TRUESTR;
    }
    if (( falsestr = get_arg_by_name( DSGW_ATTRARG_FALSESTR, adip->adi_argc,
	    adip->adi_argv )) == NULL ) {
	falsestr = DSGW_ATTRARG_FALSESTR;
    }

    boolval = ( toupper( *(adip->adi_vals[ 0 ]->bv_val) ) == 'T' );

    if ( adip->adi_htmltype == DSGW_ATTRHTML_RADIO ) {
	dsgw_emitf( "<INPUT TYPE=\"radio\" NAME=\"%s%s\" "
		"VALUE=\"TRUE\"%s%s>%s<BR>\n", nameprefix, adip->adi_attr,
		boolval ? checked : "", onclick, truestr );
	dsgw_emitf( "<INPUT TYPE=\"radio\" NAME=\"%s%s\" "
		"VALUE=\"FALSE\"%s%s>%s<BR>\n", nameprefix, adip->adi_attr,
		boolval ? "" : checked, onclick, falsestr );
    } else if ( adip->adi_htmltype == DSGW_ATTRHTML_CHECKBOX ) {
	dsgw_emitf( "<INPUT TYPE=\"checkbox\" NAME=\"%s%s\" "
		"VALUE=\"TRUE\"%s%s\">%s\n", nameprefix, adip->adi_attr,
		boolval ? checked : "", onclick, truestr );
    } else {
	usestr =  boolval ? truestr : falsestr;
	busestr.bv_val = usestr;
	busestr.bv_len = strlen(usestr);
	if ( !did_output_as_special( adip->adi_argc, adip->adi_argv, &busestr,
		adip->adi_vals[ 0 ] )) {
	    if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		dsgw_emits( "\"" );
	    }
	    
	    dsgw_emits( boolval ? truestr : falsestr );
	    if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		dsgw_emits( "\"" );
	    }
	}
    }
}


static void
bool_edit( struct dsgw_attrdispinfo *adip )
{
    if ( adip->adi_htmltype == DSGW_ATTRHTML_RADIO ||
	    adip->adi_htmltype == DSGW_ATTRHTML_CHECKBOX ) {
	bool_display( adip );
    } else {
	str_edit( adip );
    }
}


static void
time_display( struct dsgw_attrdispinfo *adip )
{
    int		i;

    for ( i = 0; adip->adi_vals[ i ] != NULL; ++i ) {
	if ( !did_output_as_special( adip->adi_argc, adip->adi_argv,
		adip->adi_vals[ i ], adip->adi_vals[ i ] )) {
	    if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		dsgw_emits( "\"" );
	    }
	    dsgw_emits( time2text( adip->adi_vals[ i ]->bv_val,
		( adip->adi_opts & DSGW_ATTROPT_DATEONLY ) != 0 ) );
	    if ((adip->adi_opts & DSGW_ATTROPT_QUOTED ) != 0 ) {
		dsgw_emits( "\"" );
	    }
	}

	if ( adip->adi_vals[ i + 1 ] != NULL ) {
	    dsgw_emits( "<BR>\n" );
	}
    }

}


/*
 * handle special "within=", "href=", and "script=" options
 * return 0 if nothing was output or 1 if something was.
 */
static int
did_output_as_special( int argc, char **argv, 
                       struct berval *label, struct berval *val )
{
    char	*href = NULL;
    char	*within = NULL;
    char	*script = NULL;
    char	*newval = NULL;

    if (( NULL == val ) || ( NULL == label )) {
	return( 0 );
    }
    if (( href = get_arg_by_name( DSGW_ATTRARG_HREF, argc, argv )) == NULL &&
	    ( within = get_arg_by_name( DSGW_ATTRARG_WITHIN, argc,
	    argv )) == NULL &&
	    ( script = get_arg_by_name( DSGW_ATTRARG_SCRIPT, argc,
	    argv )) == NULL ) {
	return( 0 );
    }

    if ( within != NULL ) {
	dsgw_substitute_and_output( within, "--value--", val->bv_val, 1 );
    } else if (href != NULL) {
	dsgw_html_href( NULL, href, label->bv_val, val->bv_val,
		get_arg_by_name( DSGW_ATTRARG_HREFEXTRA, argc, argv ));
    } else if (script != NULL) {
        newval = dsgw_strdup_escaped ( val->bv_val );
        if (newval != NULL && *newval != '\0') {
		fputs( newval, stdout );
                free( newval );
	}
    }

    return( 1 );
}


/*
 * The GET2BYTENUM() macro, time2text(), and gtime() functions are taken
 * with slight changes (to handle 4-digit years) from libldap/tmplout.c
 */
#define GET2BYTENUM( p )	(( *p - '0' ) * 10 + ( *(p+1) - '0' ))
#define BSIZ 1024

static char *
time2text( char *ldtimestr, int dateonly )
{
    int			len;
    struct tm		t;
    char		*p, zone;
    time_t		gmttime;
    char                *timestr = NULL;

    memset( (char *)&t, 0, sizeof( struct tm ));
    if (( len = strlen( ldtimestr )) < 13 ) {
	return( ldtimestr );
    }
    if ( len > 15 ) {	/* throw away excess from 4-digit year time string */
	len = 15;
    } else if ( len == 14 ) {
	len = 13;	/* assume we have a time w/2-digit year (len=13) */
    }

    for ( p = ldtimestr; p - ldtimestr + 1 < len; ++p ) {
	if ( !ldap_utf8isdigit( p )) {
	    return( ldtimestr );
	}
    }

    p = ldtimestr;
    t.tm_year = GET2BYTENUM( p ); p += 2;
    if ( len == 15 ) {
	t.tm_year = 100 * (t.tm_year - 19);
	t.tm_year += GET2BYTENUM( p ); p += 2;
    }
    else {
        /* 2 digit years...assumed to be in the range (19)70 through
           (20)69 ...less than 70 (for now, 38) means 20xx */
        if(t.tm_year < 70) {
            t.tm_year += 100;
        }
    }
 
    t.tm_mon = GET2BYTENUM( p ) - 1; p += 2;
    t.tm_mday = GET2BYTENUM( p ); p += 2;
    t.tm_hour = GET2BYTENUM( p ); p += 2;
    t.tm_min = GET2BYTENUM( p ); p += 2;
    t.tm_sec = GET2BYTENUM( p ); p += 2;

    if (( zone = *p ) == 'Z' ) {	/* GMT */
	zone = '\0';	/* no need to indicate on screen, so we make it null */
    }

    gmttime = gtime( &t );

    /* Try to get the localized string */
    timestr = dsgw_time(gmttime);

    /* Localized time string getter failed, try ctime()*/
    if (timestr == NULL){
      timestr = ctime( &gmttime );

      /* replace trailing newline */
      timestr[ strlen( timestr ) - 1 ] = zone;	
      if ( dateonly ) {
	strcpy( timestr + 11, timestr + 20 );
      }
    }

    return(timestr);
}





/* gtime.c - inverse gmtime */

#if !defined( MACOS ) && !defined( _WINDOWS ) && !defined( DOS )
#include <sys/time.h>
#endif /* !MACOS */

/* gtime(): the inverse of localtime().
	This routine was supplied by Mike Accetta at CMU many years ago.
 */

static int	dmsize[] = {
    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};

#define	dysize(y)	\
	(((y) % 4) ? 365 : (((y) % 100) ? 366 : (((y) % 400) ? 365 : 366)))

/*
#define	YEAR(y)		((y) >= 100 ? (y) : (y) + 1900)
*/
#define YEAR(y)         (((y) < 1900) ? ((y) + 1900) : (y))


/*  */

static long	gtime ( struct tm *tm )
{
    register int    i,
                    sec,
                    mins,
                    hour,
                    mday,
                    mon,
                    year;
    register long   result;

    if ((sec = tm -> tm_sec) < 0 || sec > 59
	    || (mins = tm -> tm_min) < 0 || mins > 59
	    || (hour = tm -> tm_hour) < 0 || hour > 24
	    || (mday = tm -> tm_mday) < 1 || mday > 31
	    || (mon = tm -> tm_mon + 1) < 1 || mon > 12)
	return ((long) -1);
    if (hour == 24) {
	hour = 0;
	mday++;
    }
    year = YEAR (tm -> tm_year);

    result = 0L;
    for (i = 1970; i < year; i++)
	result += dysize (i);
    if (dysize (year) == 366 && mon >= 3)
	result++;
    while (--mon)
	result += dmsize[mon - 1];
    result += mday - 1;
    result = 24 * result + hour;
    result = 60 * result + mins;
    result = 60 * result + sec;

    return result;
}


static int
looks_like_dn( char *s )
{
    return( strchr( s, '=' ) != NULL );
}


static void
do_searchdesc( dsgwtmplinfo *tip, int argc, char** argv)
{
    auto unsigned fmt = 0;
    auto unsigned opt = 0;
    {
	auto int i;
	for (i = 0; i < argc; ++i) {
	    if (!strcasecmp (argv[i], "VERBOSE")) {
		opt |= 1;
	    }
	}
    }
    switch ( tip->dsti_entrycount ) {
      case 0:
	fmt = opt & 1
	    ? ((tip->dsti_options & DSGW_DISPLAY_OPT_CUSTOM_SEARCHDESC)
	       ? DBT_SearchFound0Entries_
	       : DBT_SearchFound0EntriesWhere_)
	    : ((tip->dsti_options & DSGW_DISPLAY_OPT_CUSTOM_SEARCHDESC)
	       ? DBT_Found0Entries_
	       : DBT_Found0EntriesWhere_);
	break;
      case 1:
	fmt = opt & 1
	    ? ((tip->dsti_options & DSGW_DISPLAY_OPT_CUSTOM_SEARCHDESC)
	       ? DBT_SearchFound1Entry_
	       : DBT_SearchFound1EntryWhere_)
	    : ((tip->dsti_options & DSGW_DISPLAY_OPT_CUSTOM_SEARCHDESC)
	       ? DBT_Found1Entry_
	       : DBT_Found1EntryWhere_);
	break;
      default:
	fmt = opt & 1
	    ? ((tip->dsti_options & DSGW_DISPLAY_OPT_CUSTOM_SEARCHDESC)
	       ? DBT_SearchFoundEntries_
	       : DBT_SearchFoundEntriesWhere_)
	    : ((tip->dsti_options & DSGW_DISPLAY_OPT_CUSTOM_SEARCHDESC)
	       ? DBT_FoundEntries_
	       : DBT_FoundEntriesWhere_);
	break;
    }
    {
	auto char* format = XP_GetClientStr (fmt);
	if (format == NULL || *format == '\0') {
	    format = "Found %1$li entries where the %2$s %3$s '%4$s'.\n";
	}
	dsgw_emitf (format, (long)tip->dsti_entrycount, /* %1$li */
		    tip->dsti_search2s ? tip->dsti_search2s : "", /* %2$s */
		    tip->dsti_search3s ? tip->dsti_search3s : "", /* %3$s */
		    tip->dsti_search4s ? tip->dsti_search4s : "");/* %4$s */
    }
    if ( tip->dsti_searcherror != NULL && *tip->dsti_searcherror != '\0' ) {
	dsgw_emitf( "<BR>%s\n", tip->dsti_searcherror );
    }
    if ( tip->dsti_searchlderrtxt != NULL &&
	    *tip->dsti_searchlderrtxt != '\0' ) {
	dsgw_emitf( "<BR>(%s)\n", tip->dsti_searchlderrtxt );
    }
}


static void
do_editbutton( char *dn, char *encodeddn, int argc, char **argv )
{
    char        *buttonlabel, **rdns;

    if (( buttonlabel = get_arg_by_name( DSGW_ARG_BUTTON_LABEL, argc,
	    argv )) == NULL ) {
	buttonlabel = XP_GetClientStr(DBT_edit_);
    }

    if (( rdns = dsgw_ldap_explode_dn( dn, 1 )) != NULL ) {
	dsgw_emitf(
		"<INPUT TYPE=\"hidden\" NAME=\"authhint\" VALUE=\"%s\">\n",
		rdns[ 0 ] );
	dsgw_charray_free( rdns );
    }

    dsgw_emitf( "<INPUT TYPE=\"hidden\" NAME=\"authdesturl\">\n"
	    "<INPUT TYPE=\"hidden\" NAME=\"authdestdn\">\n"
	    "<INPUT TYPE=\"button\" VALUE=\"%s\" "
	    "onClick=\"authOrEdit('%s')\">\n", buttonlabel, encodeddn );
}


static void
do_savebutton( unsigned long dispopts, int argc, char **argv )
{
    char	*buttonlabel, *checksubmit;

    if (( buttonlabel = get_arg_by_name( DSGW_ARG_BUTTON_LABEL, argc,
	    argv )) == NULL ) {
	buttonlabel = XP_GetClientStr(DBT_saveChanges_);
    }

    dsgw_emitf( "<INPUT TYPE=\"button\" VALUE=\"%s\" onClick=\"",
	    buttonlabel );
    if (( checksubmit = get_arg_by_name( DSGW_ARG_BUTTON_CHECKSUBMIT, argc,
	    argv )) != NULL ) {
	dsgw_emitf( "if (%s) ", checksubmit );
    }
    dsgw_emitf( "submitModify('%s')\">\n",
	    ( dispopts & DSGW_DISPLAY_OPT_ADDING ) == 0
	      ? "modify" : "add" );
}


static void
do_deletebutton( int argc, char **argv )
{
    char	*buttonlabel, *prompt;

    if (( buttonlabel = get_arg_by_name( DSGW_ARG_BUTTON_LABEL, argc,
	    argv )) == NULL ) {
	buttonlabel = XP_GetClientStr(DBT_delete_);
    }

    if (( prompt = get_arg_by_name( DSGW_ARG_BUTTON_PROMPT, argc,
	    argv )) == NULL ) {
	prompt = XP_GetClientStr(DBT_deleteThisEntry_);
    }

    dsgw_emitf("<INPUT TYPE=BUTTON VALUE=\"%s\"", buttonlabel);
    dsgw_emits(" onClick=\"confirmModify('delete', ");
    dsgw_quote_emits(QUOTATION_JAVASCRIPT, prompt);
    dsgw_emits(")\">\n");
}


static void
do_editasbutton( int argc, char **argv )
{
    char	*template, *buttonlabel;

    if (( template = get_arg_by_name( DSGW_ARG_BUTTON_TEMPLATE, argc,
	    argv )) == NULL ) {
	template = "";
    }

    if (( buttonlabel = get_arg_by_name( DSGW_ARG_BUTTON_LABEL, argc,
	    argv )) == NULL ) {
	buttonlabel = XP_GetClientStr(DBT_editAs_);
    }

    dsgw_emitf( "<INPUT TYPE=\"button\" VALUE=\"%s\""
	    " onClick=\"EditEntryAs('%s')\">\n", buttonlabel, template );
}


static void
do_passwordfield( unsigned long dispopts, int argc, char **argv,
	char *fieldname )
{
    output_text_elements( argc, argv, fieldname, NULL, NULL, "",
	    DSGW_ATTRHTML_PASSWORD, dispopts );
}


static void
do_helpbutton( unsigned long dispopts, int argc, char **argv )
{
    char        *topic;

    if (( topic = get_arg_by_name( DSGW_ARG_BUTTON_TOPIC, argc,
	    argv )) == NULL ) {
	topic = "";
    }

    dsgw_emit_helpbutton( topic );
}


static void
do_closebutton( unsigned long dispopts, int argc, char **argv )
{
    dsgw_emit_button( argc, argv, "onClick=\"%s\"",
		     ( dispopts & DSGW_DISPLAY_OPT_EDITABLE ) == 0
		     ? "top.close()" : "closeIfOK()" );
}


static void
do_dneditbutton( unsigned long dispopts, int argc, char **argv )
{
    char *label, *template, *attr, *desc;

    if (( label = get_arg_by_name( DSGW_ARG_DNEDIT_LABEL, argc,
	    argv )) == NULL ) {
	label = XP_GetClientStr(DBT_edit_1);
    }
    if (( template = get_arg_by_name( DSGW_ARG_DNEDIT_TEMPLATE, argc,
	    argv )) == NULL ) {
	template = "dnedit";
    }
    if (( attr = get_arg_by_name( DSGW_ARG_DNEDIT_ATTR, argc,
	    argv )) == NULL ) {
	dsgw_emits( "<!-- Error: missing attr= argument in DS_DNEDITBUTTON "
		"directive -->\n" );
	return;
    }
    if (( desc = get_arg_by_name( DSGW_ARG_DNEDIT_DESC, argc,
	    argv )) == NULL ) {
	desc = attr;
    }

    dsgw_emitf( "<INPUT TYPE=\"button\" VALUE=\"%s\""
	     " onClick=\"DNEdit('%s', '%s', '%s')\">\n", label, template,
	     attr, desc );
}


static void
do_viewswitcher( char *template, char *dn, int argc, char **argv )
{
    dsgwtmplset	*tsp;
    dsgwview	*vp;
    char	*s, *altprefix, *altsuffix, *curprefix, *cursuffix;

    /* first we see if this template is part of a template set */
    for ( tsp = gc->gc_tmplsets; tsp != NULL; tsp = tsp->dstset_next ) {
	for ( vp = tsp->dstset_viewlist; vp != NULL; vp = vp->dsview_next ) {
	    if ( strcasecmp( vp->dsview_template, template ) == 0 ) {
		break;
	    }
	}
	if ( vp != NULL ) {
	    break;
	}
    }

    if ( tsp == NULL || tsp->dstset_viewcount == 1 ) {
	return;	/* not part of a set at all or only one view in the set */
    }

    /* emit view switcher prefix */
    if (( s = get_arg_by_name( "prefix", argc, argv )) == NULL ) {
	s = "<TABLE CELLPADDING=6 BORDER=0><TR VALIGN=center>\n";
    }
    dsgw_emits( s );

    /* retrieve view item prefix and suffix arguments */
    if (( altprefix = get_arg_by_name( "altprefix", argc, argv )) == NULL ) {
	altprefix = "<TD BGCOLOR=#B0B0B0>\n";
    }
    if (( altsuffix = get_arg_by_name( "altsuffix", argc, argv )) == NULL ) {
	altsuffix = "</TD>\n";
    }
    if (( curprefix = get_arg_by_name( "curprefix", argc, argv )) ==
	    NULL ) {
	curprefix = "<TD BGCOLOR=#808080><FONT COLOR=#000000><B>\n";
    }
    if (( cursuffix = get_arg_by_name( "currentsuffix", argc, argv )) ==
	    NULL ) {
	cursuffix = "</B></FONT></TD>\n";
    }

    /* emit one table cell item (or similar) for each available view */
    for ( vp = tsp->dstset_viewlist; vp != NULL; vp = vp->dsview_next ) {
	if ( strcasecmp( vp->dsview_template, template ) == 0 ) {
	    dsgw_emitf( "%s%s%s", curprefix, vp->dsview_caption,
		    cursuffix );
	} else {
	    dsgw_emitf( "%s\n<A HREF=\"", altprefix );
	    if ( vp->dsview_jscript == NULL ) {
		dsgw_emitf( "javascript:EditEntryAs('%s')",
			vp->dsview_template );
	    } else {
		dsgw_substitute_and_output( vp->dsview_jscript, "--dn--",
			dn, 1 );
	    }
	    dsgw_emitf( "\">%s</A>\n%s", vp->dsview_caption, altsuffix );
	}
    }

    /* emit view switcher suffix */
    if (( s = get_arg_by_name( "suffix", argc, argv )) == NULL ) {
	s = "</TR></TABLE>\n";
    }
    dsgw_emits( s );
}


static void
do_attrvalset( dsgwtmplinfo *tip, char *dn, unsigned long dispopts,
	int argc, char **argv )
{
    dsgwavset	*avp;
    char	*s, *valuearg, *prefix, *suffix;
    int		i, setpos, len, maxvallen;

    /*
     * locate "set" element in argv array so we can replace it later
     * with "value="
     */
    if (( setpos = dsgw_get_arg_pos_by_name( DSGW_ARG_AVSET_SET, argc,
	    argv )) < 0 ) {
        dsgw_emitf( XP_GetClientStr(DBT_missingSN_), DSGW_ARG_AVSET_SET );
        return;
    }
    s = &argv[ setpos ][ 4 ];

    for ( avp = gc->gc_avsets; avp != NULL; avp = avp->dsavset_next ) {
	if ( strcasecmp( s, avp->dsavset_handle ) == 0 ) {
	    break;
	}
    }
    if ( avp == NULL ) {
	dsgw_emitf( XP_GetClientStr(DBT_unknownSetSN_), s );
	return;
    }

    prefix = get_arg_by_name( "prefix", argc, argv );
    suffix = get_arg_by_name( "suffix", argc, argv );

    /* repeatedly call on do_attribute() to perform all the difficult work */
    maxvallen = 0;
    valuearg = NULL;
    for ( i = 0; i < avp->dsavset_itemcount; ++i ) {
	if ( prefix != NULL ) {
	    dsgw_emits( prefix );
	}
	dsgw_emits( avp->dsavset_prefixes[ i ] );

	/* construct "value=XXX" arg. and place in argv array */
	if (( len = strlen( avp->dsavset_values[ i ] )) > maxvallen ||
		valuearg == NULL ) {
	    maxvallen = len;
	    valuearg = dsgw_ch_realloc( valuearg, maxvallen + 7 );
	}
	PR_snprintf( valuearg, maxvallen + 7, "value=%s", avp->dsavset_values[ i ] );
	argv[ setpos ] = valuearg;

	do_attribute( tip, dn, dispopts, argc, argv );

	dsgw_emits( avp->dsavset_suffixes[ i ] );
	if ( suffix != NULL ) {
	    dsgw_emitf( "%s\n", suffix );
	}
    }
}


static void
do_std_completion_js( char *template, int argc, char **argv )
{
    if ( template != NULL ) {
	dsgw_emitf(
		"<INPUT TYPE=\"hidden\" NAME=\"compjs_tmplname\" VALUE=\"%s\">\n",
		template);
	dsgw_emits(
		"<INPUT TYPE=\"hidden\" NAME=\"completion_javascript\" VALUE=\"STD\">\n");
    }
}


/*
 * function called back by dsgw_parse_line() to evaluate IF directives.
 * return non-zero for true, zero for false.
 */
static int
condition_is_true( int argc, char **argv, void *arg )
{
    dsgwtmplinfo	*tip;

    if ( argc < 1 ) {
	return( 0 );
    }

    tip = (dsgwtmplinfo *)arg; 

    if ( strcasecmp( argv[0], DSGW_COND_FOUNDENTRIES ) == 0 ) {
	return( tip->dsti_entrycount > 0 );
    }

    if ( strcasecmp( argv[0], DSGW_COND_ADDING ) == 0 ) {
	return(( tip->dsti_options & DSGW_DISPLAY_OPT_ADDING ) != 0 );
    }
 
    if ( strcasecmp( argv[0], DSGW_COND_EDITING ) == 0 ) {
	return(( tip->dsti_options & DSGW_DISPLAY_OPT_EDITABLE ) != 0 &&
		( tip->dsti_options & DSGW_DISPLAY_OPT_ADDING ) == 0 );
    }
 
    if ( strcasecmp( argv[0], DSGW_COND_DISPLAYING ) == 0 ) {
	return(( tip->dsti_options & DSGW_DISPLAY_OPT_EDITABLE ) == 0 );
    }

    if ( strcasecmp( argv[0], DSGW_COND_BOUND ) == 0 ) {
	/* We are not really considered to be bound if we are bound
	   as the binddn user */
	return( (dsgw_get_binddn() != NULL) && gc->gc_binddn && (0 == dsgw_dn_cmp(dsgw_get_binddn(), gc->gc_binddn)) );
    }

    if ( strcasecmp( argv[0], DSGW_COND_BOUNDASTHISENTRY ) == 0 ) {
	return( dsgw_bound_as_dn( tip->dsti_entrydn, 0 ));
    }

    if ( strcasecmp( argv[0], DSGW_COND_DISPLAYORGCHART ) == 0 ) {
      return(gc->gc_orgcharturl != NULL && ((tip->dsti_options & DSGW_DISPLAY_OPT_ADDING ) == 0));
    }

    if ( strcasecmp( argv[0], DSGW_COND_DISPLAYAIMPRESENCE ) == 0 ) {
      return((gc->gc_aimpresence == 1) && ((tip->dsti_options & DSGW_DISPLAY_OPT_ADDING ) == 0));
    }

    if ( strcasecmp( argv[0], DSGW_COND_HAVEAIMSCHEMA ) == 0 ) {
      return((gc->gc_haveaimschema == 1) && ((tip->dsti_options & DSGW_DISPLAY_OPT_ADDING ) == 0));
    }

    if ( strcasecmp( argv[0], DSGW_COND_ATTRHASVALUES ) == 0 ) {
	/*
	 * format of IF statment is:
	 *    <-- IF "AttributeHasValues" "ATTRIBUTE" "MINIMUM_COUNT" -->
	 * MINIMUM_COUNT is an optional number.
	 */
	struct berval	**vals;
	int	rc, minimum;

	if ( argc < 2 || tip->dsti_entry == NULL ||
		( vals = ldap_get_values_len( tip->dsti_ld,
		                       tip->dsti_entry, argv[1])) == NULL ) {
	    /* check "attrsonly" information if applicable */
	    if ( argc < 3 && tip->dsti_attrsonly_entry != NULL ) {
		(void)ldap_get_values_len( tip->dsti_ld, tip->dsti_attrsonly_entry,	argv[1]);
		if ( dsgw_ldap_get_lderrno( tip->dsti_ld, NULL, NULL )
			== LDAP_SUCCESS ) {
		    return( 1 );
		}
	    }
	    return( 0 );
	}
	minimum = ( argc < 3 ) ? 1 : atoi( argv[ 2 ] );
	rc = ( minimum <= 1 || ldap_count_values_len( vals ) >= minimum );
	ldap_value_free_len( vals );
	return( rc );
    }

    if ( strcasecmp( argv[0], DSGW_COND_ATTRHASTHISVALUE ) == 0 ) {
	/*
	 * format of IF statment is:
	 *    <-- IF "AttributeHasThisValue" "ATTRIBUTE" "SYNTAX" "VALUE" -->
	 */
	struct berval	**vals;
	int			i, rc;
	struct attr_handler	*ahp;
	struct berval 		thisarg;
	struct berval 		*thisargp;

	if ( argc < 4 ||  tip->dsti_entry == NULL ||
	     ( vals = ldap_get_values_len( tip->dsti_ld, tip->dsti_entry,
				       argv[1])) == NULL ) {
	    return( 0 );
	}
	if (( ahp = syntax2attrhandler( argv[2] )) == NULL ) {
	    dsgw_emitf( XP_GetClientStr(DBT_unknownSyntaxSN_1), argv[2] );
	    return( 0 );
	}

	rc = 0;
	thisarg.bv_val = argv[3]?argv[3]:"";
	thisarg.bv_len = argv[3]?strlen(argv[3]):0;
	thisargp = &thisarg;
	for ( i = 0; vals[ i ] && vals[ i ]->bv_val; ++i ) {
	    if ( dsgw_valcmp(ahp->ath_compare)( (const struct berval **)&vals[i],
		    (const struct berval **)&thisargp ) == 0 ) {
		rc = 1;
		break;
	    }
	}
	ldap_value_free_len( vals );
	return( rc );
    }

    /* pass unrecognized conditionals to simple conditional handler */
    return( dsgw_simple_cond_is_true( argc, argv, NULL ));
}

/*
 * Function: dsgw_get_values
 *
 * Returns: an array of values
 *
 * Description: This function returns the values of 
 *              an attribute, taking into account any
 *              possible language or phonetic tags.
 *              pass in something like "cn" and this function
 *              will return all cn's, tagged or not.
 *
 * Author: RJP
 *
 */
static struct berval ** 
dsgw_get_values( LDAP *ld, LDAPMessage *entry, 
		 const char *target ) 
{
    BerElement  *ber        = NULL;
    char        *attr       = NULL;
    char        *new_target = NULL;
    int          new_target_size = 0;
    struct berval **val_youse  = NULL;
    struct berval **temp_vals  = NULL;
    int          i          = 0;
    int          j          = 0;
    int          temp_val_count = 0;

    /* Allocate a new target that is the original plus a semicolon*/ 
    new_target = (char *) dsgw_ch_malloc (sizeof(char) * (strlen(target) + 2) );
    sprintf (new_target, "%s;", target);
    
    new_target_size = strlen(new_target);

    /* 
     * Go through the attributes and 
     * compare the new_target with the attr name
     */
    for ( attr = ldap_first_attribute( ld, entry, &ber ); attr != NULL; 
	  attr = ldap_next_attribute( ld, entry, ber ) ) {
	
	/* If the "target;" matches the attribute name, get the values*/
	if ( strcasecmp(attr, target) == 0 ||
	     strncasecmp (attr, new_target, new_target_size) == 0) {
	    temp_vals =  ldap_get_values_len( ld, entry, attr );
	    
	    if (temp_vals == NULL) {
		continue;
	    }
	    
	    /* Find the next open spot in val_youse*/
	    if (val_youse) {
		for (; val_youse[i] && val_youse[i]->bv_val; i++) ;
	    }

	    /* Count the number of values in temp_vals */
	    for (temp_val_count = 0; temp_vals[temp_val_count] != NULL;
		 temp_val_count++);
	    
	    /* Realloc */
	    val_youse = (struct berval **) dsgw_ch_realloc (val_youse, sizeof(struct berval *) * (temp_val_count + i + 1) );
	    
	    /* Start there and copy over the pointers from temp_vals */
	    for (j = 0; j < temp_val_count; j++, i++) {
		val_youse[i] = temp_vals[j];
	    }
	    
	    val_youse[i] = NULL;
	    
	    ldap_memfree(temp_vals);
	    
	}
    }
    
    /* Free the BerElement from memory when done */
    
    if ( ber != NULL ) {
	
	ber_free( ber, 0 );
	
    }
    
    free (new_target);
    
    return(val_youse);
}

/*
 * Function: dsgw_time
 *
 * Returns: a string not unlike the string returned from ctime()
 *          except it's localized
 *
 * Description: this function takes the number of seconds since 1970
 *              and converts it to a localized string version of that.
 *              First it tries to use the clientLanguage, if that fails,
 *              It tries the default language. if that fails, it returns
 *              NULL
 *
 * Author: RJP
 *
 */
static char *
dsgw_time(time_t secs_since_1970) 
{
  UDateFormat *edatefmt;
  UErrorCode err = U_ZERO_ERROR;
  UChar *dstr0;
  static char obuf[BSIZ];
  UDate tmp_dat;
  char *locale = NULL;
  int32_t myStrlen = 0;

  /* Create a Date/Time Format using the locale */
  locale = dsgw_get_locale_from_accept_language();

  edatefmt = udat_open(
	  UDAT_DEFAULT, /* default date style for locale */
	  UDAT_DEFAULT, /* default time style for locale */
	  locale,
	  NULL, 0, /* use default timezone */
	  NULL, 0, /* no pattern */
	  &err);

  free(locale);
  locale = NULL;

  if (!edatefmt || (err != U_ZERO_ERROR)) {
    dsgw_error( DSGW_ERR_LDAPGENERAL, NULL, DSGW_ERROPT_EXIT, err, NULL );
    /*fprintf(stderr, "ERROR: NLS_NewDateTimeFormat(0): %d\n", err);*/
  }

  /* Get Current Date/Time */
  tmp_dat = (UDate) secs_since_1970;
  tmp_dat *= 1000.00;

  /* Format using the first Date/Time format */
  myStrlen = udat_format(edatefmt, tmp_dat, NULL, myStrlen, NULL, &err);
  if(err == U_BUFFER_OVERFLOW_ERROR){
    err = U_ZERO_ERROR;
    dstr0 = (UChar*)dsgw_ch_malloc(sizeof(UChar) * (myStrlen+1) );
    myStrlen = udat_format(edatefmt, tmp_dat, dstr0, myStrlen+1, NULL, &err);
  }

  if (err != U_ZERO_ERROR) {
    dsgw_error( DSGW_ERR_LDAPGENERAL, NULL, DSGW_ERROPT_EXIT, err, NULL );
    /*fprintf(stderr, "ERROR: NLS_FormatDate(1): %d\n", err);*/
  }

  /* convert to utf8 */
  u_strToUTF8(obuf, sizeof(obuf), NULL, dstr0, myStrlen, &err);

  if (err != U_ZERO_ERROR) {
    dsgw_error( DSGW_ERR_LDAPGENERAL, NULL, DSGW_ERROPT_EXIT, err, NULL );
    /*fprintf(stderr, "ERROR: NLS_NewEncodingConverter(0): %d\n", err);*/
  }
  /*fprintf(stdout, "Date(0): %s\n", obuf);*/

  /* Clean up -- but may not be enough... :) */
  free(dstr0);
  
  udat_close(edatefmt);
  edatefmt = NULL;
  
  return( (char *) obuf);
}

/*
  emacs settings
  Local Variables:
  indent-tabs-mode: t
  tab-width: 8
  End:
*/