A
download API.php
Language: PHP
LOC: 1988
Project Info
FreeMED Project(freemed)
Server: SourceForge
Type: cvs
...reemed\freemed\freemed\lib\
   acl.php
   API.php
   bcadd.php
   calendar-functions.php
   class.AdminModule.php
   class.Agata.php
   class.Authorizations.php
   class.BaseModule.php
   class.BillingModule.php
   class.CalendarModule.php
   class.ClaimLog.php
   class.Coverage.php
   class.Debug.php
   class.diagnosis_set.php
   class.Djvu.php
   class.EMRModule.php
   class.Fax.php
   class.FixedFormEntry.php
   ...s.FixedFormRenderer.php
   class.FormRenderer.php
   class.FreeMEDSelfTest.php
   class.GeneralConfig.php
   class.GraphModule.php
   class.Guarantor.php
   class.Handler_HL7v2.php
   ...s.Handler_HL7v2_A04.php
   ...s.Handler_HL7v2_A08.php
   ...s.Handler_HL7v2_S12.php
   ...s.Handler_HL7v2_S15.php
   class.InsuranceCompany.php
   class.LanguageRegistry.php
   class.Ledger.php
   ...s.MaintenanceModule.php
   class.Messages.php
   class.OMBS_Patient.php
   class.OMBS_Wrapper.php
   class.Parser_HL7v2.php
   class.Patient.php
   class.Payer.php
   class.PHPlot.php
   class.Physician.php
   class.Procedure.php
   class.RecordLock.php
   class.Remitt.php
   class.ReportsModule.php
   class.rxlist.php
   class.Scheduler.php
   class.TeX.php
   class.User.php
   class.UtilityModule.php
   class.vCalendar.php
   class.vCalendarEvent.php
   error_handler.php
   freemed.php
   i18n.php
   iso-set.php
   macros.php
   mail-functions.php
   settings.php
   settings.php.tmpl
   xml.php
   xmlrpc_services.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
<?php
	// $Id: API.php,v 1.134 2005/05/11 01:03:39 rufustfirefly Exp $
	// $Author: rufustfirefly $

// File: Core API
//
//	This is the main FreeMED API, which contains the bulk of FreeMED's
//	commonly used functions. The rest of the functions are located in
//	classes which are called dynamically using CreateObject(). It is
//	located in lib/API.php.
//

if (!defined("__API_PHP__")) {

define ('__API_PHP__', true);

// namespace/class freemed
class freemed {
	// Function: freemed::acl
	//
	//	Query ACL for a particular resource.
	//
	// Parameters:
	//
	//	$category - Which category of ARO is being queried. Examples
	//	would be things like 'admin', 'bill', 'schedule', et cetera.
	//
	//	$permission - Resource being queried. This would be things
	//	like 'add', 'modify', 'view', 'delete', et cetera.
	//
	//	$axo_group - (optional) AXO group to be searched on. Note
	//	that valid groups are things like 'patient'.
	//
	//	$axo_item - (optional) AXO item. This would be the patient
	//	ID key for a patient, or something else for another AXO
	//	group.
	//
	// Returns:
	//
	//	Boolean, depending on whether the resource is allowed or denied.
	//
	function acl ( $category, $permission, $axo_group=NULL, $axo_item=NULL ) {
		// For now, we test with just the user group specified. We
		// can expand to do internet addresses, et cetera, from
		// inside this.

		// Derive user group(s)
		global $this_user;
		if (!is_object($this_user)) { $this_user = CreateObject('_FreeMED.User'); }

		// Split groups up into array
		$groups = explode(',', $this_user->local_record['userlevel']);

		// Add "group" with the current user ARO object
		$groups[] = 'user_'.$this_user->user_number;

		// Loop for each one
		foreach ($groups as $user_group) {
			//global $display_buffer; $display_buffer .= "group = $user_group<br/>\n";
			// Test most granular to least granular
			if ($axo_group AND $axo_item) {
				// Query with AXO
				$a = $GLOBALS['acl']->acl_query (
					$category,
					$permission,
					'individual',
					$user_group,
					$axo_group,
					$axo_item
				);
				if ($a['allow'] == 1) { return true; }
			} else {
				// Query, no AXO
				$a = $GLOBALS['acl']->acl_query (
					$category,
					$permission,
					'user',
					$user_group
				);
				if ($a['allow'] == 1) { return true; }
			}
		} // end foreach user group

		// If all else fails, return false
		return false;
	} // end function freemed::acl

	// Function: freemed::acl_patient
	//
	//	Check ACLs, optionally with patient access. Note that this
	//	function behaves exactly like <freemed::acl> if the
	//	acl_patient configuration value is disabled.
	//
	// Parameters:
	//
	//	$category - Which category of ARO is being queried. Examples
	//	would be things like 'admin', 'bill', 'schedule', et cetera.
	//
	//	$permission - Resource being queried. This would be things
	//	like 'add', 'modify', 'view', 'delete', et cetera.
	//
	//	$pid - Patient id number (record id) for patient being
	//	checked.
	//
	// Returns:
	//
	//	Boolean, whether access is granted.
	//
	// See Also:
	//	<freemed::acl>
	//
	function acl_patient ( $category, $permission, $pid ) {
		if (freemed::config_value('acl_patient')) {
			// Advanced check for patient ACL as well
			$r_acl = freemed::acl($category, $permission);
			$p_acl = freemed::acl($category, $permission, 'patient', 'patient_'.$pid);
			// Decide on combination of regular and patient ACLs
			if ($p_acl == 1) {
				return true;
			}
			return false;
		} else {
			// Basic perms check
			return freemed::acl($category, $permission);
		}
	} // end function freemed::acl_patient

	// Function: freemed::check_access_for_facility
	//
	//	Checks to see if the current user has access to the specified
	//	facility.
	//
	// Parameters:
	//
	//	$facility_number - the database id of the facility in question
	//
	// Returns:
	//
	//	$access - boolean value, whether access is granted
	//
	// See Also:
	//
	//	<freemed::check_access_for_patient>
	//
	function check_access_for_facility ($facility_number) {
		global $_SESSION;

		// Separate out authdata
		$authdata = $_SESSION['authdata'];

		// Root has all access...
		if ($_SESSION['authdata']['user'] == 1) return true;

		// Grab the authorizations field
		$f_fac = freemed::get_link_field ($authdata['user'], "user", "userfac");

		// No facility, assume no access restrictions
		if ($facility_number == 0) return true;

		// If it's an "ALL" or it is found, return true
		if ((fm_value_in_string($f_fac, "-1")) OR
				(fm_value_in_string($f_fac, $facility_number)))
			return true;

	    	// Default to false
		return false;
	} // end function freemed::check_access_for_facility

	// Function: freemed::check_access_for_patient
	//
	//	Checks to see whether the current user has access to the
	//	specified patient.
	//
	// Parameters:
	//
	//	$patient_number - The database identifier for the patient
	//
	//	$user (optional) - The database identifier for the current
	//	user. (This should be used when dealing with XML-RPC or
	//	another protocol which does not use cookie-based authentication.
	//
	// Returns:
	//
	//	$access - boolean, whether access is granted
	//
	// See Also:
	//
	//	<freemed::check_access_for_facility>
	//
	function check_access_for_patient ($patient_number, $_user=0) {
		if ($_user == 0) {
			// Grab authdata
			$_authdata = $_SESSION['authdata'];
			$user = $_authdata['user'];
		} else {
			$user = $_user;
		}
		
		//eventually logging should include different messages for all returns here...
		// Root has all access...
		if ($user == 1) return true;
	
		// Grab auth information from db
		$f_user   = freemed::get_link_rec ($user, "user");
	
		// Get data records in question for the user
		$f_fac    = $f_user ["userfac"   ];
		$f_phy    = $f_user ["userphy"   ];
		$f_phygrp = $f_user ["userphygrp"];
	
		// Retrieve patient record
		$f_pat    = freemed::get_link_rec ($patient_number, "patient");
		// check for universal access
		if ((fm_value_in_string ($f_fac,    "-1")) OR
			(fm_value_in_string ($f_phy,    "-1")) OR
			(fm_value_in_string ($f_phygrp, "-1")))
			return true;
	
		// Check for physician in any physician fields
		if (($f_pat["ptpcp"]>0) AND
			(fm_value_in_string ($f_phy, $f_pat["ptpcp"])))
			return true;
		if (($f_pat["ptphy1"]>0) AND
			(fm_value_in_string ($f_phy, $f_pat["ptphy1"])))
			return true;
		if (($f_pat["ptphy2"]>0) AND
			(fm_value_in_string ($f_phy, $f_pat["ptphy2"])))
			return true;
		if (($f_pat["ptphy3"]>0) AND
			(fm_value_in_string ($f_phy, $f_pat["ptphy3"])))
			return true;
		if (($f_pat["ptdoc"]>0) AND
			(fm_value_in_string ($f_phy, $f_pat["ptdoc"])))
			return true;

	    	// Default to false
		return false;
	} // end function freemed::check_access_for_patient

	// Function: freemed::config_value
	//
	//	Retrieves a configuration value from FreeMED's centralized
	//	configuration database table.
	//
	// Parameters:
	//
	//	$key - The name of the configuration value desired.
	//
	// Returns:
	//
	//	$value - The value of the configuration key, or NULL if the
	//	key is not found.
	//
	function config_value ($config_var) {
		static $_config;
		global $sql;
	 
 		// Set to cache values
 		if (!isset($_config)) {
			$query = $sql->query("SELECT * FROM config");
	
			// If the table doesn't exist, skip out
			if (!$query) return false;
	
			// Loop through results
			while ($r = $sql->fetch_array($query)) {
				$_config[stripslashes($r[c_option])] =
					stripslashes($r[c_value]);
			} // end of looping through results
		} // end of caching
	
		// Return from cache
		return $_config["$config_var"];
	} // end function freemed::config_value

	// Function: freemed::config_user_value
	//
	//	Check configuration value against user database then
	//	system configuration database.
	//
	// Parameters:
	//
	//	$key - The name of the configuration value desired.
	//
	// Returns:
	//
	//	$value - The value of the configuration key, or NULL if the
	//	key is not found.
	//
	// See Also:
	//	<freemed::config_value>
	//
	function config_user_value ( $key ) {
		static $_cache;

		if (!isset($_cache)) {
			$u = CreateObject('FreeMED.User');
			$_cache = $u->manage_config;
		}

		if (!empty($_cache[$key])) {
			// Use user value
			return $_cache[$key];
		} else {
			// Default to system-wide setting
			return freemed::config_value($key);
		}
	} // end function freemed::config_user_value

	// Function: freemed::connect
	//
	//	Master function to run authentication routines for the
	//	current used. This method should be called at the beginning
	//	of every standalone FreeMED script when dealing with standard
	//	session based authentication.
	//
	function connect () {
		global $display_buffer;

		// Verify
		if (!freemed::verify_auth()) {
			$display_buffer .= "
			<div ALIGN=\"CENTER\">
			<b>".__("You have entered an incorrect username or password.")."</b>
			<br/><br/>
			<b><i>".__("It is possible that your cookies have expired.")."</i></b>
			<p/>
			".template::link_button(
				__("Return to the Login Screen"),
				"index.php"
			)."
			</div>
			";
			template_display();
		} // end if connected loop
	} // end function freemed::connect
	
	// Function: freemed::drug_widget
	//
	//	Creates a drug selection widget.
	//
	// Parameters:
	//
	//	$varname - Name of the variable which should contain the
	//	drug name.
	//
	//	$formname (optional) - Name of the form that contains this
	//	widget. Defaults to "myform".
	//
	//	$submitname (optional) - Name of the variable that is used
	//	to pass data between the child window and the parent window.
	//	Defaults to "submit_action".
	//
	// Returns:
	//
	//	$widget - XHTML compliant widget code
	//
	function drug_widget ( $varname, $formname="myform", $submitname="submit_action" ) {
		global ${$varname};

		// Switch depending on configuration value
		switch (freemed::config_value('drug_widget_type')) {
			case 'combobox':
			// Values from simple distinct ...
			//$values = $GLOBALS['sql']->distinct_values( 'rx', 'rxdrug');
			// Use frequency
			$q = "select rxdrug, count(rxdrug) as occur from rx where length(rxdrug) > 3 group by rxdrug order by occur desc";
			$result = $GLOBALS['sql']->query($q);
			while ($r = $GLOBALS['sql']->fetch_array($result)) {
				$values[stripslashes($r['rxdrug'])] = stripslashes($r['rxdrug']);
			}
			return html_form::combo_widget(
				$varname,
				$values
			);
			break; // end case combobox
			
			// Keep rxlist as the default setting
			case 'rxlist': default:
			// If it is set, show drug name, else widget
			if (!empty(${$varname})) {
				return "<INPUT TYPE=\"HIDDEN\" ".
				"NAME=\"".prepare($varname)."\" ".
				"VALUE=\"".prepare(${$varname})."\"/>".
				${$varname}." ".
				"<input class=\"button\" TYPE=\"BUTTON\" ".
				"onClick=\"drugPopup=window.open(".
				"'drug_lookup.php?varname=".
				urlencode($varname)."&submitname=".
				urlencode($submitname)."&formname=".
				urlencode($formname)."', 'drugPopup'); ".
				"drugPopup.opener=self; return true;\" ".
				"VALUE=\"".__("Change")."\"/>";
			} else {
				return "<input type=\"HIDDEN\" ".
				"name=\"".prepare($varname)."\"/>".
				"<input class=\"button\" type=\"BUTTON\" ".
				"onClick=\"drugPopup=window.open(".
				"'drug_lookup.php?varname=".
				urlencode($varname)."&submitname=".
				urlencode($submitname)."&formname=".
				urlencode($formname)."', 'drugPopup', ".
				"'width=400,height=200,menubar=no,titlebar=no'); ".
				"drugPopup.opener=self; return true;\" ".
				"value=\"".__("Drug Lookup")."\"/>";
			}
			break; // end default action
		} // end switch
	} // end function freemed::drug_widget

	// Function: freemed::get_link_rec
	//
	//	Get a database table record by its "id" field.
	//
	// Parameters:
	//
	//	$id - Value of the id field requested.
	//
	//	$table - Name of the FreeMED database table.
	//
	// Returns:
	//
	//	$rec - Associative array / hash containing key and value
	//	pairs, where the key is the name of the database table
	//	field, and its associated value is the value found in the
	//	database.
	//
	//	$force_no_cache - (optional) Boolean, allows defeating of
	//	automatic caching, which will distrupt sequential
	//	operations. Defaults to false.
	//
	// See Also:
	//	<freemed::get_link_field>
	//
	function get_link_rec($id="0", $table="", $force_no_cache=false) {
		global $sql;
		static $_cache;

		// Handle EMRi URL
		if (!(strpos($id, "emri://") === false)) {
			return EMRi::get_link_rec($id);
		}

		// If no database is available, trigger error
		if (empty($table))
			trigger_error ("freemed::get_link_rec: no table provided",
				E_USER_ERROR);

		// Check to see if it's cached
		if (!isset($_cache[$table][$id]) or $force_no_cache) {
			// Perform the actual query
			$result = $sql->query("SELECT * FROM ".addslashes($table)." ".
				"WHERE id='".addslashes($id)."'");
			// Fetch the array from the result into cache
			$_cache[$table][$id] = $sql->fetch_array($result);
		}

		// Return member from cache
		return $_cache[$table][$id];
	} // end function freemed::get_link_rec

	// Function: freemed::get_link_field
	//
	//	Return a single field from a particular database table
	//	from its "id" field.
	//
	// Parameters:
	//
	//	$id - Value of the id field requested.
	//
	//	$table - Name of the FreeMED database table.
	//
	//	$field - Name of the field in the database table.
	//
	// Returns:
	//
	//	$val - Scalar value of the database table field.
	//
	// See Also:
	//	<freemed::get_link_rec>
	//
	function get_link_field($id, $table, $field="id") {
		// Die if no table was passed
		if (empty($table))
			trigger_error ("freemed::get_link_field: no table provided",
				E_USER_ERROR);

		// Retrieve the entire record
		$this_array = freemed::get_link_rec($id, $table);

		// TODO: Get this to automatically deserialize serialized
		// data so that we can transparently get arrays. Probably
		// would break some phenomenal amount of code.

		// Return just the key asked for
		return $this_array["$field"];
	} // end function freemed::get_link_field

	// Function: freemed::handler_breakpoint
	//
	//	Set breakpoint for handlers for a certain function
	//
	// Parameters:
	//
	//	$name - Name of handler (example: MainMenuNotify)
	//
	//	$params - Array of parameters to be passed to the
	//	associated handlers. None are passed by default.
	//
	function handler_breakpoint ( $name, $params = NULL ) {
		$handlers = freemed::module_handler($name);
		if (is_array($handlers)) {
			foreach ($handlers AS $class => $handler) {
				if ($params != NULL) {
					$reply[] = module_function ($class, $handler, $params);
				} else {
					$reply[] = module_function ($class, $handler);
				}
			}
			return $reply;
		}
		return false;
	} // end function freemed::handler_breakpoint

	// Function: freemed::itemlist_conditions
	//
	//	Creates an SQL "WHERE" clause based on search information
	//	provided by <freemed::display_itemlist>, as used by most
	//	of FreeMED's modules.
	//
	// Parameters:
	//
	//	$where (optional) - Boolean value, whether a "WHERE" should
	//	be prepended to the returned query. Defaults to true.
	//
	// Returns:
	//
	// 	$clause - SQL query "WHERE" clause
	//
	function itemlist_conditions($where = true) {
		if (strlen($GLOBALS['_s_val']) > 0) {
			$field = addslashes($GLOBALS['_s_field']);
			$val = addslashes($GLOBALS['_s_val']);
			return ( $where ? " WHERE ( " : " AND ( " ).
				$field." = '".$val."' OR ".
				$field." LIKE '%".$val."' OR ".
				$field." LIKE '".$val."%' OR ".
				$field." LIKE '%".$val."%' ) ";
		}
	} // end function freemed::itemlist_conditions

	// Function: freemed::image_filename
	//
	//	Resolves a stored document's full path based on the qualifiers
	//	presented.
	//
	// Parameters:
	//
	//	$patient - Patient identifier
	//
	//	$record - Record identifier of the "images" table
	//
	//	$type - File type (usually "djvu")
	//
	//	$img_store (optional) - Boolean, whether or not
	//	the relative pathname will be prepended (usually "img/store/").
	//
	// Returns:
	//
	//	The relative path and file name of the image.
	//
	function image_filename($patient, $record, $type, $img_store = true) {
		$m = md5($patient);
		return ($img_store ? 'img/store/' : '' ).
			$m[0].$m[1].'/'.
			$m[2].$m[3].'/'.
			$m[4].$m[5].'/'.
			$m[6].$m[7].'/'.
			substr($m, -(strlen($m)-8)).
			'/'.$record.'.'.$type;
	} // end method freemed::image_filename

	// Function: freemed::key_binding
	//
	//	Set key binding for a particular key or set of keys.
	//
	// Parameters:
	//
	//	$binding - Associative array of key code => binding.
	//
	function key_binding ( $binding ) {
		if (!is_array($binding)) { return false; }
		foreach ($binding AS $k => $b) {
			if ($k and $b) {
				$GLOBALS['__freemed']['key_bindings'][$k] = $b;
			}
		}
	} // end method freemed::key_binding

	// Function: freemed::module_check
	//
	//	Determines whether a module is installed in the system,
	//	and optionally whether it is above a certain minimum
	//	versioning number.
	//
	// Parameters:
	//
	//	$module - Name of the module
	//
	//	$minimum_version (optional) - The minimum allowable version
	//	of the specified module. If this is not specified, any
	//	version will return true.
	//
	// Returns:
	//
	//	$installed - Boolean, whether the module is installed
	//
	function module_check ($module, $minimum_version="0.01")
	{
		static $_config; global $sql;

		// cache all modules  
		if (!is_array($_config)) {
			unset ($_config);
			$query = $sql->query("SELECT * FROM module");
			while ($r = $sql->fetch_array($query)) {
				extract ( $r );
				$_config["$module_name"] = $module_version;
			} // end of while results
		} // end caching modules config
	
		// check in cache for version > minimum_version
		return version_check($_config["$module"], $minimum_version);
	} // end function freemed::module_check

	// Function: freemed::module_check_acl
	//
	//	Check to see if module is allowable via ACLs
	//
	// Parameters:
	//
	//	$module - Module class name
	//
	//	$permission - Permission type (view, add, mod, et cetera)
	//
	// Returns:
	//
	//	Boolean value, true or false
	//
	function module_check_acl ( $module, $permission='' ) {
		// Get meta value for acl
		$m_acl = freemed::module_get_meta ( $module, 'acl' );
		if (!is_array($m_acl)) {
			// By default if there are no restrictions, allow
			return true;
		} else {
			// Check each individual ACL specified, if any work, ok
			foreach ( $m_acl AS $__grbge => $v ) {
				if (!$permission) {
					switch ($v) {
						case 'bill': $p = 'menu'; break;
						default: $p = 'view'; break;
					}
				} else {
					$p = $permission;
				}
				if (freemed::acl($v, $p)) { return true; }
			} // end foreach m_acl

			// If nothing passes, we fail
			return false;
		} // end if not array
	} // end function module_check_acl

	// Function: freemed::module_get_value
	//
	//	Gets a cached module value (such as "MODULE_NAME", etc)
	//	from the module cache.
	//
	// Parameters:
	//
	//	$module - Name of the module
	//
	//	$key - Variable name in question
	//
	// Returns:
	//
	//	$val - Value of the variable name in question 
	//
	// See Also:
	//	<freemed::module_get_meta>
	//
	function module_get_value ($module, $key) {
		// Get module list object
		$module_list = freemed::module_cache();

		// Not in the list, then we just skip it
		if (!$module_list->check_for($module)) {
			return false;
		}

		foreach ($GLOBALS['__phpwebtools']['GLOBAL_MODULES'] as $k => $v) {
			if (strtolower($v['MODULE_CLASS']) == strtolower($module)) {
				return $v[$key];
			}
		}

		// If all else fails, return false
		return false;
	} // end function freemed::module_get_value

	// Function: freemed::module_get_meta
	//
	//	Gets cached metainformation for the specified module in
	//	the module cache. Acts as a wrapper for
	//	<freemed::module_get_value>.
	//
	// Parameters:
	//
	//	$module - Name of the module
	//
	//	$key - Hash index of the metainformation in question
	//
	// Returns:
	//
	//	$val - Value of the metainformation in question 
	//
	// See Also:
	//	<freemed::module_get_value>
	//
	function module_get_meta ($module, $key) {
		$module_list = freemed::module_cache();

		// Not in the list, then we just skip it
		if (!$module_list->check_for($module)) {
			return false;
		}

		foreach ($GLOBALS['__phpwebtools']['GLOBAL_MODULES'] as $k => $v) {
			if (strtolower($v['MODULE_CLASS']) == strtolower($module)) {
				return $v['META_INFORMATION'][$key];
			}
		}

		// If all else fails, return false
		return false;
	} // end function freemed::module_get_meta

	// Function: freemed::module_cache
	//
	//	Provides global access to a PHP.module_list object with
	//	cached module information.
	//
	// Returns:
	//
	//	$cache - An object (PHP.module_list) containing the
	//	cached module information.
	//
	function module_cache () {
		static $_cache;
		if (!isset($_cache)) {
			$_cache = CreateObject(
				'PHP.module_list',
				PACKAGENAME,
				array(
					'cache_file' => 'data/cache/modules',
					'recursive' => true
				)
			);
		}
		return $_cache;
	} // end function freemed::module_cache

	// Function: freemed::module_handler
	//
	//	Returns the list of modules associated with a certain handler.
	//
	// Parameters:
	//
	//	$handler - Scalar name of the handler. This is case sensitive.
	//
	// Returns:
	//
	//	$modules - Array of modules which are associated with the
	//	specified handler. These all will be in lowercase, so
	//	remember to use strtolower().
	//
	function module_handler ($handler) {
		// Get module list object
		$module_list = freemed::module_cache();

		// Loop through modules
		foreach ($GLOBALS['__phpwebtools']['GLOBAL_MODULES'] as $k => $v) {
			// Check to see if this handler is registered
			if (!empty($v['META_INFORMATION']['__handler']["$handler"])) {
				$handler_data[strtolower($v['MODULE_CLASS'])] = $v['META_INFORMATION']['__handler']["$handler"];
			}
		}

		// Return composite
		return $handler_data;
	} // end function freemed::module_handler

	// Function: freemed::module_lookup
	//
	//	Lookup the module name as needed by FreeMED's module calls,
	//	but by the class name of the module.
	//
	// Parameters:
	//
	//	$class - Class name of the module
	//
	// Returns:
	//
	//	$module - MODULE_NAME of the specified module.
	//
	function module_lookup ($module) {
		// Get module list object
		$module_list = freemed::module_cache();

		// Not in the list, then we just skip it
		if (!$module_list->check_for($module)) {
			return false;
		}

		// Use protected __phpwebtools array to get module name
		foreach ($GLOBALS['__phpwebtools']['GLOBAL_MODULES'] as $k => $v) {
			if (strtolower($v['MODULE_CLASS']) == strtolower($module)) {
				return $v['MODULE_NAME'];
			}
		}

		// If all else fails, return false
		return false;
	} // end function freemed::module_lookup

	// Function: freemed::module_register
	//
	//	Registers module or newer version of module in FreeMED's
	//	global module registry.
	//
	// Parameters:
	//
	//	$module - Name of module (must be resolved using
	//	freemed::module_lookup, or by using MODULE_NAME).
	//
	//	$version - Version of module to register.
	//
	function module_register ($module, $version) {
		global $sql;

		// check for modules  
		if (!freemed::module_check($module, $version)) {
			// Check for preexisting module record
			$q = $sql->query("SELECT * FROM module ".
				"WHERE module_name='".
				addslashes($module)."'");
			if (!$sql->results($q)) {
				$query = $sql->query($sql->insert_query(
					'module',
					array (
						'module_name' => $module,
						'module_version' => $version
					)
				));
			} else {
				// Perform update query
				$query = $sql->query($sql->update_query(
					'module',
					array (
						'module_version' => $version
					),
					array (
						'module_name' => $module
					)
				));
			}
			return (!empty($query));
		} // end checking for module installed

		return true;
	} // end function freemed::module_register

	// Function: freemed::module_version
	//
	//	Get the current version number of a particular module in
	//	FreeMED from the module database table.
	//
	// Parameters:
	//
	//	$module - Name of module (must be resolved using
	//	freemed::module_lookup, or by using MODULE_NAME).
	//
	function module_version ($module) {
		static $_config; global $sql;

		// cache all modules  
		if (!is_array($_config)) {
			unset ($_config);
			$query = $sql->query("SELECT * FROM module");
			while ($r = $sql->fetch_array($query)) {
				extract ( $r );
				$_config["$module_name"] = $module_version;
			} // end of while results
		} // end caching modules config

		// check in cache for version
		return $_config["$module"];
	} // end function freemed::module_version

	// Function: freemed::multiple_choice
	//
	//	Create a multiple-choice widget
	//
	// Parameters:
	//
	//	$sql_query
	//
	//	$display_field - Hash of the field display format, with
	//	'##' surrounding the members of the table. (For example:
	//	'##phylname##, ##phyfname##' from a query on the physician
	//	table would print their last name and first name separated
	//	by a comma.)
	//
	//	$select_name - Name of the variable that the widget is
	//	specifying.
	//
	//	$blob_data - The actual compressed data string which contains
	//	the array of values.
	//
	//	$display_all (optional)
	//
	// Returns:
	//
	//	XHTML-compliant multiple choice widget code.
	//
	function multiple_choice ($sql_query, $display_field, $select_name,
			$blob_data, $display_all=true) {
		global $sql;
		$buffer = "";

		$brackets = "[]";
		$result = $sql->query ($sql_query); // check
		$all_selected = fm_value_in_string ($blob_data, "-1");

		$buffer .= "<select ID=\"".$select_name."\" NAME=\"".$select_name."[]\" multiple SIZE=\"5\">\n";
		if ($display_all) {
			$buffer .= "<option VALUE=\"-1\" ".
			($all_selected ? "selected" : "").">".__("ALL")."</option>\n";
		}
	
		if ( $sql->results ($result) ) {
			while ($r = $sql->fetch_array ($result)) {
				if (!(strpos ($display_field, "##") === false)) {
					$displayed = ""; // set as null
					$f_split = explode ("##", $display_field);
					foreach ($f_split AS $f_k => $f_v) {
						if (!($f_k & 1) ) {
							$displayed .= $f_v;
						} else {
							$displayed .= prepare($r[$f_v]);
						}
					}
				} else { // if it is only one field
					$displayed = stripslashes($r[$display_field]);
				} // end if-else displayed loop
				$buffer .= "
				<option VALUE=\"".prepare($r['id'])."\" ".
				( (fm_value_in_string ($blob_data, $r['id'])) ? "selected" : "" ).
				">$displayed".( $debug ? " [".$r['id']."]" : "" )."</option>\n";
			} // end while
		} // end checking for results
		$buffer .= "</select>\n"; // end the select tag
		return $buffer;
	} // end function freemed::multiple_choice

	// Function: freemed::patient_box
	//
	//	Create a "patient box" with quick access to various patient
	//	functions.
	//
	// Parameters:
	//
	//	$patient_object - An object of type 'FreeMED.Patient' which
	//	encapsulates the selected patient's data.
	//
	// Returns:
	//
	//	XHTML compliant patient box widget code.
	//
	function patient_box ($patient_object) {
		// Catch to make sure it's an actual object
		if (!is_object($patient_object)) return NULL;
		
		// Make sure template functions are included
		include_once(freemed::template_file('lib.php'));

		return template::patient_box($patient_object);	
	} // end function freemed::patient_box

	// Function: freemed::patient_widget
	//
	//	Create a patient selection widget
	//
	// Parameters:
	//
	//	$varname - The name of the variable that this widget
	//	contains data for.
	//
	//	$formname (optional) - Name of the form that this widget is
	//	contained in. Defaults to "myform".
	//
	//	$submitname (optional) - The name of the submit button which
	//	is passed to the child window that is created. Defaults to
	//	"submit_action".
	//
	//	$autosubmit - (optional) Whether or not to submit on click.
	//	Boolean, defaults to false.
	//
	// Returns:
	//
	//	XHTML compliant patient selection widget code.
	//
	function patient_widget ( $varname, $formname="myform", $submitname="submit_action", $autosubmit = false ) {
		global ${$varname};

		include_once(freemed::template_file('ajax.php'));
		if (${$varname}) { $_obj = CreateObject('FreeMED.Patient', ${$varname}); }
		return ajax_widget($varname, 'patient', $_obj, 'id', $autosubmit);

		// If it is set, show patient name, else widget
		if (${$varname} > 0) {
			$this_patient = CreateObject('FreeMED.Patient', ${$varname});	
			return "<input TYPE=\"HIDDEN\" ".
				"NAME=\"".prepare($varname)."\" ".
				"VALUE=\"".prepare(${$varname})."\"/>".
				$this_patient->fullName()." (".
				$this_patient->ptdob.") ".
				"<input class=\"button\" TYPE=\"BUTTON\" ".
				"onClick=\"patientPopup=window.open(".
				"'patient_lookup.php?varname=".
				urlencode($varname)."&submitname=".
				urlencode($submitname)."&formname=".
				urlencode($formname)."', 'patientPopup', ".
				"'width=450,height=250,menubar=no,titlebar=no'); ".
				"patientPopup.opener=self; return true;\" ".
				"VALUE=\"".__("Change")."\"/>\n".
				"<input class=\"button\" TYPE=\"BUTTON\" ".
				"onClick=\"document.".$formname.".".
					$varname.".value = ''; ".
					"document.".$formname.".submit();\" ".
				"VALUE=\"".__("Remove")."\"/>\n";
		} else {
			return "<input TYPE=\"HIDDEN\" ".
				"NAME=\"".prepare($varname)."\"/>".
				"<input TYPE=\"BUTTON\" ".
				"onClick=\"patientPopup=window.open(".
				"'patient_lookup.php?varname=".
				urlencode($varname)."&submitname=".
				urlencode($submitname)."&formname=".
				urlencode($formname)."', 'patientPopup', ".
				"'width=450,height=250,menubar=no,titlebar=no'); ".
				"patientPopup.opener=self; return true;\" ".
				"VALUE=\"".__("Patient Lookup")."\" ".
				"class=\"button\" />";
		}
	} // end function freemed::patient_widget

	// Function: freemed::printers_widget
	//
	//	Create XHTML widget to represent printer selection
	//
	// Parameters:
	//
	//	$varname - Name of the variable which will hold the
	//	data returned by this widget
	//
	// Returns:
	//
	//	XHTML compliant widget code
	//
	function printers_widget ( $varname ) {
		global $this_user;
		if (!is_object($this_user)) {
			$this_user = CreateObject('FreeMED.User');
		}

		static $_driver;
		if (!isset($_driver)) {
			$_driver = CreateObject('PHP.PrinterWrapper');
		}

		return html_form::select_widget(
			$varname,
			$_driver->driver->GetPrinters()
		);
	} // end function freemed::printers_widget

	// Function: freemed::query_to_array
	//
	//	Dumps the output of an SQL query to a multidimentional
	//	hashed array.
	//
	// Parameters:
	//
	//	$query - Text SQL query
	//
	//	$single_dimension - (optional) Reduce to single array, using
	//	k and v table columns as key and value. Defaults to true.
	//
	// Returns:
	//
	//	Multidimentional hashed array.
	//
	function query_to_array ( $query, $single_dimension=true ) {
		global $sql;
		unset ($this_array);

		$result = $sql->query($query);

		if (!$sql->results($result)) return array("" => "");

		$index = 0;
		while ($r = $sql->fetch_array($result)) {
			foreach ($r AS $k => $v) {
				$this_array[$index][(stripslashes($k))] =
					stripslashes($v);
			}
			$index++;
		}

		// Decide if we hash to associative array
		if ($single_dimension) {
			foreach ($this_array AS $k => $v) {
				$result_array[$v['k']] = $v['v'];
			}
			return $result_array;
		} else {
			if ($index == 1) {
				return $this_array[0];
			} else {
				return $this_array;
			}
		}
	} // end function freemed::query_to_array

	// Function: freemed::quickform_i18n
	//
	//	Perform internationalization (i18n) on an HTML_QuickForm
	//	PEAR object.
	//
	// Parameters:
	//
	//	&$object - Object reference
	//
	function quickform_i18n ( &$object ) {
		$object->_requiredNote = '<span style="font-size:80%; color:#ff0000;">*</span><span style="font-size:80%;"> '.__("denotes required field").'</span>';
		$object->_jsPrefix = __("Invalid information entered.");
		$object->_jsPostfix = __("Please correct these fields.");
	} // end method quickform_i18n

	// Function: freemed::race_widget
	//
	//	Create HL7 v2.3.1 compliant race widget (table 0005)
	//
	// Parameters:
	//
	//	$varname - Name of the variable which contains this data.
	//
	// Returns:
	//
	//	$widget - XHTML compliant race widget code.
	//
	function race_widget ( $varname ) {
		// HL7 v2.3.1 compliant race widget (table 0005)
		return html_form::select_widget($varname,
			array (
				__("unknown race") => '7',
				__("Hispanic, white") => '1',
				__("Hispanic, black") => '2',
				__("American Indian or Alaska Native") => '3',
				__("Black, not of Hispanic origin") => '4',
				__("Asian or Pacific Islander") => '5',
				__("White, not of Hispanic origin") => '6'
			)
		);
	} // end function freemed::race_widget

	// Function freemed::religion_widget
	//
	//	Create HL7 v2.3.1 compliant religion widget (table 0006)
	//
	// Parameters:
	//
	//	$varname - Name of the variable which contains this data.
	//
	// Returns:
	//
	//	$widget - XHTML compliant religion widget code.
	//
	function religion_widget ( $varname ) {
		// HL7 v2.3.1 compliant race widget (table 0006)
		return html_form::select_widget($varname,
			array (
				"---" => '',
				__("Catholic") => '0',
				__("Jewish") => '1',
				__("Eastern Orthodox") => '2',
				__("Baptist") => '3',
				__("Methodist") => '4',
				__("Lutheran") => '5',
				__("Presbyterian") => '6',
				__("United Church of God") => '7',
				__("Episcopalian") => '8',
				__("Adventist") => '9',
				__("Assembly of God") => '10',
				__("Brethren") => '11',
				__("Christian Scientist") => '12',
				__("Church of Christ") => '13',
				__("Church of God") => '14',
				__("Disciples of Christ") => '15',
				__("Evangelical Covenant") => '16',
				__("Friends") => '17',
				__("Jehovah's Witness") => '18',
				__("Latter-Day Saints") => '19',
				__("Islam") => '20',
				__("Nazarene") => '21',
				__("Other") => '22',
				__("Pentecostal") => '23',
				__("Protestant, Other") => '24',
				__("Protestant, No Denomenation") => '25',
				__("Reformed") => '26',
				__("Salvation Army") => '27',
				__("Unitarian; Universalist") => '28',
				__("Unknown/No preference") => '29',
				__("Native American") => '30',
				__("Buddhist") => '31'
			)
		);
	} // end function freemed::religion_widget

	// Function: freemed::rich_text_area
	//
	//	Creates a rich text editing widget (HTML)
	//
	// Parameters:
	//
	//	$varname - Name of variable to store the data in
	//
	//	$rows - (optional) Vertical size of text area. Defaults to
	//	10 lines.
	//
	//	$cols - (optional) Horizontal size of text area. Defaults to
	//	60 characters.
	//
	//	$force_js - (optional) Force Javascript to be displayed
	//	every time. Defaults to false.
	//
	// Returns:
	//
	//	XHTML-compliant rich text area widget
	function rich_text_area ( $varname, $rows=10, $cols=60, $force_js=false ) {
		static $_jsset;

		// For compatibility with html_form::text_area()
		$wrap = 'VIRTUAL';

		// Handle initial setting of includes, etc
		// If force_js is set, we put this in anyway for things like
		// notebooks, where even if something is generated, it isn't
		// always displayed.
		if (!$_jsset or $force_js) {
		/*
			$buffer .= 
			"<script type=\"text/javascript\" src=\"lib/template/default/htmlarea/htmlarea.js\"></script>\n".
			"<script type=\"text/javascript\" src=\"lib/template/default/htmlarea/lang/en.js\"></script>\n".
			"<script type=\"text/javascript\" src=\"lib/template/default/htmlarea/dialog.js\"></script>\n".
			"<script type=\"text/javascript\" src=\"lib/template/default/htmlarea/popupwin.js\"></script>\n".
			"<script type=\"text/javascript\">\n".
			"\tHTMLArea.loadPlugin(\"TableOperations\");\n".
			"\tHTMLArea.loadPlugin(\"SpellChecker\");\n".
			"</script>\n".
			"<link rel=\"stylesheet\" type=\"text/css\" ".
				"href=\"lib/template/default/htmlarea/htmlarea.css\" />\n";
				    
			$_jsset = true;
			*/
		}

		// For this, we're just going to add the name of this
		// widget to the list, and we'll generate this on the
		// fly from elsewhere in the template.
		$GLOBALS['__freemed']['rich_text_areas'][] = $varname;

		// Set this to be what we do
		$GLOBALS['__freemed']['on_load'] = 'initEditor';
			
		// Add the actual widget from phpwebtools
		$buffer .= html_form::text_area($varname,$wrap,$rows,$cols);

		// Return the whole bundle
		return $buffer;
	} // end function freemed::rich_text_area

	// Function: freemed::secure_filename
	//
	//	Remove potentially hazardous characters from filenames
	//
	// Parameters:
	//
	//	$original - Original filename
	//
	// Returns:
	//
	//	$sanitized - Sanitized filename
	//
	function secure_filename ( $filename ) {
		// Items to remove
		$secure_these = array (
			"\\",
			".",
			"/",
			"|"
		);

		// Pass to internal variable
		$this_filename = $filename;

		// Perform replacements
		foreach ( $secure_these AS $drek => $secure_var ) {
			$this_filename = str_replace (
				"\$".$secure_var,
				"",
				$this_filename
			);
		}

		// Return secured filename
		return $this_filename;
	} // end function freemed::secure_filename

	// Function: freemed::sql2date
	//
	//	Convert an SQL timestamp (such as MySQL timestamps) into
	//	a nice-looking date string.
	//
	// Parameters:
	//
	//	$date - SQL timestamp string
	//
	// Returns:
	//
	//	Formatted date/time string
	//
	function sql2date ( $date ) {
		$ts = mktime (
			substr($date, 8, 2),
			substr($date, 10, 2),
			substr($date, 12, 2),
			substr($date, 4, 2),
			substr($date, 6, 2),
			substr($date, 0, 4)
		);
		return date('m/d/Y H:i', $ts);
	} // end function freemed::sql2date

	// Function: freemed::store_image
	//
	//	Stores posted file in scanned document image store.
	//
	// Parameters:
	//
	//	$patient_id - Patient identifier from the patient table.
	//	Do not pass a patient object.
	//
	//	$varname - The variable name describing the file that was
	//	posted using the HTTP POST method.
	//
	//	$type - (optional) This is either 'identification' in the
	//	case of an identifying photograph, or the record number
	//	of this document in the scanned documents table
	//
	//	$encoding - (optional) Type of DjVu encoding. Currently
	//	'cjb2' and 'c44' encodings are supported.
	//
	// Returns:
	//
	//	Name of file if successful.
	//
	function store_image ( $patient_id=0, $varname, $type="identification", $encoding='cjb2' ) {
		global ${$varname};

		// Check for valid patient id
		if ($patient_id < 1) return false;

		// Determine extension
		$file_parts = explode (".", $_FILES[$varname]["name"]);
		$ext = $file_parts[count($file_parts)-1];

		// If there is no extension, die
		if (strlen($ext) < 3) { return false; }

		// Get temporary name
		$image = $_FILES[$varname]["tmp_name"];

		// If temp name doesn't exist, return false
		if (empty($image)) return false;

		// Create proper path
		$mkdir_command = 'mkdir -p '.PHYSICAL_LOCATION.'/'.
			dirname(
				freemed::image_filename(
					$patient_id,
					$type,
					'djvu'
				)
			);
		//print "mkdir_command = $mkdir_command<br/>\n";
		$mkdir_output = `$mkdir_command`;
		//print $mkdir_output."<br/>\n";

		// Process depending on 
		switch (strtolower($ext)) {
			/*
			case "jpg":
			case "jpeg":
				// Simple JPEG handler: copy
				$name = freemed::image_filename(
					$patient_id,
					$type,
					'djvu'
				);
				copy ($image, "./".$name);
				return $name;
				break; // end handle JPEGs
			*/

			default:
				// More complex: use imagemagick
				$name = freemed::image_filename(
					$patient_id,
					$type,
					'djvu'
				);
				// Convert to PBM
				$command = "/usr/bin/convert ".
					freemed::secure_filename($image).
					" ".PHYSICAL_LOCATION."/".
					freemed::image_filename(
						$patient_id,
						$type,
						'djvu.'.
						( $encoding=='c44' ?
						'jpg' : 'pbm' )
					);
				//print "convert command = ".$command."<br/>\n";
				$output = `$command`;
				//print "convert output = ".$output."<br/>\n";

				// Convert to DJVU
				switch ($encoding) {
					case 'c44':
						$ee = '/usr/bin/c44';
						break;
					case 'cjb2':
					default:
						$ee = '/usr/bin/cjb2';
						break;
				}
				$command = $ee." ".
					PHYSICAL_LOCATION."/".
					freemed::image_filename(
						$patient_id,
						$type,
						'djvu.'.
						( $encoding=='c44' ?
						'jpg' : 'pbm' )
					)." ".
					PHYSICAL_LOCATION."/".
					freemed::image_filename(
						$patient_id,
						$type,
						'djvu'
					);
				//print "command = $command<br/>\n";
				//print "<br/>".exec ($command)."<br/>\n";
				$output = `$command`;
				//print "<br/>".`$command`."<br/>\n";

				// Remove PBM
				unlink(PHYSICAL_LOCATION.'/'.
					freemed::image_filename(
						$patient_id,
						$type,
						'djvu.'.
						( $encoding=='c44' ?
						'jpg' : 'pbm' )
					)
				);
				return $name;
				break; // end handle others
		} // end checking by extension
	} // end function freemed::store_image

	// Function: freemed::support_djvu
	//
	//	Determines whether the current browser supports DjVu.
	//
	// Parameters:
	//
	//	$browser - PHP.browser_detect object.
	//
	// Returns:
	//
	//	Boolean, whether DjVu is supported or not.
	//
	function support_djvu ( $browser ) {
		// Assume true
		$support = true;

		return $support;
	} // end function freemed::support_djvu

	// Function: freemed::template_file
	//
	//	Resolve file to existing either in default template or
	//	current template.
	//
	// Parameters:
	//
	//	$file - Filename, relative to the template structure
	//	(login_form.php would resolve to lib/template/*/login_form.php)
	//
	// Returns:
	//
	//	Fully qualified template path (lib/template/*/*)
	//
	function template_file ( $file ) {
		if (file_exists('lib/template/'.$GLOBALS['template'].'/'.$file)) {
			return 'lib/template/'.$GLOBALS['template'].'/'.$file;
		} else {
			return 'lib/template/default/'.$file;
		}
	} // end function freemed::template_file

	// Function: freemed::user_flag
	//
	//	Determine if a particular user flag is set for the current
	//	user.
	//
	// Parameters:
	//
	//	$flag - The flag in question. This should be something
	//	like USER_ADMIN, USER_DELETE, etc.
	//
	// Returns:
	//
	//	True if the flag is set for the current user.
	//
	function user_flag ( $flag ) {
		global $database, $sql;
		static $userlevel;

		// Extract authdata from SESSION
		$authdata = $_SESSION['authdata'];

		// Check for cached userlevel
		if (isset($userlevel)) { return ($userlevel & $flag); }

		// Check for null user
		if (($authdata["user"]<1) or (!isset($authdata["user"]))) {
			$userlevel = 0;
			return false; // if no user, return 0
		}

		if ($authdata["user"] == 1) {
			// Anything but disabled user, return true
			if ($flag == USER_DISABLED) {
				return false;
			} else {
				return true;
			}
		} else {
			$result = $sql->query("SELECT * FROM user
				WHERE id='".addslashes($authdata["user"])."'");

			// Check for improper results, return "unauthorized"
			if (!$sql->results($result) or ($sql->num_rows($result) != 1)) {
				// Set so that nothing works
				$userlevel = USER_DISABLED;
				if ($flag == USER_DISABLED) {
					return true;
				} else {
					return false;
				}
			}

			// Get results
			$r = $sql->fetch_array($result);

			// Set $userlevel (which is cached)
			$userlevel = $r["userlevel"];

			// Return the answer...
			return ($userlevel & $flag);
		} // end else loop checking for name
	} // end function user_flag

	// Function: freemed::lock_override
	//
	//	Determine if the current user has the ability to "override"
	//	the locking of a record.
	//
	// Returns:
	//
	//	Boolean value, whether or not the user has override
	//	permissions.
	//
	function lock_override () {
		global $this_user;
		if (!is_object($this_user)) {
			$this_user = CreateObject('_FreeMED.User');
		}

		$a = explode(',', freemed::config_value('lock_override'));
		foreach ($a as $u) {
			if ($u == $this_user->user_number) { return true; }
		}
		
		return false;
	} // end function lock_override

	// Function: freemed::phone_display
	//
	//	Displays phone number in system format.
	//
	// Parameters:
	//
	//	$phone - Phone number raw
	//
	// Returns:
	//
	//	Formatted phone number for display
	//
	function phone_display ( $phone ) {
		if (strlen($phone) < 7) { return __("NONE"); }
		switch (freemed::config_value('phofmt')) {
			case "usa":
				return '('.substr($phone, 0, 3).') '.
					substr($phone, 3, 3).'-'.
					substr($phone, 6, 4).
					( strlen($phone)>10 ? ' '.substr($phone, 10, 4) : '' );
				break;
			case "fr":
				return '+'.substr($w, 0, 2).
					substr($w, 2, 2). 
					substr($w, 4, 2). 
					substr($w, 6, 2). 
					substr($w, 8, 2); 
				break;
			case "unformatted":
			default:
				return $phone;
				break;
		} // end formatting case statement
	} // end function phone_display

	// Function: freemed::verify_auth
	//
	//	Determines if the current user is authenticated when dealing
	//	with PHP sessions. This is not used for basic authentication.
	//
	// Returns:
	//
	//	True if the current session is authenticated.
	//
	function verify_auth ( ) {
		global $debug, $Connection, $sql;

		// Associate "SESSION" with proper session variable
		$PHP_SELF = $_SERVER['PHP_SELF'];
 
		// Do we have to check for _username?
		$check = !empty($_REQUEST['_username']);
	
		// Check for authdata array
		if (is_array($_SESSION['authdata'])) {
			// Check to see if ipaddr is set or not...
			if (!SESSION_PROTECTION) {
				return true;
			} else {
				if ( !empty($_SESSION['ipaddr']) ) {
					if ($_SESSION['ipaddr'] == $_SERVER['REMOTE_ADDR']) {
						// We're already authorized
						return true;
					} else {
						// IP address has changed, ERROR
						unset($_SESSION['ipaddr']);
						print "IP ADDRESS<BR>\n";
						return false;
					} // end checking ipaddr
				} else {
					// Force check if no ip address is present. This
					// should get around null IPs getting set by
					// accident without compromising security.
					$check = true;
				} // end if isset ipaddr
			} // end checking for SESSION_PROTECTION
		} 
		
		if ($check) {
			// Find this user
  			$result = $sql->query ("SELECT * FROM user ".
				"WHERE username = '".addslashes($_REQUEST['_username'])."'");
	
			// If the user isn't found, false
			if (!$sql->results($result)) { return false; }
	
			// Get information
			$r = $sql->fetch_array ($result);

			// Use _hash (md5) if passed, else plain _password
			$login_md5 = ( $_REQUEST['_hash'] ? $_REQUEST['_hash'] : md5($_REQUEST['_password']) );

			$user=$_REQUEST['_username'];

			if((LOGLEVEL<1)||(LOG_HIPAA || LOG_LOGIN))
			{
			syslog(LOG_INFO,"API.php|verify_auth login attempt $user ");
			}

			$db_pass=$r['userpassword'];		

	//		This is insecure and should not be used
	//		It is here for debugging purposes only...
	//		if(LOG_MD5||(LOGLEVEL<1)) // Md5 password Logging
	//		{
	//		syslog(LOG_INFO,"API.php|verify_auth Password entered__ $login_md5 ");
	//		}

			

	
			// Check password
			if ($login_md5 == $r['userpassword']) {
				// Set session vars
				$_SESSION['authdata'] = array (
					"username" => $_REQUEST['_username'],
					"user" => $r['id']
				);
				// Set ipaddr for SESSION_PROTECTION
				$_SESSION['ipaddr'] = $_SERVER['REMOTE_ADDR'];
	
				// Authorize
				if(((LOGLEVEL<1)||LOG_ERRORS)||(LOG_HIPAA || LOG_LOGIN)){syslog(LOG_INFO,"API.php|verify_auth successful login");}		
				return true;
			} else { // check password
				// Failed password check
				unset ( $_SESSION['authdata'] );
				unset ( $_SESSION['ipaddr'] );
	                       if(((LOGLEVEL<1)||LOG_ERRORS)||(LOG_HIPAA || LOG_LOGIN)){ syslog(LOG_INFO,"API.php|verify_auth failed login");	}	
				return false;
			} // end check password
		} // end of checking for authdata array
	} // end method freemed::verify_auth

} // end namespace/class freemed

class EMRi {
	// EMRi Server information
	var $EMRi_server_host;
	var $EMRi_server_port;
	var $EMRi_server_uri;
	var $EMRi_user;
	var $EMRi_password;

	function EMRi () {
		$this->get_server_name();
		// FIXME: Kludge for fqdn
		$this->fqdn = 'test';
		// FIXME: EXTREME KLUDGE for testing purposes only!
		$this->EMRi_user = 'root';
		$this->EMRi_password = 'password';
	} // end constructor EMRi

	// TODO: finish EMRi linking functions
	function get_link_rec ( $url ) {
		die("STUB: EMRi::get_link_rec()");
	} // end method EMRi->get_link_rec

	function get_server_name () {
		// This should actually get the best EMRi server.
		// Barring that, we assign static
		$this->EMRi_server_host = 'localhost';
		$this->EMRi_server_port = '3674';
		$this->EMRi_server_uri  = '/RPC2';
	} // end method EMRi->get_server_name

	//----- Method calls for hosts and servers ---------------------------

	function host_method ($fqdn, $method, $argv) {
		// Make sure we're connected
		if (!isset($this->EMRi_server_host)) $this->get_server_name();

		// Call the proper function on the server
		return xu_rpc_http_concise(array(
			'method' => $method,
			'args'   => $argv,
			'host'   => $this->EMRi_server_host,
			'port'   => $this->EMRi_server_port,
			'uri'    => $this->EMRi_server_uri,
			'debug'  => 1,
			'output' => NULL,
			'secure' => 0, // this needs to be fixed!

			// FIXME: These should be pulled from the database
			'user'   => 'root',
			'pass'   => 'password'
		));
	} // end method EMRi->host_method

	function server_method ($method, $argv) {
		static $client;
	
		// Make sure we're connected
		if (!isset($this->EMRi_server_host)) $this->get_server_name();

		// Check for prexisting client
		if (!is_object($client)) {
			$client = CreateObject(
				'PHP.xmlrpc_client',
				$this->EMRi_server_uri, // URI
				$this->EMRi_server_host, // HOST
				$this->EMRi_server_port // PORT
			);
			$client->setDebug();
		}

		// Set proper credentials
		$client->setCredentials($this->EMRi_user, $this->EMRi_password);

		// TODO: Pre-call argument processing

		// Call with function
		$response = $client->send (
			CreateObject(
				'PHP.xmlrpcmsg',
				$method,
				$argv // arguments
			)
		);

		// Return deserialized version
		return $response->deserialize();
	} // end method EMRi->server_method

	//-------------------------------------------------------------------


	//----- Authenticate methods ----------------------------------------

	function authenticate_user ($user, $pass) {
		// Call EMRi.Authentication.user on server
		return $this->server_method(
			"EMRi.Authentication.user",
			array(
				$user,
				$pass
			)
		);
	} // end method EMRi->authenticate_user

	//----- Patient methods ---------------------------------------------

	function patient_index ($pid) {
		// If it's an array, send the array, if not,
		// send an array wrapper for the scalar value
		if (!is_array($pid)) {
			$patients = array ($pid);			
		} else {
			$patients = $pid;
		}

		foreach ($patients AS $k => $v) {
			// Process scalar
			$this_patient = freemed::get_link_rec($v,"patient");

			// Add to param
			$param[] = array (
				'fqdn'       => $this->fqdn,
				'pid'        => $this_patient['ptssn'],
				'last_name'  => $this_patient['ptlname'],
				'first_name' => $this_patient['ptfname'],
				'version'    => $this_patient['version']
			);
			
		}

		// Call the method
		return $this->server_method(
			"EMRi.Patient.index",
			array($param)
		);
	} // end method EMRi->patient_index

	function patient_search ($pid) {
		// If it's an array, send the array, if not,
		// send an array wrapper for the scalar value
		if (!is_array($pid)) {
			$param = array ("pid" => $pid);			
		} else {
			$param = $pid;
		}

		// Call the method
		$result = $this->server_method(
			"EMRi.Patient.search",
			array($param)
		);

		// For now, return the raw result
		return $result;
	} // end method EMRi->patient_search

} // end namespace/class EMRi

//------------------ NON NAMESPACE FUNCTIONS ---------------------

// Function: freemed_alternate
//
//	Create alternating texts. Used mostly for alternating
//	row displays, either as CLASS tags or as BGCOLOR tags.
//
// Parameters:
//
//	$elements - Array of elements which are to be alternated
//	between. Defaults to array ('cell', 'cell_alt').
//
// Returns:
//
//	The next element in the circular loop of the presented
//	array.
//
function freemed_alternate ($_elements) {
	static $_pos;

	if (!is_array($_elements)) {
		// By default, cell and cell_alt
		$elements = array ("cell", "cell_alt");
	} else {
		// Otherwise, pull into local scope
		$elements = $_elements;
	}

	if (!isset($_pos)) {
		// If there is no current position, set to initial state
		$_pos = 0;
	} else {
		// Otherwise increment and wrap around
		$_pos++;
		if ($_pos >= count($elements)) { $_pos = 0; }
	}

	return $elements[$_pos];
} // end function freemed_alternate

// Function: freemed_display_actionbar
//
//	Creates the ADD/RETURN TO MENU bar present in most FreeMED
//	modules.
//
// Parameters:
//
//	$page_name - (optional) Name of the current page.
//
//	$ref - (optional) Name of the referring page. If this is not
//	explicitly set, the global variable '_ref' acts as the
//	default value.
//
// Returns:
//
//	XHTML compliant actionbar widget.
//
function freemed_display_actionbar ($this_page_name="", $__ref="") {
	global $page_name, $patient, $_ref, $_pass, $module;

	$buffer = "";

	if (!empty($_ref)) $__ref = $_ref;

	if ($this_page_name=="") $this_page_name = $page_name;

	// No reference, return to homepage
	if (empty($__ref)) { $_ref="main.php"; }

	// Assume return to management if nothing else
	if ($GLOBALS["return"] == "manage") {
		$__ref = "manage.php?id=$patient";
	}

    // show the actual bar, build with page_name reference
    // and global variables
	global $globaladdcounter; $globaladdcounter++;
	global $template;

	$buffer .= "
    <table CLASS=\"reverse\" WIDTH=\"100%\" BORDER=\"0\"
     CELLSPACING=\"0\" CELLPADDING=\"3\">
    <tr CLASS=\"reverse\">
    <td ALIGN=\"LEFT\"><a HREF=\"$this_page_name?".
    	( isset($_pass) ? $_pass.'&' : '' )."module=".urlencode($module)."&".
	"action=addform".
     ( !empty($patient) ? "&patient=".urlencode($patient) : "" )."\"
	onMouseOver=\"window.status='".__("Add")."'; return true;\"
	onMouseOut=\"window.status=''; return true;\"
	><small><b>".__("ADD")."</b></small></a></td>
    <td WIDTH=\"30%\">&nbsp;</td>
    <td ALIGN=\"RIGHT\"><a HREF=\"$__ref\" CLASS=\"reverse\"
     ><small><b>".__("RETURN TO MENU")."</b></small></a></td>
    </tr></table>
  	";
	return $buffer;

} // end function freemed_display_actionbar

// Function: freemed_display_itemlist
//
//	Creates a paginated list display based on formatting data for
//	a particular result set. This should be used in conjunction
//	with <freemed::itemlist_conditions> to produce a proper
//	SQL query.
//
// Parameters:
//
//	$result - SQL query passed to the display.
//
//	$page_link - Current page name.
//
//	$control_list - List of column names and database table column
//	names, as an associative array. (Example: array (
//	__("Date") => 'procdt', __("Procedure Code") => 'proccpt' ) )
//
//	$blank_list - Array of values for the columns describing what a
//	blank entry should be displayed as.
//
//	$xref_list - (optional) Associative array describing cross
//	table references. For example, if your column 'proccpt'
//	described a CPT code, you could use 'cpt' => 'cptcode' to
//	describe the table name ('cpt') and the column to be displayed
//	name ('cptcode'), which would be determined by the value of
//	the corresponding column in $control_list.
//
//	$cur_page_var - (optional) Pagination tracking variable. The
//	default is 'this_page'.
//
//	$index_field - (optional) Currently this is unused, and should
//	be passed as '' or NULL.
//
//	$flags - (optional) Bitfield of operators, such as ITEMLIST_MOD |
//	ITEMLIST_DEL.
//
// Returns:
//
//	XHTML compliant item listing with search widgets.
//
function freemed_display_itemlist ($result, $page_link, $control_list, 
                           $blank_list, $xref_list="",
			   $cur_page_var="this_page",
			   $index_field="", $flags=-1)
{
  global $_ref, $record_name;
  global $modify_level, $delete_level, $patient, $action, $module;
  global $page_name, ${$cur_page_var}, $max_num_res;
  global $_s_field, $_s_val, $_pass, $sql;

  //echo "page name $page_name this $this->page_name module $module<BR>";
  
  if ($flags==-1) $flags=(ITEMLIST_MOD|ITEMLIST_DEL);

  // pull current page name
  if (empty ($page_link)) {
    $parts = explode("?", basename($GLOBALS["REQUEST_URI"]));
    $page_link = $parts[0];
  } // end of pull current page name

  if ( (isset($module)) AND (!empty($module)) )
  {
	// if we are in a module pull the module loader
    // name for paging
    $parts = explode("?", basename($GLOBALS["REQUEST_URI"]));
    $page_name = $parts[0];
  }

  // TODO: make sure $control_list is an array, verify the inputs, yadda yadda

  $num_pages = ceil($sql->num_rows($result)/$max_num_res);
  if (${$cur_page_var}<1 OR ${$cur_page_var}>$num_pages) ${$cur_page_var}=1;

  if (strlen(${$cur_page_var})>0) { // there's an offset
    for ($i=1;$i<=(${$cur_page_var}-1)*$max_num_res;$i++) {
      $herman = $sql->fetch_array($result); // offset the proper number of rows
    }
  }

  $buffer="";

  $buffer .= "
    <!-- Begin itemlist Table -->
    <table WIDTH=\"100%\" CELLSPACING=\"0\" CELLPADDING=\"2\" BORDER=\"0\"
     ALIGN=\"CENTER\" VALIGN=\"MIDDLE\" CLASS=\"itemlistbox\">
    <tr>
     <td ALIGN=\"CENTER\">
      <big><b>".__($record_name)."</b></big>
     </td>
    </tr>".
    
   ( ((strlen($cur_page_var)>0) AND ($num_pages>1)) ? "
   <tr ALIGN=\"CENTER\"><td CLASS=\"reverse\">
    <table BORDER=\"0\" CELLPADDING=\"2\" CELLSPACING=\"0\">
     <form METHOD=\"POST\" ACTION=\"$page_name\">
    ".
    
    ((${$cur_page_var} > 1) ? "
    <tr><td>".template::link_button(
        __("Previous"),
        "$page_name?$cur_page_var=".(${$cur_page_var}-1).
        ((strlen($_s_field)>0) ? "&_s_field=$_s_field&_s_val="
        .prepare($_s_val)."" : "").
        "&module=$module&action=$action")."
    </td>
    " : "" )
    
    ."<td CLASS=\"reverse\">
     ".__("Page"). 
     fm_number_select($cur_page_var, 1, $num_pages, 1, false, true).
	" of ".$num_pages."
     <input TYPE=\"HIDDEN\" NAME=\"action\"  VALUE=\"".prepare($action)."\"/>
     <input TYPE=\"HIDDEN\" NAME=\"module\"  VALUE=\"".prepare($module)."\"/>
     <input TYPE=\"HIDDEN\" NAME=\"patient\" VALUE=\"".prepare($patient)."\"/>
     <input class=\"button\" TYPE=\"SUBMIT\" VALUE=\"".__("Go")."\"/>
    </td>".
    
    ((${$cur_page_var} < $num_pages) ? "
    <td>".template::link_button(
        __("Next"),
        "$page_name?$cur_page_var=".(${$cur_page_var}+1).
        ((strlen($_s_field)>0) ? "&_s_field=$_s_field&_s_val="
        .prepare($_s_val)."" : "").
        "&module=$module&action=$action")."
    </td></tr>
    " : "" )
    
    ."
     </form>
    </table>
   </td></tr>
    " : "" )
    
    ."<tr><td>
    ".freemed_display_actionbar($page_link)."
    </td></tr>
    <tr><td>
  ";
  // end header

  $buffer .= "
    <table WIDTH=\"100%\" CELLSPACING=\"0\" CELLPADDING=\"2\" BORDER=\"0\"
     ALIGN=\"CENTER\" ALIGN=\"MIDDLE\">
    <tr>
  ";
  while (list($k,$v)=each($control_list)) {
    $buffer .= "
      <td CLASS=\"reverse\">
       $k&nbsp;
      </td>
    ";
  }
  if ($flags != 0) {
  $buffer .= "
      <td CLASS=\"reverse\">".__("Action")."</td>
	  </tr>
  ";
  } else {
  	$buffer .= "<td CLASS=\"reverse\"></td></tr>";
  }
 
  if ($sql->num_rows($result)>0) 
   while ($this_result = $sql->fetch_array($result) AND 
      ((strlen($cur_page_var)>0) ? ($on_this_page < $max_num_res) : (1)) ) {
    $on_this_page++;
    $first = true; // first item in the list has 'view' link
    $buffer .= "
    <tr CLASS=\"".freemed_alternate()."\" ".
    ( ($flags & ITEMLIST_VIEW) ?
    "onClick=\"window.location='$page_link?module=$module&patient=$patient&".
    "action=view&id=".urlencode($this_result['id'])."'; return true;\" " :
    "" ).">
    ";
    reset($control_list); // it's already each'd the arrays, 
    if (is_array($xref_list)) 
      reset($xref_list);    // but we have to do it again for the next iteration
    $field_num=0;
    while (list($k,$v)=each($control_list)) {
      $is_xref=false;
      if (is_array($xref_list)) {
        reset($xref_list);
        $xref_k = $xref_v = "";
        for ($i=0;$i<=$field_num;$i++)
          list ($xref_k, $xref_v) = each($xref_list);
        // the proper item is now in $xref_{k,v}
        if (strlen($xref_v)>1) {
          $is_xref=true;
          $xref_item=freemed::get_link_field($this_result[$v],
                                                    $xref_k,$xref_v);
          $item_text = ( (strlen($xref_item)<1) ?
                         prepare($blank_list[$field_num]) :
                         prepare($xref_item) );
        }
      } // if there are any xrefs in the table
      if (!$is_xref) { // not an xref item 
        $item_text = ( (strlen($this_result[$v])<1)?
                       prepare($blank_list[$field_num])  :
                       prepare($this_result[$v]) ); 
      }
      if ($first) {
        $first = false;
        $buffer .= "
      <td>
        <a HREF=\"$page_link?".( !isset($_pass) ? $_pass.'&' : '' ).
	"patient=$patient&action=display&id=".
	"$this_result[id]&module=$module\"
	  >$item_text</a>&nbsp;
      </td>
        ";
      } else {
        $buffer .= "
      <td>
        $item_text&nbsp;
      </td>
        ";
      }
    $field_num++;
    } // while each data field
    
    $buffer .= "
      <td>
    ";
    if ($flags & ITEMLIST_VIEW) {
      $buffer .= "
        <a HREF=\"$page_link?".( isset($_pass) ? $_pass.'&' : '' ).
	"module=$module&patient=$patient&action=view&id=".
	urlencode($this_result['id'])."\" class=\"button\">".__("VIEW")."</a>
      ";
    }
    if ($flags & ITEMLIST_PRINT) {
      $buffer .= "
        <a href=\"javascript:return false;\" onClick=\"window.open('$page_link?".( isset($_pass) ? $_pass.'&' : '' ).
	"module=$module&patient=$patient&action=print&id=".
	urlencode($this_result['id'])."', 'printWindow', ".
	"'width=400,height=200,menubar=no,titlebar=no'); return true;\" ".
	"class=\"button\">".__("PRINT")."</a>
      ";
    }
    if (freemed::acl('support', 'view') AND 
         ($flags & ITEMLIST_MOD) AND (!$this_result['locked'])) {
      $buffer .= "
        <a HREF=\"$page_link?".( isset($_pass) ? $_pass.'&' : '' ).
	"module=$module&patient=$patient&action=modform&id=".
	urlencode($this_result['id'])."\" class=\"button\">".__("MOD")."</a>
      ";
    }
    if (freemed::acl('support', 'delete') AND
         ($flags & ITEMLIST_DEL) AND (!$this_result['locked'])) {
	$buffer .= html_form::confirm_link_widget(
        	"$page_link?".( isset($_pass) ? $_pass.'&' : '' ).
		"patient=$patient&module=$module&action=delete&id=".
				urlencode($this_result['id']),
	 	__("DEL"),
		array(
			'confirm_text' =>
			__("Are you sure you want to delete this record?"),

			'text' => __("Delete"),
			'class' => 'button'
		)
	)."\n";

    }
    if (freemed::acl('support', 'delete') AND
         ($flags & ITEMLIST_LOCK) AND ($this_result['locked']=='0')) {
	$buffer .= html_form::confirm_link_widget(
        	"$page_link?".( isset($_pass) ? $_pass.'&' : '' ).
		"patient=$patient&module=$module&action=lock&id=".
				urlencode($this_result['id']),
	 	__("LOCK"),
		array(
			'confirm_text' =>
			__("Are you sure you want to lock this record?"),

			'text' => __("Lock"),
			'class' => 'button'
		)
	)."\n";
    }
    
    
    $buffer .= "
      &nbsp;</td>
    </tr>
    ";
   } // while each result-row
  else { // no items to display
   $buffer .= "
    <tr CLASS=\"".freemed_alternate()."\">
     <td COLSPAN=".(count($control_list)+1)." ALIGN=\"CENTER\">
      <i>No ".__($GLOBALS["record_name"])."</i>
     </td>
    </tr>
   ";
  } // if no items to display
   
  $buffer .= "
    </table>
   </td></tr>
   <tr><td>
  ";
  
  // searchbox
 if (($num_pages>1) or !empty($_s_val)) {
  $GLOBALS['__freemed']['on_load'] = 'changeFocus';
  $buffer .= "
    <table WIDTH=\"100%\" CELLSPACING=\"0\" CELLPADDING=\"2\" BORDER=\"0\">
    <tr CLASS=\"reverse\">
    <form METHOD=\"POST\" NAME=\"itemlistsearch\" ACTION=\"".prepare($page_name)."\">
      <script language=\"Javascript\">
	function changeFocus() {
		document.forms.itemlistsearch._s_val.focus();
		return true;
	}
      </script>
     <td ALIGN=\"CENTER\">
      ".html_form::select_widget(
        "_s_field",
	$control_list
      )."
      ".__("contains")."
      <input class=\"button\" TYPE=\"HIDDEN\" NAME=\"module\"
       VALUE=\"".prepare($module)."\"/>
      <input class=\"button\" TYPE=\"HIDDEN\" NAME=\"$cur_page_var\" VALUE=\"1\"/>
      ".html_form::text_widget('_s_val', 20)."
      <input class=\"button\" TYPE=\"SUBMIT\" VALUE=\"".__("Search")."\"/>
      <input class=\"button\" TYPE=\"BUTTON\" VALUE=\"".__("Reset")."\"
       onClick=\"this.form._s_val.value=''; this.form.submit(); return true;\"/>
     </td>
    </form>
    </tr>
    </table>
   </tr></td>
   <tr><td>
  ";
 } // no searchbox for short-short lists
  // end searchbox
  
  // footer
  $buffer .= freemed_display_actionbar($page_link)
    ."</td></tr>
    </table>
    <!-- End itemlist Table -->
  ";

  return $buffer; // gotta remember this part!
}

// Function: freemed_display_facilities
//
//	Creates an XHTML facility selection widget.
//
// Parameters:
//
//	$varname - Name of the global variable containing the data for this
//	widget.
//
//	$default_load - (optional) Depreciated.
//
//	$internal_external - (optional) Exclusively internal or external
//	facilities. If this is passed at all, "0" selects internal
//	facilities and "1" selects external facilities.
//
//	$by_array - (optional) Array of facility id numbers to limit the
//	selection to.
//
// Returns:
//
//	XHTML compliant facility selection widget.
//
function freemed_display_facilities ($param="", $default_load = false,
                                     $intext="", $by_array="") {
	global $sql, $_COOKIE;

	// Check for default or passed facility
	if ($GLOBALS[$param] > 0) {
		// Only set this if $param is a legal value
		$facility = $GLOBALS[$param];
	} else {
		// Otherwise set via cookie
		$facility = ( $_SESSION['default_facility'] > 0 ?
			$_SESSION['default_facility'] :
			$_COOKIE['default_facility'] ) + 0;
	}

	$buffer = "";

	switch ($intext) {
		case "0": // internal
			$intextquery = "WHERE psrintext='0'";
			break;
		case "1": // external
			$intextquery = "WHERE psrintext='1'";
			break;
		default:
			$intextquery = "";
	}

	// Check for "by_array"
	if (is_array($by_array)) {
		$intextquery .= " AND id IN ( ".implode(",", $by_array)." ) ";
	} // end checking for by_array

	// list doctors in SELECT/OPTION tag list, and
	// leave doctor selected who is in param
	$buffer .= "<option VALUE=\"0\"".
		( ($param == 0) ? " selected" : "" ).">".__("NONE SELECTED").
		"</option>\n";
	$query = "SELECT * FROM facility ".$intextquery.
		"ORDER BY psrname,psrnote";
	$result = $sql->query ($query);
	if (!$result) return false;

	while ($row = $sql->fetch_array($result)) {
		$buffer .= "<option VALUE=\"".prepare($row[id]).
			"\" ".
			( ($row[id]==$facility) ? "selected" : "" ).">".
			prepare($row[psrname]." (".$row[psrcity].", ".
				$row[psrstate].")").
			( ($debug) ? "[".$row[psrnote]."]" :
			"" )."</option>\n";
	} // while there are more results...
	return $buffer;
} // end function freemed_display_facilities

function freemed_display_physicians ($param, $intext="") {
	die ("freemed_display_physicians - DEPRECIATED");
/*
	$buffer = "";

	// list doctors in SELECT/OPTION tag list, and
	// leave doctor selected who is in param
	$buffer .= "
		<option VALUE=\"0\">".__("NONE SELECTED")."</option>
	";
	$query = "SELECT * FROM physician ".
		( ($intext != "") ? " WHERE phyref='$intext'" : "" ).
		"ORDER BY phylname,phyfname";
	$result = $sql->query ($query);
	if (!$sql->results($result)) {
		// don't do anything...! 
	} else { // exit if no more docs
		while ($row = $sql->fetch_array($result)) {
			$buffer .= "
			<option VALUE=\"$row[id]\" ".
			( ($row[id] == $param) ? "selected" : "" ).
			">".prepare("$row[phylname], $row[phyfname]")."</option>
			"; // end of actual output
		} // while there are more results...
	}
	return $buffer;
*/
} // end function freemed_display_physicians

///////////////////////////////////////////////////
// function freemed_display_printerlist
// displays printers from the database
function freemed_display_printerlist ($param)
{
  global $sql;

  // list printers in SELECT/OPTION tag list, and
  // leave printer selected who is in param
  echo "
    <OPTION VALUE=\"0\">".__("NONE SELECTED")."
  ";
  $query = "SELECT * FROM printer ORDER BY ".
     "prnthost, prntname";
  $result = $sql->query ($query);
  if (!$result) {
    // don't do anything...! 
  } else { // exit if no more printers
    while ($row=$sql->fetch_array($result)) {
      echo "
        <OPTION VALUE=\"$row[id]\" ".
	( ($param == $row[id]) ? "SELECTED" : "" ).
        ">".prepare("$row[prnthost] $row[prntname]")."
      "; // end of actual output
    } // while there are more results...
  }
} // end function freemed_display_printerlist

// Function: freemed_display_selectbox
//
//	Create an XHTML selection box
//
// Parameters:
//
//	$result - SQL query result
//
//	$format - Format hash for the display box (result field names
//	surrounded by '##'s)
//
//	$varname - Name of the variable to store the selected data in.
//
//	$size - (optional) Size of the box. Defaults to default size.
//
// Returns:
//
//	XHTML compliant selection widget.
//
function freemed_display_selectbox ($result, $format, $param="", $size="") {
	global ${$param}; // so it knows to put SELECTED on properly
	global $sql; // for database connection

	static $var; // array of $result-IDs so we only go through them once
	static $count; // count of results

	if (!isset($var["$result"])) {
		if ($result) {
			$count["$result"] = $sql->num_rows($result);
			while ($var["$result"][] = $sql->fetch_array($result));
		} // non-empty result
	} // if we haven't gone through this list yet
 
	$buffer = "";
	if ($count["$result"]<1) { 
		$buffer .= __("NONE")." ".
			"<input TYPE=\"HIDDEN\" NAME=\"".prepare($param)."\" ".
			"VALUE=\"0\"/>\n";
		return $buffer; // do nothing!
	} // if no result

	$buffer .= "
		<select NAME=\"$param\"".
		( $size ? " size=\"".$size."\"" : "" ).">
		<option VALUE=\"0\">".__("NONE SELECTED")."</option>
	";
	
	reset($var["$result"]); // if we're caching it, we have to reset it!
	// no null values!
	while ( (list($pickle,$item) = each($var["$result"])) AND ($item[id])) {
		// START FORMAT-FETCHING
		// Odd members are variable names
		$format_array = explode("#",$format);
		while (list($index,$str) = each($format_array)) {
			// ignore the evens!
			if ( !($index & 1) ) continue;
			// can't just change $str!
			$format_array[$index] = $item[$str];
		} // while replacing each variable name
		// put it back together
		$this_format = join("", $format_array);
		// END FORMAT-FETCHING    

		$buffer .= "
		<option VALUE=\"$item[id]\" ".
		( ($item[id] == $$param) ? "selected" : "" ).
		">".prepare($this_format)."</option>\n";
	} // while fetching result
	$buffer .= "
	</select>
	";
  
	return $buffer;
} // end function freemed_display_selectbox

// Function: freemed_export_stock_data
//
//	Export FreeMED database table to a file
//
// Parameters:
//
//	$table_name - Name of the SQL table to export
//
function freemed_export_stock_data ($table_name, $file_name="") {
	global $sql, $debug;

	$physical_file = PHYSICAL_LOCATION . "/data/" . DEFAULT_LANGUAGE . 
		"/" .  $table_name . "." . DEFAULT_LANGUAGE . "." . 
		date("Ymd");

	//if (strlen ($file_name) > 2) $physical_file = $file_name;

	//if (file_exists ($physical_file)) { return false; } // fix this later

	$query = "SELECT * FROM ".addslashes($table_name)." ".
		"INTO OUTFILE '".addslashes($physical_file)."' ".
		"FIELDS TERMINATED BY ',' ".
		"OPTIONALLY ENCLOSED BY '' ".
		"ESCAPED BY '\\\\'";

	if ($debug) echo "<BR> query = \"$query\" <BR> \n";

	$result = $sql->query ($query);

	if ($debug) echo "<BR> result = \"$result\" <BR> \n";

	return $result;
} // end function freemed_export_stock_data

// function freemed_get_userlevel
//   returns user level (1-10)
//   (assumes 1 if not found, 9 if root)
function freemed_get_userlevel ( $param = "" ) {
	die("called freemed_get_userlevel: obsolete STUB");
}

// Function: freemed_import_stock_data
//
//	Import an SQL table into FreeMED
//
// Parameters:
//
//	$table_name - Name of the SQL table to import
//
function freemed_import_stock_data ($table_name) {
	global $sql;

	// Produce a physical location
	$physical_file = PHYSICAL_LOCATION . "/data/" . DEFAULT_LANGUAGE .
		"/" .  $table_name . "." . DEFAULT_LANGUAGE . ".data";

	// Die if the phile doesn't exist
	if (!file_exists($physical_file)) return false;

	// Create the query
	$query = "LOAD DATA LOCAL INFILE '".addslashes($physical_file)."' ".
		"INTO TABLE ".addslashes($table_name)." ".
		"FIELDS TERMINATED BY ','";
           
	$result = $sql->query ($query); // try doing it

	return $result; // send the results home...
} // end function freemed_import_stock_data

// function freemed_open_db
// --- simply backwards compatibility stub for freemed::connect
function freemed_open_db () {
	freemed::connect();
} // end function freemed_open_db

//---------------------------------------------------------------------------
// Time and Date Functions
//---------------------------------------------------------------------------

// Function: freemed_get_date_next
//
//	Get next valid SQL format date (YYYY-MM-DD)
//
// Parameters:
//
//	$date - Starting date
//
// Returns:
//
//	Next date.
//
function freemed_get_date_next ($cur_dt) {
	global $cur_date;

	$y = substr ($cur_dt, 0, 4); // get year
	$m = substr ($cur_dt, 5, 2); // get month
	$d = substr ($cur_dt, 8, 2); // get date

	// check for validity of given date... if not, cur_date
	if (!checkdate($m, $d, $y)) { 
		$y = substr ($cur_date, 0, 4);
		$m = substr ($cur_date, 5, 2);
		$d = substr ($cur_date, 8, 2); 
	}

	if (!checkdate($m, $d + 1, $y)) { // roll day?
		if (!checkdate($m + 1, 1, $y)) { // roll month?
			// roll year
			return date ("Y-m-d", mktime (0,0,0,1,1,$y+1));
		} else {
			// roll month
			return date ("Y-m-d", mktime (0,0,0,$m+1,1,$y));
		} // end checking roll month?
	} else { // checking roll day
		// roll day
		return date ("Y-m-d", mktime (0,0,0,$m,$d+1,$y));
	} // end checking roll day
} // end function freemed_get_date_next

// Function: freemed_get_date_prev
//
//	Get previous date in SQL format (YYYY-MM-DD)
//
// Parameters:
//
//	$date - Starting date
//
// Returns:
//
//	Previous date.
//
function freemed_get_date_prev ($cur_dt) {
	$cur_date = date ("Y-m-d");

	$y = substr ($cur_dt, 0, 4); // year
	$m = substr ($cur_dt, 5, 2); // month
	$d = substr ($cur_dt, 8, 2); // day 

	if (!checkdate ($m, $d, $y)) {
		$y = substr ($cur_date, 0, 4);
		$m = substr ($cur_date, 5, 2);
		$d = substr ($cur_date, 8, 2);
	} // if not right, use current date

	if (($d==1) AND ($m>1)) { // if first day...
		$d = 31; $m--; // roll back
		  // while day too high, decrease
		while (!checkdate ($m, $d, $y)) $d--;
		return date ("Y-m-d",mktime(0,0,0,$m,$d,$y));
	} else if (($d==1) AND ($m==1)) { 
		// roll back year
		$m=12; $y--; $d=31;
		return date ("Y-m-d",mktime(0,0,0,$m,$d,$y));
	} else { // checking for day
		// roll back day
		$d--;
		return date ("Y-m-d",mktime(0,0,0,$m,$d,$y));
	} // end checking for first day
} // end function freemed_get_date_prev

// Function: fm_date_assemble
//
//	Assemble seperate date fields into single SQL format date hash
//
// Parameters:
//
//	$varname - Name of the date variable
//
//	$array_index - (optional) Array index of $varname that should
//	contain the result data.
//
// Returns:
//
//	SQL formated date string.
//
function fm_date_assemble ($datevarname="", $array_index=-1) {
	// Check for variable name
	if ($datevarname=="")
		trigger_error ("fm_date_assemble: no variable name given",
			E_USER_ERROR);

	// Import into local scope
	global ${$datevarname."_m"}, ${$datevarname."_d"}, ${$datevarname."_y"};

	// Handle calendar js widget
	if (freemed::config_user_value('date_widget_type') == 'js') {
		global ${$datevarname};
		return ${$datevarname};
	}

	// Decide where they come from if they are from an array
	if ($array_index == -1) {
		$m = ${$datevarname."_m"};
		$d = ${$datevarname."_d"};
		$y = ${$datevarname."_y"};
	} else {
		$m = ${$datevarname."_m"}[$array_index];
		$d = ${$datevarname."_d"}[$array_index];
		$y = ${$datevarname."_y"}[$array_index];
	} // end checking for array index

	// Return assembled string in SQL format
	return $y."-".$m."-".$d;
} // end function fm_date_assemble

// Function: fm_date_entry
//
//	Creates XHTML-compliant date selection widget
//
// Parameters:
//
//	$varname - Variable name to contain the result data.
//
//	$pre_epoch - (optional) Whether the date selection widget should
//	contain years more than 20 in the past. Defaults to false.
//
//	$array_index - (optional) Array index for varname to determine
//	which element of the array is being used. Defaults to no array
//	index.
//
// Returns:
//
//	XHTML-compliant date selection widget.
//
function fm_date_entry ($datevarname="", $pre_epoch=false, $arrayvalue=-1) {
	if ($datevarname=="") return false;  // indicate problems

	// Determine array "suffix"
	if (($arrayvalue+0)==-1) { $suffix=""; $pos=""; }
	  else { $suffix="[]"; $pos="[$arrayvalue]"; }

	// Import into local scope present values
	global $$datevarname, ${$datevarname."_y"}, 
	  ${$datevarname."_m"}, ${$datevarname."_d"};

	// Quickly check to see if we have to replace the value
	/*
	if (empty(freemed::config_user_value('date_widget_type'))) {
		$GLOBALS['sql']->query(
			$GLOBALS['sql']->insert_query(
				'config',
				array(
					'c_option' => 'date_widget_type',
					'c_value' => 'js'
				)
			)
		);
	}
	*/

	// Check for use case to use special date widget
	if (freemed::config_user_value('date_widget_type') == 'js') {
		static $already_js;
		if (!$already_js) {
			$header .= "<link rel=\"Stylesheet\" type=\"text/css\" href=\"lib/template/default/calendar-system.css\"></link>\n";
			$header .= "<script language=\"javascript\" ".
				"src=\"lib/template/default/calendar_stripped.js\"></script>\n";
			$header .= "<script language=\"javascript\" ".
				"src=\"lib/template/default/calendar-en.js\"></script>\n";
			$header .= "<script language=\"javascript\" ".
				"src=\"lib/template/default/calendar-setup_stripped.js\"></script>\n";
			$already_js = true;
		}
		$buffer .= html_form::text_widget (
			$datevarname,
			array (
				'length' => 10,
				'id' => $datevarname.'_cal'
			)
		);
		$buffer .= "
		<img src=\"lib/template/default/img/calendar_widget.gif\" border=\"0\" id=\"".$datevarname."_img\" />
		";
		$footer .= "
		<script type=\"text/javascript\">
		Calendar.setup({
			inputField	:	\"".$datevarname."_cal\",
			ifFormat	:	'%Y-%m-%d',
			daFormat	:	'Y-d-m',
			singleClick	:	true,
			".( !empty(${$datevarname}) ?
			"date		:	'".${$datevarname}."'," : '' )."
			button		:	\"".$datevarname."_img\"
		});
		</script>
		";
		$GLOBALS['__freemed']['header'] .= $header;
		//$GLOBALS['__freemed']['footer'] .= $footer;
		return $buffer.$footer;
	}

	// Set months
	$months = array (
		"", // null so that 1 = Jan, not 0 = Jan
		__("Jan"),
		__("Feb"),
		__("Mar"),
		__("Apr"),
		__("May"),
		__("Jun"),
		__("Jul"),
		__("Aug"),
		__("Sep"),
		__("Oct"),
		__("Nov"),
		__("Dec")
	);

	// For brevity, import into single letter variables
	$w = ${$datevarname.$pos};
	$m = ${$datevarname."_m".$pos};
	$d = ${$datevarname."_d".$pos};
	$y = ${$datevarname."_y".$pos};

	// Determine *where the date is coming from...
	if (!empty($w)) {
		// If the whole is set... split into parts and use that
		$y = substr ($w, 0, 4);  // split year
		$m = substr ($w, 5, 2);  // split month
		$d = substr ($w, 8, 2);  // split day
	} elseif (empty($y) and empty($m) and empty($d)) {
		// If there is no whole and no parts, use current date
		$y = date ("Y")+0;
		$m = date ("m")+0;
		$d = date ("d")+0;
	} // end if not empty whole date

	// Determine what the range should be
	switch ($pre_epoch) {
		case true:
			$starting_year = (date("Y")-120);
			$ending_year   = (date("Y")+20);
			break;
		case false: default:
			$starting_year = (date("Y")-20);
			$ending_year   = (date("Y")+20);
			break;
	} // end switch for pre_epoch

	// If the dates are legacy, reasonable and out of range, accept
	if (($y>1800) AND ($y<$starting_year)) $starting_year = $y;
	if (($y>1800) AND ($y>$ending_year))   $ending_year   = $y;

	// Form the buffers, then assemble

	// Month buffer
	$buffer_m = "\t<select NAME=\"".$datevarname."_m$suffix\">\n".
		"\t\t<option VALUE=\"00\" ".
		( ($m==0) ? "SELECTED" : "" ).">".__("NONE")."</option>\n";
	for ($i=1;$i<=12;$i++) {
		$buffer_m .= "\n\t\t<option VALUE=\"".( ($i<10) ? "0" : "" ).
			"$i\" ".  ( ($i==$m) ? "SELECTED" : "" ).
			">".__($months[$i])."</option>\n";
	} // end for loop (months) 
	$buffer_m .= "\t</select>\n";

	// Day buffer
	$buffer_d = "\t<select NAME=\"".$datevarname."_d$suffix\">\n".
		"\t\t<option VALUE=\"00\" ".
		( ($d==0) ? "SELECTED" : "" ).">".__("NONE")."</option>\n";
	for ($i=1;$i<=31;$i++) {
		$buffer_d .= "\n\t\t<option VALUE=\"".( ($i<10) ? "0" : "" ).
			"$i\" ".( ($i==$d) ? "SELECTED" : "" ).">$i</option>\n";
	} // end looping for days
	$buffer_d .= "\t</select>\n";

	// Year buffer
	$buffer_y = "\t<select NAME=\"".$datevarname."_y$suffix\">\n".
		"\t\t<option VALUE=\"0000\" ".
		( ($y==0) ? "SELECTED" : "" ).">".__("NONE")."</option>\n";
	for ($i=$starting_year;$i<=$ending_year;$i++) {
		$buffer_y .= "\n\t\t<option VALUE=\"$i\" ".
			( ($i==$y) ? "SELECTED" : "" ).">$i</option>\n";
	} // end for look (years)
	$buffer_y .= "\t</select>\n";

	// now actually display the input boxes
	switch (freemed::config_value("dtfmt")) {
		case "mdy":
			return $buffer_m . " <b>-</b> ".
			$buffer_d . " <b>-</b> ".
			$buffer_y;
			break;
		case "dmy":
			return $buffer_d . " <b>-</b> ".
			$buffer_m . " <b>-</b> ".
			$buffer_y;
			break;
		case "ymd": default:
			return $buffer_y . " <b>-</b> ".
			$buffer_m . " <b>-</b> ".
			$buffer_d;
			break;
	} // end switch for dtfmt config value
} // end function fm_date_entry

// Function: fm_date_print
//
//	Create a nicely formatted date display
//
// Parameters:
//
//	$date - SQL formated date
//
//	$show_text_days - (optional) Whether or not to show the day names
//	as text names. Defaults to false.
//
// Returns:
//
//	Formatted date display.
//
function fm_date_print ($actualdate, $show_text_days=false) {
	$y  = substr ($actualdate, 0, 4);        // extract year
	$m  = substr ($actualdate, 5, 2);        // extract month
	$d  = substr ($actualdate, 8, 2);        // extract day
	$ts = mktime (0, 0, 0, $m, $d, $y<1970 ? 2000 : $y); // generate timestamp (fake year)

	$lang_months = array (
		'',
		__("Jan"),
		__("Feb"),
		__("Mar"),
		__("Apr"),
		__("May"),
		__("Jun"),
		__("Jul"),
		__("Aug"),
		__("Sep"),
		__("Oct"),
		__("Nov"),
		__("Dec")
	);

	// Return depending on configuration format
	switch (freemed::config_value("dtfmt")) {
		case "mdy":
			if ($show_text_days and ($y > 1969)) {
				return date("D F d, ", $ts).$y;
			} else {
				return date("F d, ", $ts).$y;
			}
			break;
		case "dmy":
			if ($show_text_days and ($y > 1969)) {
				return $d." ".$lang_months[0+$m].", ".$y;
			} else {
				return date("d M, ", $ts).$y;
			}
			break;
		case "ymd": default:
			if ($show_text_days and ($y > 1969)) {
				return date("D", $ts)." ".$y.date("-m-d", $ts);
			} else {
				return $y.date("-m-d", $ts);
			}
			break; 
	} // end switch
} // end function fm_date_print

// Function: fm_htmlize_array
//
//	Convert array to XHTML input type=HIDDEN tags
//
// Parameters:
//
//	$varname - Variable name to put the data in
//
//	$cur_array - Actual data to be stored
//
// Returns:
//
//	XHTML input type=HIDDEN tags
//
function fm_htmlize_array ($variable_name, $cur_array) {
	// Cache the length of the array
	$array_length = count ($cur_array);

	// If there is nothing in the array, return nothing
	if ($array_length==0) { return ""; }

	// Loop through the array
	for ($i=0; $i<$array_length; $i++)
		$buffer .= "\t<input TYPE=\"HIDDEN\" NAME=\"".
		prepare($variable_name)."[".prepare($i)."]\" ".
		"VALUE=\"".prepare($cur_array[$i])."\"/>\n";

	// Dump back the hash
	return $buffer;
} // end function fm_htmlize_array

function fm_make_string_array($string) {
	// ensure string ends in ,
	if (!strpos($string,","))
		return $string.",";
	return $string;
} // end function fm_make_string_array

function fm_join_from_array ($cur_array) {
	// If there is nothing, return nothing
	if (count($cur_array)==0) return "";

	// If it is scalar, return the value
	if (!is_array($cur_array)) return "$cur_array";

	// Otherwise compact it with "," as the separator character
	return implode ($cur_array, ",");
} // end function fm_join_from_array 

// Function: fm_number_select
//
//	Create an XHTML compliant number selection widget
//
// Parameters:
//
//	$varname - Name of the variable to store this data in
//
//	$min - (optional) Minimum value. Defaults to 0.
//
//	$max - (optional) Maximum value. Defaults to 10.
//
//	$step - (optional) Incrementing value. Defaults to 1.
//
//	$add_zero - (optional) Prepend zeros to values under 10. Defaults
//	to false.
//
//	$submit_on_blur - (optional) Submit the form when focus on the
//	widget is lost. Defaults to false.
//
// Returns:
//
//	XHTML-compliant number selection widget
//
function fm_number_select ($varname, $min=0, $max=10, $step=1, $addz=false, $submit_on_blur = false) {
	global ${$varname}; // bring in the variable

	// Pull into local scope
	$selected = ${$varname};

	// Start header
	$buffer = "\n\t<select NAME=\"".prepare($varname)."\" ".
		( $submit_on_blur ?
		"onChange=\"this.form.submit(); return true;\"" :
		"" ).">\n";

	// Check to make sure step isn't illegal
	if ($step==0) $step = 1;

	// Check to see if parameters are legal
	if ( ($min>$max) AND ($step>=0) )  return false;
	if ( ($min<$max) AND ($step<=0) )  return false;

	for ($i=$min; $i<=$max; $i+=$step) {
		$buffer .=  "\t\t<option VALUE=\"$i\"".
			( (("$selected"=="$i") or ($selected==$i)) ?
			"selected" : "" ).
			">".( (($i<10) and ($addz)) ? "0" : "" )."$i</option>\n";
	} // end for loop

	// Footer
	$buffer .= "\t</select>\n";

  	// Return buffer
	return $buffer;
} // end function fm_number_select

function fm_phone_assemble ($phonevarname="", $array_index=-1) {
  $buffer = ""; // we use buffered output for notebook class!
  if ($phonevarname=="") return ""; // return nothing if no variable is given
  global ${$phonevarname}, ${$phonevarname."_1"},
    ${$phonevarname."_2"}, ${$phonevarname."_3"}, 
    ${$phonevarname."_4"}, ${$phonevarname."_5"};
  if ($array_index == -1) {
    $w  = ${$phonevarname};    // whole number
    $p1 = ${$phonevarname."_1"};    // part 1
    $p2 = ${$phonevarname."_2"};    // part 2
    $p3 = ${$phonevarname."_3"};    // part 3
    $p4 = ${$phonevarname."_4"};    // part 4
    $p5 = ${$phonevarname."_5"};    // part 5
  } else {
    $w  = ${$phonevarname}[$array_index];  // whole number
    $p1 = ${$phonevarname."_1"}[$array_index];  // part 1
    $p2 = ${$phonevarname."_2"}[$array_index];  // part 2
    $p3 = ${$phonevarname."_3"}[$array_index];  // part 3
    $p4 = ${$phonevarname."_4"}[$array_index];  // part 4
    $p5 = ${$phonevarname."_5"}[$array_index];  // part 5
  } // end checking for array index

  // Check for case where parts aren't set, but whole is
  $phofmt = freemed::config_value('phofmt');
  if (${$phonevarname} and !${$phonevarname.'_1'} and ($phofmt=='usa' or $phofmt=='fr')) {
    return $w;
  }
  
  switch (freemed::config_value("phofmt")) {
    case "usa":
     return $p1.$p2.$p3.$p4;        // assemble number and put it all together
    case "fr":
     return $p1.$p2.$p3.$p4.$p5;    // assemble number and put it all together
    case "unformatted":
    default:
     return $w;                     // return whole number...
  } // end switch for formatting
} // end function fm_phone_assemble

function fm_phone_entry ($phonevarname="", $array_index=-1, $ext=true) {
  if ($phonevarname=="") return false;  // indicate problems
  if (($array_index+0)==-1) { $suffix="";   }     
   else                     { $suffix="[]"; }
  $formatting = freemed::config_value("phofmt"); // get phone formatting
  global $$phonevarname, ${$phonevarname."_1"},	 // get global vars
         ${$phonevarname."_2"}, ${$phonevarname."_3"}, 
         ${$phonevarname."_4"}, ${$phonevarname."_5"}; 

  // Check to see if autoskip JS is enabled
  if (!$GLOBALS['__phpwebtools']['autoskip']) {
    // Enable autoskip
    $buffer .= "
    	<script LANGUAGE=\"JavaScript\">
	function autoskip(here, next) {
		if (here.value.length==here.getAttribute('maxlength') && here.getAttribute) {
			next.focus()
		}
	}
	</script>
    ";
    
    // Set for future reference
    $GLOBALS['__phpwebtools']['autoskip'] = 1;
  }

  if ($array_index == -1)  {
    $w = ${$phonevarname};    // whole number
  } else {
    $w = ${$phonevarname}[$array_index];  // whole number
  }

  if (!empty($w)) {
    // if phone # is not empty, split
    switch ($formatting) {
      case "usa":
       $p1 = substr($w,  0, 3); // area code
       $p2 = substr($w,  3, 3); // prefix
       $p3 = substr($w,  6, 4); // local number
       $p4 = substr($w, 10, 4); // extention
       break;
      case "fr":
       $p1 = substr($w, 0, 2); 
       $p2 = substr($w, 2, 2); 
       $p3 = substr($w, 4, 2); 
       $p4 = substr($w, 6, 2); 
       $p5 = substr($w, 8, 2); 
       break;
      case "unformatted":
      default:
       // nothing!! hahahahahahahahahahahahaha!
       break;
    } // end formatting case statement
  } else { // end if not empty whole date
    if ($array_index == -1) {
      $p1 = ${$phonevarname."_1"};    // part 1
    $p2 = ${$phonevarname."_2"};    // part 2
    $p3 = ${$phonevarname."_3"};    // part 3
    $p4 = ${$phonevarname."_4"};    // part 4
    $p5 = ${$phonevarname."_5"};    // part 5
    } else {
    $p1 = ${$phonevarname."_1"}[$array_index];  // part 1
    $p2 = ${$phonevarname."_2"}[$array_index];  // part 2
    $p3 = ${$phonevarname."_3"}[$array_index];  // part 3
    $p4 = ${$phonevarname."_4"}[$array_index];  // part 4
    $p5 = ${$phonevarname."_5"}[$array_index];  // part 5
    } // end checking for array index
  }

  // now actually display the input boxes
  switch ($formatting) {
    case "usa":
     $buffer .= "
      <b>(</b>
      <input TYPE=\"TEXT\" NAME=\"".$phonevarname."_1$suffix\" SIZE=\"4\"
       MAXLENGTH=\"3\" VALUE=\"$p1\"
       onFocus=\"if (!this.value) { this.value='".freemed::config_value('default_area_code')."'; } return true;\" 
       onKeyup=\"autoskip(this, ".$phonevarname."_2$suffix); return true;\"
       /> <b>)</b>
      <input TYPE=\"TEXT\" NAME=\"".$phonevarname."_2$suffix\" SIZE=\"4\"
       MAXLENGTH=\"3\" VALUE=\"$p2\"
       onFocus=\"if (!".$phonevarname."_1.value) { ".$phonevarname."_1.value='".freemed::config_value('default_area_code')."'; } return true;\" 
       onKeyup=\"autoskip(this, ".$phonevarname."_3$suffix); return true;\"
       /> <b>-</b>
      <input TYPE=\"TEXT\" NAME=\"".$phonevarname."_3$suffix\" SIZE=\"5\"
       MAXLENGTH=\"4\" VALUE=\"$p3\" ".( $ext ? "
       onKeyup=\"autoskip(this, ".$phonevarname."_4$suffix); return true;\"
       " : "" )."/>".( $ext ? " <i>ext.</i>
      <input TYPE=\"TEXT\" NAME=\"".$phonevarname."_4$suffix\" SIZE=\"5\"
       MAXLENGTH=\"4\" VALUE=\"$p4\"/>" : "" ); break;
    case "fr":
     $buffer .= "
      <B>(</B>
      <input TYPE=\"TEXT\" NAME=\"".$phonevarname."_1$suffix\" SIZE=\"3\"
       MAXLENGTH=\"2\" VALUE=\"$p1\"
       onKeyup=\"autoskip(this, ".$phonevarname."_2$suffix); return true;\"
       /> <b>)</b>
      <input TYPE=\"TEXT\" NAME=\"".$phonevarname."_2$suffix\" SIZE=\"3\"
       MAXLENGTH=\"2\" VALUE=\"$p2\"
       onKeyup=\"autoskip(this, ".$phonevarname."_3$suffix); return true;\"
       /> 
      <input TYPE=\"TEXT\" NAME=\"".$phonevarname."_3$suffix\" SIZE=\"3\"
       MAXLENGTH=\"2\" VALUE=\"$p3\"
       onKeyup=\"autoskip(this, ".$phonevarname."_4$suffix); return true;\"
       />
      <input TYPE=\"TEXT\" NAME=\"".$phonevarname."_4$suffix\" SIZE=\"3\"
       MAXLENGTH=\"2\" VALUE=\"$p4\"
       onKeyup=\"autoskip(this, ".$phonevarname."_5$suffix); return true;\"
       />
      <input TYPE=\"TEXT\" NAME=\"".$phonevarname."_5$suffix\" SIZE=\"3\"
       MAXLENGTH=\"2\" VALUE=\"$p5\"
       />
     "; break;
    case "unformatted": 
    default:
     $buffer .= "
      <input TYPE=\"TEXT\" NAME=\"".$phonevarname."$suffix\" SIZE=\"15\"
       MAXLENGTH=\"16\" VALUE=\"$w\"/>
     "; break;
  } // end switch for dtfmt config value

  return $buffer;                         // we exited well!
} // end function fm_phone_entry

//---------------------------------------------------------------------------
// Variable Manipulation Functions
//---------------------------------------------------------------------------

// I am tired of trying to log stuff
// These all need an entry and log exit for log level 0
// Fred Trotter....



function fm_split_into_array ($original_string) {
	// If there is nothing to split, return nothing
	if (empty($original_string)) return "";

	// Split and return
	return explode (",", $original_string);
} // end function fm_split_into_array

function fm_value_in_array ($cur_array, $value) {
	// If there is no array, it obviously does not have the value
	if (count ($cur_array) < 0) return false;

	// Not sure about this...
	//if (!is_array ($cur_array)) return ($cur_array == $value);

	// loop through array
	for ($c=0;$c<count($cur_array);$c++)
		if ($cur_array[$c]==$value) // if there is a match...
			return true; // return true.

	// Return false if we didn't find it
	return false;
} // end function fm_split_into_array

function fm_value_in_string ($cur_string, $value) {
	// Check for "," separator indicating hash'd array
	if ( ! (strpos ($cur_string, ",") === false) ) {
		// Split it out...
		$this_array = fm_split_into_array ($cur_string);
		// ... then use fm_value_in_array to return the value
		return fm_value_in_array ($this_array, $value);
	} // end checking for ","

	// Otherwise do a simple substring match check
	//if (strstr($cur_string,$value) != "") return true;
	if (trim($cur_string) == trim($value)) { return true; }

	// If it hasn't been found, return false
	return false;
} // end function fm_value_in_string

// fm_eval -- evaluate string variables (with security checks, of course)
function fm_eval ($orig_string) {
	// Import all global variables
	foreach ($GLOBALS AS $k => $v) global ${$k};

	// Transfer to internal variable
	$loc_string = $orig_string;

	// Secure the string so that kiddies don't mess anything up
	$sec_string = fm_secure ($loc_string);

	// Use eval to pull in the proper variables
	eval ("\$new_string = \"$sec_string\";");

	// Return the processed string
	return $new_string;
} // end function fm_eval

// fm_secure -- secures strings that are to be evaled by simply removing
//              all secure varaibles...
function fm_secure ($orig_string) {
	// Variables to secure
	$secure_these = array (
		"db_user",
		"db_password",
		"db_host",
		"database",
		"gifhome",
		"db_engine"
	);

	// Pass to internal variable
	$this_string = "$orig_string"; 

	// Perform replacements
	foreach ( $secure_these AS $drek => $secure_var ) {
		$this_string = str_replace (
			"\$".$secure_var,
			"",
			$this_string
		);
	}

	// Return secured string
	return $this_string;
} // end function fm_secure

//---------------------------------------------------------------------------
// Patient Coverage Functions
//---------------------------------------------------------------------------

function fm_get_active_coverage ($ptid=0) {
	global $sql;

	// Initialize results
	$result = 0;

	// If no patient ID was given, return 0
	if ($ptid == 0) return 0;

	// Form and perform query
	$query = "SELECT id FROM coverage WHERE ".
		"covpatient='".addslashes($ptid)."' ".
		"AND covstatus='".ACTIVE."'";
	$result = $sql->query($query);

	// If nothing was returned, return 0
	if (!$result) return $result;

	// Pull in id's for all pertinent records
        while ($rec = $sql->fetch_array($result)) $ins_id[] = $rec["id"];

	// If nothing was done, nothing return 0
	if (!isset($ins_id)) return 0;

	// Return the array of coverages
        return $ins_id;
} // end function fm_get_active_coverages

function fm_verify_patient_coverage($ptid=0, $coveragetype=PRIMARY) {
	global $sql, $cur_date;

	// Initialize result
	$result = 0;

	// Check for ptid, otherwise return 0
	if ($ptid == 0) return 0;
	
	// default coveragetype is primary	
	$query = "SELECT id FROM coverage WHERE ".
		"covpatient='".addslashes($ptid)."' AND ".
		"covstatus='".ACTIVE."' AND ".
		"covtype='".addslashes($coveragetype)."'";
	$result = $sql->query($query);

	// Check for results, otherwise return 0
	if (!$sql->results($result)) return 0;
		
	// Return the id
	$row = $sql->fetch_array($result);
	return $row[id];
} // end function fm_verify_patient_coverage

//---------------------------------------------------------------------------
// Time-related Functions
//---------------------------------------------------------------------------

function fm_time_entry ($timevarname="") {
  if ($timevarname=="") return false;  // indicate problems
  global $$timevarname, ${$timevarname."_h"}, 
    ${$timevarname."_m"}, ${$timevarname."_ap"};


  $w = $$timevarname;       
  $h = ${$timevarname."_h"};
  if (!empty($w))
  {
		// if timeval then extract the pieces
		// this could be first time thru since $timevarname
        // will not be saved across page invocations
	  $values = explode(":",$$timevarname);
      ${$timevarname."_h"}  = $values[0];
      ${$timevarname."_m"}  = $values[1];
      ${$timevarname."_ap"} = $values[2];
      $ap = $values[2];
     
  }
  elseif (empty($h))
  {
	  // if not timeval and not hour then
      // plug a default. we shoud have a value in $h
      // secondtime thru
	  $$timevarname = "00:00:AM";
      ${$timevarname."_h"} = "00";
	  ${$timevarname."_m"} = "00";
	  ${$timevarname."_ap"} = __("AM");
	  $ap = __("AM");
  }

  //echo ${$timevarname."_h"}."<BR>";
  //echo ${$timevarname."_m"}."<BR>";
  //echo ${$timevarname."_ap"}."<BR>";
	

  $buffer_h = fm_number_select($timevarname."_h",0,12);
  $buffer_m = fm_number_select($timevarname."_m",0,59);
  $buffer_ap = "<select NAME=\"$timevarname"."_ap"."\">".
	"<option VALUE=\"AM\" ".
		( $ap=="AM" ? "SELECTED" : "").">". __("AM")."</option>\n".
	"<option VALUE=\"PM\" ".
		( $ap=="PM" ? "SELECTED" : "").">". __("PM")."</option>\n";
   
  return $buffer_h.$buffer_m.$buffer_ap;
  
} // end fm_time_entry


function fm_time_assemble ($timevarname="") {
  if ($timevarname=="") return ""; // return nothing if no variable is given
  global ${$timevarname."_h"}, ${$timevarname."_m"}, ${$timevarname."_ap"};

    $m = ${$timevarname."_m"};
    $h = ${$timevarname."_h"};
    $ap = ${$timevarname."_ap"};
  return $h.":".$m.":".$ap;                     // return SQL format date
} // end function fm_time_assemble

//---------------------------------------------------------------------------
// Template-related Functions
//---------------------------------------------------------------------------

// Function: template_display
//
//	Display the current template
//
// Parameters:
//
//	$terminate - (optional) End script execution on termination of
//	function. Defaults to true.
//
function template_display ($terminate_on_execute=true) {
	global $display_buffer; // localize display buffer
	global $template; // localize template
	foreach ($GLOBALS AS $k => $v) global ${$k};

	include_once (freemed::template_file('template.php'));

	// Kill everything after this has been displayed
	if ($terminate_on_execute) die("");
} // end function template_display

//********************** END TEMPLATE SUPPORT

// Function: page_push
//
//	Push page onto global history stack.
//
function page_push () {
	global $page_title;
	$page_history = $_SESSION['page_history'];

	// Import it if it exists
	if (isset($_SESSION['page_history'])) {
		// Import
		$_page_history = $_SESSION['page_history'];

		// Check to see if this is the last item on the list...
		// ... kick out without adding.
		if (basename($_page_history[(count($_page_history))]) ==
			basename($_SERVER['PHP_SELF'])) return true;
	} // end checking for existing history

	// Add to the list of pages
	$_page_history["$page_title"] = basename($_SERVER['PHP_SELF'])."?".
		"module=".urlencode($_REQUEST['module'])."&".
		"action=".urlencode($_REQUEST['action'])."&".
		"type=".urlencode($_REQUEST['type']);

	// Reimport into SESSION
	$_SESSION['page_history'] = $_page_history;
} // end function page_push

// Function: page_pop
//
//	Pop off page from global history stack.
//
function page_pop () {
	// Return false if there is nothing in the list
	if (!isset($_SESSION['page_history'])) return false;

	// Import page_history
	$_page_history = $_SESSION['page_history'];

	// Otherwise get the last one and return it ...
	$to_return = $_page_history[(count($page_history)-1)];
	$to_return_name = $_page_history[(count($page_history_name)-1)];

	// .. then remove it from the stack
	unset($_page_history[(count($_page_history)-1)]);
	unset($_page_history_name[(count($_page_history)-1)]);

	// Reimport into SESSION
	$_SESSION['page_history'] = $_page_history;
	$_SESSION['page_history_name'] = $_page_history_name;

	// And return value (access as list(x,y) = page_pop())
	return array ($to_return, $to_return_name);
} // end function page_pop

// Function: patient_push
//
//	Push patient onto global history stack.
//
function patient_push ($patient) {
	// Import it if it exists
	if (isset($_SESSION['patient_history'])) {
		// Import
		$patient_history = $_SESSION['patient_history'];

		// Clean out null entries... and rogue arrays
		foreach ($patient_history AS $k => $v) {
			if (!$v) unset($patient_history[$k]);
			if (is_array($v)) unset($patient_history[$k]);
		} // end foreach

		// Check to see if this is the last item on the list...
		// ... kick out without adding.
		if ($patient_history[(count($patient_history))] == $patient) {
			// Reimport due to cleaning
			$_SESSION['patient_history'] = $patient_history;

			// And we don't have to add it, exit with true
			return true;
		} // end checking if we just saw them...
	} // end checking for existing history

	// Add to the list of pages
	$patient_history[] = $patient;

	// Reimport into SESSION
	$_SESSION['patient_history'] = $patient_history;
} // end function patient_push

// Function: patient_history_list
//
//	Get global history list for patients
//
// Returns:
//
//	Array of patients in global history list.
//
function patient_history_list () {
	// Return false if there is nothing in the list
	if (!is_array($_SESSION['patient_history'])) return false;

	// Import patient_history
	$patient_history = $_SESSION['patient_history'];

	// Sort by alpha
	ksort($patient_history);

	// Check for no patient history
	if (count($patient_history)<1) return false;

	// Create new empty array
	unset($history);

	// Loop through array
	foreach ($patient_history AS $k => $v) {
		// Kludge to get around strange PHP crashing error on
		// $v processing by checking if it's an array.
		if (!is_array($v)) {
			// Get patient information
			$this_patient = CreateObject('FreeMED.Patient', $v);
	
			// Form Lastname, Firstname, ID list item
			$key = $this_patient->fullName() . " (".$v.")";

			// Add to new array
			$history["$key"] = $v;
		}
	} // end foreach

	// Return generated array
	return array_reverse($history);
} // end function patient_history_list

// Function: page_history_list
//
//	Get global history list for pages
//
// Returns:
//
//	Array of pages in global history list.
//
function page_history_list () {
	// Return false if there is nothing in the list
	if (!is_array($_SESSION['page_history'])) return false;

	// Import patient_history
	$page_history = $_SESSION['page_history'];

	// Check for no patient history
	if (count($page_history)<1) return false;

	// Create new empty array
	unset($history);

	// Loop through array
	foreach ($page_history AS $k => $v) {
		if (!empty($k) and !empty($v) and !is_array($v)) {
			// Add to new array
			$history["$k"] = $v;
		}
	} // end foreach

	// Return generated array
	return array_reverse($history);
} // end function page_history_list

// Function: help_url
//
//	Contruct a help link from the specified page and section
//
// Parameters:
//
//	$page - (optional) Name of the page that this relates to.
//
//	$section - (optional) Subsection of the page.
//
// Returns:
//
//	Fully formed URL to the specified help page.
//
function help_url ( $page = "", $section = "" ) {
	$language = $_SESSION['language'];

	// If there's no page name, substitute in $PHP_SELF
	if ($page == "") {
		$page_name = page_name();
	} else {
		$page_name = $page;
	}

	// Produce name by removing .php
	$page_name = str_replace(".php", "", $page_name);

	// Build helpfile name...
	if (empty($page_name) AND empty($section)) {
		// Default if nothing is provided
		$_help_name = "locale/$language/doc/default.$language.html";
	} elseif (!empty($page_name) AND empty($section)) {
		// If just page name, leave out section
		$_help_name = "locale/$language/doc/$page_name.$language.html";
	} elseif (!empty($page_name) AND !empty($section)) {
		// Page name and section provided
		$_help_name = "locale/$language/doc/$page_name.$section.$language.html";
	} else {
		// Should never have section with no page name
		$_help_name = "locale/$language/doc/default.$language.html";
	}

	// Check to see if it exists
	if (!file_exists($_help_name)) {
		// Try to pass it back thru with just the page if section bites
		if (!empty($section)) {
			return help_url ($page_name);
		} else {
			// If it doesn't exist, don't pass it...
			return "help.php";
		}
	} else {
		if ($section != "") {
			return "help.php?page_name=".urlencode($page_name)."&".
				"section=".urlencode($section);
		} else {
			return "help.php?page_name=".urlencode($page_name);
		}
	}
} // end function help_url

//---------------------------------------------------------------------------
// Authentication Subsystem
//---------------------------------------------------------------------------

// TODO: Upgrade basic_authentication to deal with MD5 sums, since we're no longer doing plain text.

// Function: check_basic_authentication
//
//	Check current basic authentication against users in the database.
//	This function is broken until phpwebtools is upgraded to support
//	MD5-based basic authentication verification.
//
// Returns:
//
//	Boolean value, whether user is properly authenticated.
//
function check_basic_authentication () {
	global $sql;

	// Build array of users
	$query = "SELECT username, userpassword, userlevel FROM user";
	$result = $sql->query($query);
	if ($sql->results($result)) {
		while ($r = $sql->fetch_array($result)) {
			$users[(stripslashes($r['username']))] =
				stripslashes($r['userpassword']);
		} // end looping thru results
	} // end no results

	// Call phpwebtools' basic authentication function
	return basic_authentication(PACKAGENAME, $users);
} // end function check_basic_authentication

} // end checking for __API_PHP__

?>

About Koders | Resources | Downloads | Support | Black Duck | Terms of Service | DMCA | Privacy Policy | Contact Us