File: functions.inc.php

package info (click to toggle)
postfixadmin 2.3.5-2+deb7u1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 6,200 kB
  • sloc: php: 25,767; xml: 14,485; perl: 964; sh: 664; python: 169; makefile: 84
file content (2427 lines) | stat: -rw-r--r-- 71,098 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
<?php
/** 
 * Postfix Admin 
 * 
 * LICENSE 
 * This source file is subject to the GPL license that is bundled with  
 * this package in the file LICENSE.TXT. 
 * 
 * Further details on the project are available at : 
 *     http://www.postfixadmin.com or http://postfixadmin.sf.net 
 * 
 * @version $Id: functions.inc.php 1335 2012-01-15 12:10:59Z christian_boltz $ 
 * @license GNU GPL v2 or later. 
 * 
 * File: functions.inc.php
 * Contains re-usable code.
 */

$version = '2.3.5';

/**
 * check_session
 *  Action: Check if a session already exists, if not redirect to login.php
 * Call: check_session ()
 * @return String username (e.g. foo@example.com)
 */
function authentication_get_username()
{
    global $CONF;
    if (!isset($_SESSION['sessid'])) {
        header ("Location: " . $CONF['postfix_admin_url'] . "/login.php");
        exit(0);
    }
    $SESSID_USERNAME = $_SESSION['sessid']['username'];
    return $SESSID_USERNAME;
}

/**
 * Returns the type of user - either 'user' or 'admin' 
 * Returns false if neither (E.g. if not logged in)
 * @return String admin or user or (boolean) false.
 */
function authentication_get_usertype() {
    if(isset($_SESSION['sessid'])) {
        if(isset($_SESSION['sessid']['type'])) {
            return $_SESSION['sessid']['type'];
        }
    }
    return false;
}
/**
 *
 * Used to determine whether a user has a particular role.
 * @param String role-name. (E.g. admin, global-admin or user)
 * @return boolean True if they have the requested role in their session.
 * Note, user < admin < global-admin
 */
function authentication_has_role($role) {
    global $CONF;
    if(isset($_SESSION['sessid'])) {
        if(isset($_SESSION['sessid']['roles'])) {
            if(in_array($role, $_SESSION['sessid']['roles'])) {
                return true;
            }
        }
    }
    return false;
}

/**
 * Used to enforce that $user has a particular role when 
 * viewing a page.
 * If they are lacking a role, redirect them to 
 * $CONF['postfix_admin_url']/login.php
 *
 * Note, user < admin < global-admin
 */
function authentication_require_role($role) {
    global $CONF;
    // redirect to appropriate page?
    if(authentication_has_role($role)) {
        return True;
    }
    if($role === 'user') {
        header("Location: " . $CONF['postfix_admin_url'] . '/users/login.php');
    }
    else {
        header("Location: " . $CONF['postfix_admin_url'] . "/login.php");
    }
    exit(0);
}
/**
 * @return boolean TRUE if a admin, FALSE otherwise.
 */
function authentication_is_admin() {
    return authentication_get_usertype() == 'admin';
}

/**
 * @return boolean TRUE if a user, FALSE otherwise.
 */
function authentication_is_user() {
    return authentication_get_usertype() == 'user';
}


/**
 * Add an error message for display on the next page that is rendered.
 * @param String message to show. 
 *
 * Stores string in session. Flushed through header template.
 * @see _flash_string()
 */
function flash_error($string) {
    _flash_string('error', $string);
}

/**
 * Used to display an info message on successful update.
 * @param String $string
 * Stores data in sessio.
 * @see _flash_string()
 */
function flash_info($string) {
    _flash_string('info', $string);
}
/**
 * 'Private' method used for flash_info() and flash_error().
 */
function _flash_string($type, $string) {
    if(!isset($_SESSION['flash'])) {
        $_SESSION['flash'] = array();
    }
    if(!isset($_SESSION['flash'][$type])) {
        $_SESSION['flash'][$type] = array();
    }
    $_SESSION['flash'][$type][] = $string;
}

//
// check_language
// Action: checks what language the browser uses
// Call: check_language
// Parameter: $use_post - set to 0 if $_POST should NOT be read
//
function check_language ($use_post = 1)
{
    global $CONF;
    global $supported_languages; # from languages/languages.php

    $lang = $CONF['default_language'];

    if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
    {
        $lang_array = preg_split ('/(\s*,\s*)/', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        if (safecookie('lang')) {
            array_unshift($lang_array, safecookie('lang')); # prefer language from cookie
        }
        if ( $use_post && safepost('lang')) {
            array_unshift($lang_array, safepost('lang')); # but prefer $_POST['lang'] even more
        }

        for($i = 0; $i < count($lang_array); $i++)
        {
            $lang_next = $lang_array[$i];
            $lang_next = strtolower(trim($lang_next));
            if(array_key_exists($lang_next, $supported_languages))
            {
                $lang = $lang_next;
                break;
            }
        }
    }
    return $lang;
}

//
// language_selector
// Action: returns a language selector dropdown with the browser (or cookie) language preselected
// Call: language_selector()
//
function language_selector()
{
    global $supported_languages; # from languages/languages.php

    $current_lang = check_language();

    $selector = '<select name="lang" xml:lang="en" dir="ltr">';

    foreach($supported_languages as $lang => $lang_name) {
        if ($lang == $current_lang) {
            $selected = ' selected="selected"';
        } else {
            $selected = '';
        }
        $selector .= "<option value='$lang'$selected>$lang_name</option>";
    }
    $selector .= "</select>";
    return $selector;
}

//
// check_string
// Action: checks if a string is valid and returns TRUE if this is the case.
// Call: check_string (string var)
//
function check_string ($var)
{
    if (preg_match ('/^([A-Za-z0-9 ]+)+$/', $var))
    {
        return true;
    }
    else
    {
        return false;
    }
}



//
// check_domain
// Action: Checks if domain is valid and returns TRUE if this is the case.
// Call: check_domain (string domain)
//
// TODO: make check_domain able to handle as example .local domains
function check_domain ($domain)
{
    global $CONF;
    global $PALANG;

    if (!preg_match ('/^([-0-9A-Z]+\.)+' . '([0-9A-Z]){2,6}$/i', ($domain)))
    {
        flash_error(sprintf($PALANG['pInvalidDomainRegex'], htmlentities($domain)));
        return false;
    }

    if (isset($CONF['emailcheck_resolve_domain']) && 'YES' == $CONF['emailcheck_resolve_domain'] && 'WINDOWS'!=(strtoupper(substr(php_uname('s'), 0, 7)))) 
    {

        // Look for an AAAA, A, or MX record for the domain

        if(function_exists('checkdnsrr')) {
            // AAAA (IPv6) is only available in PHP v. >= 5
            if (version_compare(phpversion(), "5.0.0", ">="))
            {
                if (checkdnsrr($domain,'AAAA')) return true;
            }
            if (checkdnsrr($domain,'A')) return true;
            if (checkdnsrr($domain,'MX')) return true;
            flash_error(sprintf($PALANG['pInvalidDomainDNS'], htmlentities($domain)));
            return false;
        }
        else {
            flash_error("emailcheck_resolve_domain is enabled, but function (checkdnsrr) missing!");
        }
    }

    return true;
}


/**
 * check_email
 * Checks if an email is valid - if it is, return true, else false.
 * @param String $email - a string that may be an email address.
 * @return boolean true if it's an email address, else false.
 * TODO: make check_email able to handle already added domains
 */
function check_email ($email)
{
    global $CONF;
    global $PALANG;

    $ce_email=$email;

    //strip the vacation domain out if we are using it
    //and change from blah#foo.com@autoreply.foo.com to blah@foo.com
    if ($CONF['vacation'] == 'YES')
    { 
        $vacation_domain = $CONF['vacation_domain'];
        $ce_email = preg_replace("/@$vacation_domain/", '', $ce_email);
        $ce_email = preg_replace("/#/", '@', $ce_email);
    }

    // Perform non-domain-part sanity checks
    if (!preg_match ('/^[-!#$%&\'*+\\.\/0-9=?A-Z^_{|}~]+' . '@' . '[^@]+$/i', trim ($ce_email)))
    {
        flash_error($PALANG['pInvalidMailRegex']);
        return false;
    }

    // Determine domain name
    $matches=array();
    if (!preg_match('|@(.+)$|',$ce_email,$matches))
    {
        flash_error($PALANG['pInvalidMailRegex']);
        return false;
    }
    $domain=$matches[1];

    # check domain name
    return check_domain($domain);
}



/**
 * Clean a string, escaping any meta characters that could be
 * used to disrupt an SQL string. i.e. "'" => "\'" etc.
 *
 * @param String (or Array) 
 * @return String (or Array) of cleaned data, suitable for use within an SQL
 *    statement.
 */
function escape_string ($string)
{
    global $CONF;
    // if the string is actually an array, do a recursive cleaning.
    // Note, the array keys are not cleaned.
    if(is_array($string)) {
        $clean = array();
        foreach(array_keys($string) as $row) {
            $clean[$row] = escape_string($string[$row]);  
        }
        return $clean;
    }
    if (get_magic_quotes_gpc ())
    {
        $string = stripslashes($string);
    }
    if (!is_numeric($string))
    {
        $link = db_connect();
        if ($CONF['database_type'] == "mysql")
        {
            $escaped_string = mysql_real_escape_string($string, $link);
        }
        if ($CONF['database_type'] == "mysqli")
        {
            $escaped_string = mysqli_real_escape_string($link, $string);
        }
        if ($CONF['database_type'] == "pgsql") 
        {
            // php 5.2+ allows for $link to be specified.
            if (version_compare(phpversion(), "5.2.0", ">="))
            {
                $escaped_string = pg_escape_string($link, $string);
            }
            else 
            {
                $escaped_string = pg_escape_string($string);
            }
        }
    }
    else
    {
        $escaped_string = $string;
    }
    return $escaped_string;
}


/**
 * safeget
 * Action: get value from $_GET[$param], or $default if $_GET[$param] is not set
 * Call: $param = safeget('param')   # replaces $param = $_GET['param']
 *       - or -
 *  $param = safeget('param', 'default')
 *
 *  @param String parameter name.
 *  @param String (optional) - default value if key is not set.
 *  @return String 
 */
function safeget ($param, $default="") {
    $retval=$default;
    if (isset($_GET[$param])) $retval=$_GET[$param];
    return $retval;
}

/**
 * safepost - similar to safeget()
 * @see safeget()
 * @param String parameter name
 * @param String (optional) default value (defaults to "")
 * @return String - value in $_POST[$param] or $default
 * same as safeget, but for $_POST
 */
function safepost ($param, $default="") {
    $retval=$default;
    if (isset($_POST[$param])) $retval=$_POST[$param];
    return $retval;
}

/**
 * safeserver
 * @see safeget()
 * @param String $param 
 * @param String $default (optional)
 * @return String value from $_SERVER[$param] or $default
 */
function safeserver ($param, $default="") {
    $retval=$default;
    if (isset($_SERVER[$param])) $retval=$_SERVER[$param];
    return $retval;
}

/**
 * safecookie
 * @see safeget()
 * @param String $param 
 * @param String $default (optional)
 * @return String value from $_COOKIE[$param] or $default
 */
function safecookie ($param, $default="") {
    $retval=$default;
    if (isset($_COOKIE[$param])) $retval=$_COOKIE[$param];
    return $retval;
}


//
// get_domain_properties
// Action: Get all the properties of a domain.
// Call: get_domain_properties (string domain)
//
function get_domain_properties ($domain)
{
    global $CONF;
    global $table_alias, $table_mailbox, $table_domain;
    $list = array ();

    $result = db_query ("SELECT COUNT(*) FROM $table_alias WHERE domain='$domain'");
    $row = db_row ($result['result']);
    $list['alias_count'] = $row[0];

    $result = db_query ("SELECT COUNT(*) FROM $table_mailbox WHERE domain='$domain'");
    $row = db_row ($result['result']);
    $list['mailbox_count'] = $row[0];

    $result = db_query ("SELECT SUM(quota) FROM $table_mailbox WHERE domain='$domain'");
    $row = db_row ($result['result']);
    $list['quota_sum'] = $row[0];
    $list['alias_count'] = $list['alias_count'] - $list['mailbox_count'];

    $list['alias_pgindex']=array ();
    $list['mbox_pgindex']=array ();
    $list['mbox_pgindex_count'] = 0;
    //while loop to figure index names. use page_size and loop of queries
    $i=0;
    $current=0;
    $page_size = (int) $CONF['page_size'];
    if ($page_size < 1) die ("\$CONF['page_size'] = '$page_size' is invalid (it may only contain digits and must be >= 1)");
    $tmpstr="";
    $idxlabel="";
    $list['alias_pgindex_count'] = 0;

    if ( $list['alias_count'] > $page_size )
    {
        while ( $current < $list['alias_count'] )
        { 
            $limitSql=('pgsql'==$CONF['database_type']) ? "1 OFFSET $current" : "$current, 1";
            $query = "SELECT $table_alias.address
                FROM $table_alias
                LEFT JOIN $table_mailbox ON $table_alias.address=$table_mailbox.username
                WHERE ($table_alias.domain='$domain' AND $table_mailbox.maildir IS NULL)
                ORDER BY $table_alias.address LIMIT $limitSql";
            $result = db_query ("$query");
            $row = db_array ($result['result']);
            $tmpstr = $row['address'];
            //get first 2 chars
            $idxlabel = $tmpstr[0] . $tmpstr[1] . "-";
            ($current + $page_size - 1 <= $list['alias_count']) ? $current = $current + $page_size - 1 : $current = $list['alias_count'] - 1;
            $limitSql=('pgsql'==$CONF['database_type']) ? "1 OFFSET $current" : "$current, 1";
            $query = "SELECT $table_alias.address
                FROM $table_alias
                LEFT JOIN $table_mailbox ON $table_alias.address=$table_mailbox.username
                WHERE ($table_alias.domain='$domain' AND $table_mailbox.maildir IS NULL)
                ORDER BY $table_alias.address LIMIT $limitSql";
            $result = db_query ("$query");
            $row = db_array ($result['result']);
            $tmpstr = $row['address'];
            $idxlabel = $idxlabel . $tmpstr[0] . $tmpstr[1];

            $current = $current + 1;

            $list['alias_pgindex'][]=$idxlabel;
            $i++;
        }
        $list['alias_pgindex_count']=$i;
    }

    $i=0;
    $current=0;
    $page_size = $CONF['page_size'];
    $tmpstr="";
    $idxlabel="";

    if ( $list['mailbox_count'] > $page_size )
    {
        while ( $current < $list['mailbox_count'] )
        { 
            $limitSql=('pgsql'==$CONF['database_type']) ? "1 OFFSET $current" : "$current, 1";
            $query = "SELECT $table_mailbox.username FROM $table_mailbox WHERE $table_mailbox.domain='$domain' ORDER BY $table_mailbox.username LIMIT $limitSql";
            $result = db_query ("$query");
            $row = db_array ($result['result']);
            $tmpstr = $row['username'];
            //get first 2 chars
            $idxlabel = $tmpstr[0] . $tmpstr[1] . "-";
            ($current + $page_size - 1 <= $list['mailbox_count']) ? $current = $current + $page_size - 1 : $current = $list['mailbox_count'] - 1;
            $limitSql=('pgsql'==$CONF['database_type']) ? "1 OFFSET $current" : "$current, 1";
            $query = "SELECT $table_mailbox.username FROM $table_mailbox WHERE $table_mailbox.domain='$domain' ORDER BY $table_mailbox.username LIMIT $limitSql";
            $result = db_query ("$query");
            $row = db_array ($result['result']);
            $tmpstr = $row['username'];
            $idxlabel = $idxlabel . $tmpstr[0] . $tmpstr[1];

            $current = $current + 1;

            $list['mbox_pgindex'][]=$idxlabel;
            $i++;
        }
        $list['mbox_pgindex_count']=$i;
    }

    // end mod

    $query="SELECT * FROM $table_domain WHERE domain='$domain'";
    if ('pgsql'==$CONF['database_type'])
    {
        $query=" SELECT *, EXTRACT(epoch FROM created) AS uts_created, EXTRACT(epoch FROM modified) AS uts_modified FROM $table_domain WHERE domain='$domain' ";
    }
    $result = db_query ($query);
    $row = db_array ($result['result']);
    $list['description'] = $row['description'];
    $list['aliases'] = $row['aliases'];
    $list['mailboxes'] = $row['mailboxes'];
    $list['maxquota'] = $row['maxquota'];
    $list['quota'] = $row['quota'];
    $list['transport'] = $row['transport'];
    $list['backupmx'] = $row['backupmx'];
    $list['created'] = $row['created'];
    $list['modified'] = $row['modified'];
    $list['active'] = $row['active'];

    if ($CONF['database_type'] == "pgsql")
    {
        $list['active']=('t'==$row['active']) ? 1 : 0;
        $list['backupmx']=('t'==$row['backupmx']) ? 1 : 0;
        $list['created']= gmstrftime('%c %Z',$row['uts_created']);
        $list['modified']= gmstrftime('%c %Z',$row['uts_modified']);
    }
    else
    {
        $list['active'] = $row['active'];
        $list['backupmx'] = $row['backupmx'];
    }

    return $list;
}



//
// get_mailbox_properties
// Action: Get all the properties of a mailbox.
// Call: get_mailbox_properties (string mailbox)
//
function get_mailbox_properties ($username)
{
    global $CONF;
    global $table_mailbox;
    $query="SELECT * FROM $table_mailbox WHERE username='$username'";
    if ('pgsql'==$CONF['database_type'])
    {
        $query="
            SELECT
            *,
            EXTRACT(epoch FROM created) AS uts_created,
            EXTRACT(epoch FROM modified) AS uts_modified
            FROM $table_mailbox
            WHERE username='$username'
            ";
    }
    $result = db_query ($query);
    $row = db_array ($result['result']);
    $list['name'] = $row['name'];
    $list['maildir'] = $row['maildir'];
    $list['quota'] = $row['quota'];
    $list['domain'] = $row['domain'];
    $list['created'] = $row['created'];
    $list['modified'] = $row['modified'];
    $list['active'] = $row['active'];

    if ($CONF['database_type'] == "pgsql")
    {
        $list['active']=('t'==$row['active']) ? 1 : 0;
        $list['created']= gmstrftime('%c %Z',$row['uts_created']);
        $list['modified']= gmstrftime('%c %Z',$row['uts_modified']);
    }
    else
    {
        $list['active'] = $row['active'];
    }

    return $list;
}



//
// check_alias
// Action: Checks if the domain is still able to create aliases.
// Call: check_alias (string domain)
//
function check_alias ($domain)
{
    $limit = get_domain_properties ($domain);
    if ($limit['aliases'] == 0)
    {
        # 0 = unlimited, -1 = disabled
        return true;
    }
    if ($limit['aliases'] < 0)
    {
        return false;
    }
    if ($limit['alias_count'] >= $limit['aliases'])
    {
        return false;
    }
    else
    {
        return true;
    }
}



//
// check_mailbox
// Action: Checks if the domain is still able to create mailboxes.
// Call: check_mailbox (string domain)
//
function check_mailbox ($domain)
{
    $limit = get_domain_properties ($domain);
    /* -1 = disable, 0 = unlimited */
    if ($limit['mailboxes'] == 0)
    {
        return true;
    }
    if ($limit['mailboxes'] < 0)
    {
        return false;
    }
    if ($limit['mailbox_count'] >= $limit['mailboxes'])
    {
        return false;
    }
    else
    {
        return true;
    }
}



//
// check_quota
// Action: Checks if the user is creating a mailbox with the correct quota
// Call: check_quota (string domain)
//
function check_quota ($quota, $domain)
{
    $limit = get_domain_properties ($domain);
    if ($limit['maxquota'] == 0)
    {
        return true;
    }
    if (($limit['maxquota'] < 0) and ($quota < 0))
    {
        return true;
    }
    if (($limit['maxquota'] > 0) and ($quota == 0))
    {
        return false;
    }
    if ($quota > $limit['maxquota'])
    {
        return false;
    }
    else
    {
        return true;
    }
}



//
// multiply_quota
// Action: Recalculates the quota from bytes to MBs (multiply, *)
// Call: multiply_quota (string $quota)
//
function multiply_quota ($quota)
{
    global $CONF;
    if ($quota == -1) return $quota;
    $value = $quota * $CONF['quota_multiplier'];
    return $value;
}



//
// divide_quota
// Action: Recalculates the quota from MBs to bytes (divide, /)
// Call: divide_quota (string $quota)
//
function divide_quota ($quota)
{
    global $CONF;
    if ($quota == -1) return $quota;
    $value = round($quota / $CONF['quota_multiplier'],2);
    return $value;
}



//
// check_owner
// Action: Checks if the admin is the owner of the domain (or global-admin)
// Call: check_owner (string admin, string domain)
//
function check_owner ($username, $domain)
{
    global $table_domain_admins;
    $result = db_query ("SELECT 1 FROM $table_domain_admins WHERE username='$username' AND (domain='$domain' OR domain='ALL') AND active='1'");
    if ($result['rows'] != 1)
    {
        if ($result['rows'] > 1) { # "ALL" + specific domain permissions. 2.3 doesn't create such entries, but they are available as leftover from older versions
            flash_error("Permission check returned more than one result. Please go to 'edit admin' for your username and press the save "
             . "button once to fix the database. If this doesn't help, open a bugreport.");
        } 
        return false;
    }
    else
    {
        return true;
    }
}



//
// check_alias_owner
// Action: Checks if the admin is the owner of the alias.
// Call: check_alias_owner (string admin, string alias)
//
function check_alias_owner ($username, $alias)
{
    global $CONF;
    if (authentication_has_role('global-admin')) return true;
    $tmp = preg_split('/\@/', $alias);
    if (($CONF['special_alias_control'] == 'NO') && array_key_exists($tmp[0], $CONF['default_aliases']))
    {
        return false;
    }
    else
    {
        return true;
    }
}


/**
 * List domains for an admin user. 
 * @param String $username
 * @return array of domain names.
 */
function list_domains_for_admin ($username)
{
    global $CONF;
    global $table_domain, $table_domain_admins;
    $list = array ();
    // does $username need escaping here?
    $active_sql = db_get_boolean(True);
    $backupmx_sql = db_get_boolean(False);
    $query = "SELECT $table_domain.domain, $table_domain_admins.username FROM $table_domain 
        LEFT JOIN $table_domain_admins ON $table_domain.domain=$table_domain_admins.domain 
        WHERE $table_domain_admins.username='$username' 
        AND $table_domain.active='$active_sql'
        AND $table_domain.backupmx='$backupmx_sql'
        ORDER BY $table_domain_admins.domain";

    $result = db_query ($query);
    if ($result['rows'] > 0)
    {
        $i = 0;
        while ($row = db_array ($result['result']))
        {
            $list[$i] = $row['domain'];
            $i++;
        }
    }
    return $list;
}



//
// list_domains
// Action: List all available domains.
// Call: list_domains ()
//
function list_domains ()
{
    global $table_domain;
    $list = array();

    $result = db_query ("SELECT domain FROM $table_domain WHERE domain!='ALL' ORDER BY domain");
    if ($result['rows'] > 0)
    {
        $i = 0;
        while ($row = db_array ($result['result']))
        {
            $list[$i] = $row['domain'];
            $i++;
        }
    }
    return $list;
}




//
// admin_exist
// Action: Checks if the admin already exists.
// Call: admin_exist (string admin)
//
function admin_exist ($username)
{
    $result = db_query ("SELECT 1 FROM " . table_by_key ('admin') . " WHERE username='$username'");
    if ($result['rows'] != 1)
    {
        return false;
    }
    else
    {
        return true;
    }
}



//
// domain_exist
// Action: Checks if the domain already exists.
// Call: domain_exist (string domain)
//
function domain_exist ($domain)
{
    global $table_domain;

    $result = db_query("SELECT 1 FROM $table_domain WHERE domain='$domain'");
    if ($result['rows'] != 1)
    {
        return false;
    }
    else
    {
        return true;
    }
}



//
// list_admins
// Action: Lists all the admins
// Call: list_admins ()
//
// was admin_list_admins
//
function list_admins ()
{
    global $table_admin;
    $list = "";

    $result = db_query ("SELECT username FROM $table_admin ORDER BY username");
    if ($result['rows'] > 0)
    {
        $i = 0;
        while ($row = db_array ($result['result']))
        {
            $list[$i] = $row['username'];
            $i++;
        }
    }
    return $list;
}



//
// get_admin_properties
// Action: Get all the admin properties.
// Call: get_admin_properties (string admin)
//
function get_admin_properties ($username)
{
    global $CONF;
    global $table_admin, $table_domain_admins;
    $list = array ();

    $result = db_query ("SELECT * FROM $table_domain_admins WHERE username='$username' AND domain='ALL'");
    if ($result['rows'] == 1)
    {
        $list['domain_count'] = 'ALL';
    }
    else
    {
        $result = db_query ("SELECT COUNT(*) FROM $table_domain_admins WHERE username='$username'");
        $row = db_row ($result['result']);
        $list['domain_count'] = $row[0];
    }

    $query = "SELECT * FROM $table_admin WHERE username='$username'";
    if ('pgsql'==$CONF['database_type']) {
        $query="
            SELECT
            *,
            EXTRACT(epoch FROM created) AS uts_created,
            EXTRACT (epoch FROM modified) AS uts_modified
            FROM $table_admin
            WHERE username='$username'
            ";
    }

    $result = db_query ($query);
    $row = db_array ($result['result']);
    $list['created'] = $row['created'];
    $list['modified'] = $row['modified'];
    $list['active'] = $row['active'];
    if ('pgsql'==$CONF['database_type']) {
        $list['active'] = ('t'==$row['active']) ? 1 : 0;
        $list['created']= gmstrftime('%c %Z',$row['uts_created']);
        $list['modified']= gmstrftime('%c %Z',$row['uts_modified']);
    }
    return $list;
}



//
// encode_header
// Action: Encode a string according to RFC 1522 for use in headers if it contains 8-bit characters.
// Call: encode_header (string header, string charset)
//
function encode_header ($string, $default_charset = "utf-8")
{
    if (strtolower ($default_charset) == 'iso-8859-1')
    {
        $string = str_replace ("\240",' ',$string);
    }

    $j = strlen ($string);
    $max_l = 75 - strlen ($default_charset) - 7;
    $aRet = array ();
    $ret = '';
    $iEncStart = $enc_init = false;
    $cur_l = $iOffset = 0;

    for ($i = 0; $i < $j; ++$i)
    {
        switch ($string{$i})
        {
        case '=':
        case '<':
        case '>':
        case ',':
        case '?':
        case '_':
            if ($iEncStart === false)
            {
                $iEncStart = $i;
            }
            $cur_l+=3;
            if ($cur_l > ($max_l-2))
            {
                $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
                $aRet[] = "=?$default_charset?Q?$ret?=";
                $iOffset = $i;
                $cur_l = 0;
                $ret = '';
                $iEncStart = false;
            }
            else
            {
                $ret .= sprintf ("=%02X",ord($string{$i}));
            }
            break;
        case '(':
        case ')':
            if ($iEncStart !== false)
            {
                $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
                $aRet[] = "=?$default_charset?Q?$ret?=";
                $iOffset = $i;
                $cur_l = 0;
                $ret = '';
                $iEncStart = false;
            }
            break;
        case ' ':
            if ($iEncStart !== false)
            {
                $cur_l++;
                if ($cur_l > $max_l)
                {
                    $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
                    $aRet[] = "=?$default_charset?Q?$ret?=";
                    $iOffset = $i;
                    $cur_l = 0;
                    $ret = '';
                    $iEncStart = false;
                }
                else
                {
                    $ret .= '_';
                }
            }
            break;
        default:
            $k = ord ($string{$i});
            if ($k > 126)
            {
                if ($iEncStart === false)
                {
                    // do not start encoding in the middle of a string, also take the rest of the word.
                    $sLeadString = substr ($string,0,$i);
                    $aLeadString = explode (' ',$sLeadString);
                    $sToBeEncoded = array_pop ($aLeadString);
                    $iEncStart = $i - strlen ($sToBeEncoded);
                    $ret .= $sToBeEncoded;
                    $cur_l += strlen ($sToBeEncoded);
                }
                $cur_l += 3;
                // first we add the encoded string that reached it's max size
                if ($cur_l > ($max_l-2))
                {
                    $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
                    $aRet[] = "=?$default_charset?Q?$ret?= ";
                    $cur_l = 3;
                    $ret = '';
                    $iOffset = $i;
                    $iEncStart = $i;
                }
                $enc_init = true;
                $ret .= sprintf ("=%02X", $k);
            }
            else
            {
                if ($iEncStart !== false)
                {
                    $cur_l++;
                    if ($cur_l > $max_l)
                    {
                        $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
                        $aRet[] = "=?$default_charset?Q?$ret?=";
                        $iEncStart = false;
                        $iOffset = $i;
                        $cur_l = 0;
                        $ret = '';
                    }
                    else
                    {
                        $ret .= $string{$i};
                    }
                }
            }
            break;
        }
    }
    if ($enc_init)
    {
        if ($iEncStart !== false)
        {
            $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
            $aRet[] = "=?$default_charset?Q?$ret?=";
        }
        else
        {
            $aRet[] = substr ($string,$iOffset);
        }
        $string = implode ('',$aRet);
    }
    return $string;
}



//
// generate_password
// Action: Generates a random password
// Call: generate_password ()
//
function generate_password () {
    global $CONF;

    //check that password length is sensible
    $length = (int) $CONF['min_password_length'];
    if ($length < 5 || $length > 32) {
  	    $length = 8;
    }

    // define possible characters
    $possible = "2345678923456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"; # skip 0 and 1 to avoid confusion with O and l

    // add random characters to $password until $length is reached
    $password = "";
    while (strlen($password) < $length) {
        // pick a random character from the possible ones
        $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);

        // we don't want this character if it's already in the password
        if (!strstr($password, $char)) {
            $password .= $char;
        }
    }

    return $password;
}



/**
 * Encrypt a password, using the apparopriate hashing mechanism as defined in 
 * config.inc.php ($CONF['encrypt']). 
 * When wanting to compare one pw to another, it's necessary to provide the salt used - hence
 * the second parameter ($pw_db), which is the existing hash from the DB.
 *
 * @param string $pw
 * @param string $encrypted password
 * @return string encrypted password.
 */
function pacrypt ($pw, $pw_db="")
{
    global $CONF;
    $pw = stripslashes($pw);
    $password = "";
    $salt = "";

    if ($CONF['encrypt'] == 'md5crypt') {
        $split_salt = preg_split ('/\$/', $pw_db);
        if (isset ($split_salt[2])) {
            $salt = $split_salt[2];
        }
        $password = md5crypt ($pw, $salt);
    }

    elseif ($CONF['encrypt'] == 'md5') {
        $password = md5($pw);
    }

    elseif ($CONF['encrypt'] == 'system') {
        if (preg_match("/\\$1\\$/", $pw_db)) {
            $split_salt = preg_split ('/\$/', $pw_db);
            $salt = "\$1\$${split_salt[2]}\$";
        }
        else {
            if (strlen($pw_db) == 0) {
                $salt = substr (md5 (mt_rand ()), 0, 2);
            }
            else {
                $salt = substr ($pw_db, 0, 2);
            }
        }
        $password = crypt ($pw, $salt);
    }

    elseif ($CONF['encrypt'] == 'cleartext') {
        $password = $pw;
    }

    // See https://sourceforge.net/tracker/?func=detail&atid=937966&aid=1793352&group_id=191583
    // this is apparently useful for pam_mysql etc.
    elseif ($CONF['encrypt'] == 'mysql_encrypt')
    {
        $pw = escape_string($pw);
        if ($pw_db!="") {
            $salt=escape_string(substr($pw_db,0,2));
            $res=db_query("SELECT ENCRYPT('".$pw."','".$salt."');");
        } else {
            $res=db_query("SELECT ENCRYPT('".$pw."');");
        }
        $l = db_row($res["result"]);
        $password = $l[0];
    }

    elseif ($CONF['encrypt'] == 'authlib') {
        $flavor = $CONF['authlib_default_flavor'];
        $salt = substr(create_salt(), 0, 2); # courier-authlib supports only two-character salts
        if(preg_match('/^{.*}/', $pw_db)) {
            // we have a flavor in the db -> use it instead of default flavor
            $result = preg_split('/[{}]/', $pw_db, 3); # split at { and/or }
            $flavor = $result[1];  
            $salt = substr($result[2], 0, 2);
        }

        if(stripos($flavor, 'md5raw') === 0) {
            $password = '{' . $flavor . '}' . md5($pw);
        } elseif(stripos($flavor, 'md5') === 0) {
            $password = '{' . $flavor . '}' . base64_encode(md5($pw, TRUE));
        } elseif(stripos($flavor, 'crypt') === 0) {
            $password = '{' . $flavor . '}' . crypt($pw, $salt);
	} elseif(stripos($flavor, 'SHA') === 0) {
	    $password = '{' . $flavor . '}' . base64_encode(sha1($pw, TRUE));
        } else {
            die("authlib_default_flavor '" . $flavor . "' unknown. Valid flavors are 'md5raw', 'md5', 'SHA' and 'crypt'");
        }
    }

    elseif (preg_match("/^dovecot:/", $CONF['encrypt'])) {
        $split_method = preg_split ('/:/', $CONF['encrypt']);
        $method       = strtoupper($split_method[1]);
        if (! preg_match("/^[A-Z0-9-]+$/", $method)) { die("invalid dovecot encryption method"); }  # TODO: check against a fixed list?
        if (strtolower($method) == 'md5-crypt') die("\$CONF['encrypt'] = 'dovecot:md5-crypt' will not work because dovecotpw generates a random salt each time. Please use \$CONF['encrypt'] = 'md5crypt' instead."); 

        $dovecotpw = "dovecotpw";
        if (!empty($CONF['dovecotpw'])) $dovecotpw = $CONF['dovecotpw'];

        # Use proc_open call to avoid safe_mode problems and to prevent showing plain password in process table
        $spec = array(
            0 => array("pipe", "r"), // stdin
            1 => array("pipe", "w"), // stdout
            2 => array("pipe", "w"), // stderr
        );

        $pipe = proc_open("$dovecotpw '-s' $method", $spec, $pipes);

        if (!$pipe) {
            die("can't proc_open $dovecotpw");
        } else {
            // use dovecot's stdin, it uses getpass() twice
            // Write pass in pipe stdin
            fwrite($pipes[0], $pw . "\n", 1+strlen($pw)); usleep(1000);
            fwrite($pipes[0], $pw . "\n", 1+strlen($pw));
            fclose($pipes[0]);

            // Read hash from pipe stdout
            $password = fread($pipes[1], "200");

            if ( !preg_match('/^\{' . $method . '\}/', $password)) {
                $stderr_output = stream_get_contents($pipes[2]);
                error_log('dovecotpw password encryption failed.');
                error_log('STDERR output: ' . $stderr_output);
                die("can't encrypt password with dovecotpw, see error log for details"); 
            }

            fclose($pipes[1]);
            fclose($pipes[2]);
            proc_close($pipe);

            $password = trim(str_replace('{' . $method . '}', '', $password));
        }
    }

    else {
        die ('unknown/invalid $CONF["encrypt"] setting: ' . $CONF['encrypt']);
    }

    $password = escape_string ($password);
    return $password;
}

//
// md5crypt
// Action: Creates MD5 encrypted password
// Call: md5crypt (string cleartextpassword)
//

function md5crypt ($pw, $salt="", $magic="")
{
    $MAGIC = "$1$";

    if ($magic == "") $magic = $MAGIC;
    if ($salt == "") $salt = create_salt ();
    $slist = explode ("$", $salt);
    if ($slist[0] == "1") $salt = $slist[1];

    $salt = substr ($salt, 0, 8);
    $ctx = $pw . $magic . $salt;
    $final = hex2bin (md5 ($pw . $salt . $pw));

    for ($i=strlen ($pw); $i>0; $i-=16)
    {
        if ($i > 16)
        {
            $ctx .= substr ($final,0,16);
        }
        else
        {
            $ctx .= substr ($final,0,$i);
        }
    }
    $i = strlen ($pw);

    while ($i > 0)
    {
        if ($i & 1) $ctx .= chr (0);
        else $ctx .= $pw[0];
        $i = $i >> 1;
    }
    $final = hex2bin (md5 ($ctx));

    for ($i=0;$i<1000;$i++)
    {
        $ctx1 = "";
        if ($i & 1)
        {
            $ctx1 .= $pw;
        }
        else
        {
            $ctx1 .= substr ($final,0,16);
        }
        if ($i % 3) $ctx1 .= $salt;
        if ($i % 7) $ctx1 .= $pw;
        if ($i & 1)
        {
            $ctx1 .= substr ($final,0,16);
        }
        else
        {
            $ctx1 .= $pw;
        }
        $final = hex2bin (md5 ($ctx1));
    }
    $passwd = "";
    $passwd .= to64 (((ord ($final[0]) << 16) | (ord ($final[6]) << 8) | (ord ($final[12]))), 4);
    $passwd .= to64 (((ord ($final[1]) << 16) | (ord ($final[7]) << 8) | (ord ($final[13]))), 4);
    $passwd .= to64 (((ord ($final[2]) << 16) | (ord ($final[8]) << 8) | (ord ($final[14]))), 4);
    $passwd .= to64 (((ord ($final[3]) << 16) | (ord ($final[9]) << 8) | (ord ($final[15]))), 4);
    $passwd .= to64 (((ord ($final[4]) << 16) | (ord ($final[10]) << 8) | (ord ($final[5]))), 4);
    $passwd .= to64 (ord ($final[11]), 2);
    return "$magic$salt\$$passwd";
}

function create_salt ()
{
    srand ((double) microtime ()*1000000);
    $salt = substr (md5 (rand (0,9999999)), 0, 8);
    return $salt;
}

/**/ if (!function_exists('hex2bin')) { # PHP around 5.3.8 includes hex2bin as native function - http://php.net/hex2bin
function hex2bin ($str)
{
    $len = strlen ($str);
    $nstr = "";
    for ($i=0;$i<$len;$i+=2)
    {
        $num = sscanf (substr ($str,$i,2), "%x");
        $nstr.=chr ($num[0]);
    }
    return $nstr;
}
/**/ }

function to64 ($v, $n)
{
    $ITOA64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    $ret = "";
    while (($n - 1) >= 0)
    {
        $n--;
        $ret .= $ITOA64[$v & 0x3f];
        $v = $v >> 6;
    }
    return $ret;
}



//
// smtp_mail
// Action: Sends email to new account.
// Call: smtp_mail (string To, string From, string Data)
// TODO: Replace this with something decent like PEAR::Mail or Zend_Mail.
function smtp_mail ($to, $from, $data)
{
    global $CONF;
    $smtpd_server = $CONF['smtp_server'];
    $smtpd_port = $CONF['smtp_port'];
    $smtp_server = $_SERVER["SERVER_NAME"];
    $errno = "0";
    $errstr = "0";
    $timeout = "30";

    $fh = @fsockopen ($smtpd_server, $smtpd_port, $errno, $errstr, $timeout);

    if (!$fh)
    {
        return false;
    }
    else
    {
        $res = smtp_get_response($fh);
        fputs ($fh, "EHLO $smtp_server\r\n");
        $res = smtp_get_response($fh);
        fputs ($fh, "MAIL FROM:<$from>\r\n");
        $res = smtp_get_response($fh);
        fputs ($fh, "RCPT TO:<$to>\r\n");
        $res = smtp_get_response($fh);
        fputs ($fh, "DATA\r\n");
        $res = smtp_get_response($fh);
        fputs ($fh, "$data\r\n.\r\n");
        $res = smtp_get_response($fh);
        fputs ($fh, "QUIT\r\n");
        $res = smtp_get_response($fh);
        fclose ($fh);
    }
    return true;
}



//
// smtp_get_response
// Action: Get response from mail server
// Call: smtp_get_response (string FileHandle)
//
function smtp_get_response ($fh)
{
    $res ='';
    do
{
    $line = fgets($fh, 256);
    $res .= $line;
}
while (preg_match("/^\d\d\d\-/", $line));
return $res;
}



$DEBUG_TEXT = "\n
    <p />\n
    Please check the documentation and website for more information.\n
    <p />\n
    <a href=\"http://postfixadmin.sf.net/\">Postfix Admin</a><br />\n
    <a href='https://sourceforge.net/forum/forum.php?forum_id=676076'>Forums</a>
    ";


/**
 * db_connect
 * Action: Makes a connection to the database if it doesn't exist
 * Call: db_connect ()
 * Optional parameter: $ignore_errors = TRUE, used by setup.php
 *
 * Return value:
 * a) without $ignore_errors or $ignore_errors == 0
 *    - $link - the database connection -OR-
 *    - call die() in case of connection problems
 * b) with $ignore_errors == TRUE
 *    array($link, $error_text);
 */
function db_connect ($ignore_errors = 0)
{
    global $CONF;
    global $DEBUG_TEXT;
    if ($ignore_errors != 0) $DEBUG_TEXT = '';
    $error_text = '';
    $link = 0;

    if ($CONF['database_type'] == "mysql")
    {
        if (function_exists ("mysql_connect"))
        {
            $link = @mysql_connect ($CONF['database_host'], $CONF['database_user'], $CONF['database_password']) or $error_text .= ("<p />DEBUG INFORMATION:<br />Connect: " .  mysql_error () . "$DEBUG_TEXT");
            if ($link) {
                @mysql_query("SET CHARACTER SET utf8",$link);
                @mysql_query("SET COLLATION_CONNECTION='utf8_general_ci'",$link);
                $succes = @mysql_select_db ($CONF['database_name'], $link) or $error_text .= ("<p />DEBUG INFORMATION:<br />MySQL Select Database: " .  mysql_error () . "$DEBUG_TEXT");
            }
        }
        else
        {
            $error_text .= "<p />DEBUG INFORMATION:<br />MySQL 3.x / 4.0 functions not available! (php5-mysql installed?)<br />database_type = 'mysql' in config.inc.php, are you using a different database? $DEBUG_TEXT";
        }
    }
    elseif ($CONF['database_type'] == "mysqli")
    {
        if (function_exists ("mysqli_connect"))
        {
            $link = @mysqli_connect ($CONF['database_host'], $CONF['database_user'], $CONF['database_password']) or $error_text .= ("<p />DEBUG INFORMATION:<br />Connect: " .  mysqli_connect_error () . "$DEBUG_TEXT");
            if ($link) {
                @mysqli_query($link,"SET CHARACTER SET utf8");
                @mysqli_query($link,"SET COLLATION_CONNECTION='utf8_general_ci'");
                $success = @mysqli_select_db ($link, $CONF['database_name']) or $error_text .= ("<p />DEBUG INFORMATION:<br />MySQLi Select Database: " .  mysqli_error ($link) . "$DEBUG_TEXT");
            }
        }
        else
        {
            $error_text .= "<p />DEBUG INFORMATION:<br />MySQL 4.1 functions not available! (php5-mysqli installed?)<br />database_type = 'mysqli' in config.inc.php, are you using a different database? $DEBUG_TEXT";
        }
    }
    elseif ($CONF['database_type'] == "pgsql")
    {
        if (function_exists ("pg_pconnect"))
        {
            if(!isset($CONF['database_port'])) {
                $CONF['database_port'] = '5432';
            }
            $connect_string = "host=" . $CONF['database_host'] . " port=" . $CONF['database_port'] . " dbname=" . $CONF['database_name'] . " user=" . $CONF['database_user'] . " password=" . $CONF['database_password'];
            $link = @pg_pconnect ($connect_string) or $error_text .= ("<p />DEBUG INFORMATION:<br />Connect: failed to connect to database. $DEBUG_TEXT");
            if ($link) pg_set_client_encoding($link, 'UNICODE');
        }
        else
        {
            $error_text .= "<p />DEBUG INFORMATION:<br />PostgreSQL functions not available! (php5-pgsql installed?)<br />database_type = 'pgsql' in config.inc.php, are you using a different database? $DEBUG_TEXT";
        }
    }
    else
    {
        $error_text = "<p />DEBUG INFORMATION:<br />Invalid \$CONF['database_type']! Please fix your config.inc.php! $DEBUG_TEXT";
    }

    if ($ignore_errors)
    {
        return array($link, $error_text);
    }
    elseif ($error_text != "")
    {
        print $error_text;
        die();
    }
    elseif ($link)
    {
        return $link;
    }
    else
    {
        print "DEBUG INFORMATION:<br />\n";
        print "Connect: Unable to connect to database<br />\n";
        print "<br />\n";
        print "Make sure that you have set the correct database type in the config.inc.php file<br />\n";
        print $DEBUG_TEXT;
        die();
    }
}

/**
 * Returns the appropriate boolean value for the database.
 * Currently only PostgreSQL and MySQL are supported.
 * @param boolean $bool (REQUIRED)
 * @return String or int as appropriate.
 */
function db_get_boolean($bool) {
    if(!is_bool($bool)) {
        die("Invalid usage of 'db_get_boolean($bool)'");
    }

    global $CONF;
    if($CONF['database_type']=='pgsql') {
        // return either true or false (unquoted strings)
        if($bool) {
            return 't';
        }  
        return 'f';
    }
    elseif($CONF['database_type'] == 'mysql' || $CONF['database_type'] == 'mysqli') {
        if($bool) {
            return 1;  
        } 
        return 0;
    }
}

//
// db_query
// Action: Sends a query to the database and returns query result and number of rows
// Call: db_query (string query)
// Optional parameter: $ignore_errors = TRUE, used by upgrade.php
//
function db_query ($query, $ignore_errors = 0)
{
    global $CONF;
    global $DEBUG_TEXT;
    $result = "";
    $number_rows = "";
    static $link;
    $error_text = "";
    if ($ignore_errors) $DEBUG_TEXT = "";

    if (!is_resource($link)) $link = db_connect ();

    if ($CONF['database_type'] == "mysql") $result = @mysql_query ($query, $link) 
        or $error_text = "<p />DEBUG INFORMATION:<br />Invalid query: " . mysql_error($link) . "$DEBUG_TEXT";
    if ($CONF['database_type'] == "mysqli") $result = @mysqli_query ($link, $query) 
        or $error_text = "<p />DEBUG INFORMATION:<br />Invalid query: " . mysqli_error($link) . "$DEBUG_TEXT";
    if ($CONF['database_type'] == "pgsql")
    {
        $result = @pg_query ($link, $query) 
            or $error_text = "<p />DEBUG INFORMATION:<br />Invalid query: " . pg_last_error() . "$DEBUG_TEXT";
    }
    if ($error_text != "" && $ignore_errors == 0) die($error_text);

    if ($error_text == "") {
        if (preg_match("/^SELECT/i", trim($query)))
        {
            // if $query was a SELECT statement check the number of rows with [database_type]_num_rows ().
            if ($CONF['database_type'] == "mysql") $number_rows = mysql_num_rows ($result);
            if ($CONF['database_type'] == "mysqli") $number_rows = mysqli_num_rows ($result);
            if ($CONF['database_type'] == "pgsql") $number_rows = pg_num_rows ($result);
        }
        else
        {
            // if $query was something else, UPDATE, DELETE or INSERT check the number of rows with
            // [database_type]_affected_rows ().
            if ($CONF['database_type'] == "mysql") $number_rows = mysql_affected_rows ($link);
            if ($CONF['database_type'] == "mysqli") $number_rows = mysqli_affected_rows ($link);
            if ($CONF['database_type'] == "pgsql") $number_rows = pg_affected_rows ($result);
        }
    }

    $return = array (
        "result" => $result,
        "rows" => $number_rows,
        "error" => $error_text
    );
    return $return;
}



// db_row
// Action: Returns a row from a table
// Call: db_row (int result)
//
function db_row ($result)
{
    global $CONF;
    $row = "";
    if ($CONF['database_type'] == "mysql") $row = mysql_fetch_row ($result);
    if ($CONF['database_type'] == "mysqli") $row = mysqli_fetch_row ($result);
    if ($CONF['database_type'] == "pgsql") $row = pg_fetch_row ($result);
    return $row;
}



// db_array
// Action: Returns a row from a table
// Call: db_array (int result)
//
function db_array ($result)
{
    global $CONF;
    $row = "";
    if ($CONF['database_type'] == "mysql") $row = mysql_fetch_array ($result);
    if ($CONF['database_type'] == "mysqli") $row = mysqli_fetch_array ($result);
    if ($CONF['database_type'] == "pgsql") $row = pg_fetch_array ($result);
    return $row;
}



// db_assoc
// Action: Returns a row from a table
// Call: db_assoc(int result)
//
function db_assoc ($result)
{
    global $CONF;
    $row = "";
    if ($CONF['database_type'] == "mysql") $row = mysql_fetch_assoc ($result);
    if ($CONF['database_type'] == "mysqli") $row = mysqli_fetch_assoc ($result);
    if ($CONF['database_type'] == "pgsql") $row = pg_fetch_assoc ($result);
    return $row;
}



//
// db_delete
// Action: Deletes a row from a specified table
// Call: db_delete (string table, string where, string delete)
//
function db_delete ($table,$where,$delete)
{
    # $table = table_by_key($table); # intentionally disabled to avoid breaking delete.php in 2.3.x
    # This makes the behaviour of this function incorrect, but delete.php is the only file in 2.3.x calling db_delete and expects this (wrong) behaviour.
    $query = "DELETE FROM $table WHERE " . escape_string($where) . "='" . escape_string($delete) . "'";
    $result = db_query ($query);
    if ($result['rows'] >= 1)
    {
        return $result['rows'];
    }
    else
    {
        return true;
    }
}


/**
 * db_insert
 * Action: Inserts a row from a specified table
 * Call: db_insert (string table, array values)
 * @param String $table - table name
 * @param array - key/value map of data to insert into the table.
 * @param array (optional) - array of fields to set to now()
 * @return int - number of inserted rows
 */
function db_insert ($table, $values, $timestamp = array())
{
    $table = table_by_key ($table);

    foreach(array_keys($values) as $key) {
        $values[$key] = "'" . escape_string($values[$key]) . "'";
    }

    foreach($timestamp as $key) {
        $values[$key] = "now()";
    }

    $sql_values = "(" . implode(",",escape_string(array_keys($values))).") VALUES (".implode(",",$values).")";

    $result = db_query ("INSERT INTO $table $sql_values");
    return $result['rows'];
}


/**
 * db_update
 * Action: Updates a specified table
 * Call: db_update (string table, array values, string where)
 * @param String $table - table name
 * @param String - WHERE condition
 * @param array - key/value map of data to insert into the table.
 * @param array (optional) - array of fields to set to now()
 * @return int - number of updated rows
 */
function db_update ($table, $where, $values, $timestamp = array())
{
    $table = table_by_key ($table);

    foreach(array_keys($values) as $key) {
        $sql_values[$key] = escape_string($key) . "='" . escape_string($values[$key]) . "'";
    }

    foreach($timestamp as $key) {
        $sql_values[$key] = escape_string($key) . "=now()";
    }

    $sql="UPDATE $table SET ".implode(",",$sql_values)." WHERE $where";

    $result = db_query ($sql);
    return $result['rows'];
}



/**
 * db_log
 * Action: Logs actions from admin
 * Call: db_log (string username, string domain, string action, string data)
 * Possible actions are:
 * 'create_alias'
 * 'create_alias_domain'
 * 'create_mailbox'
 * 'delete_alias'
 * 'delete_alias_domain'
 * 'delete_mailbox'
 * 'edit_alias'
 * 'edit_alias_state'
 * 'edit_alias_domain_state'
 * 'edit_mailbox'
 * 'edit_mailbox_state'
 * 'edit_password'
 */
function db_log ($username,$domain,$action,$data)
{
    global $CONF;
    global $table_log;
    $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];

    $action_list = array('create_alias', 'create_alias_domain', 'delete_alias', 'delete_alias_domain', 'edit_alias', 'create_mailbox', 'delete_mailbox', 'edit_mailbox', 'edit_alias_state', 'edit_alias_domain_state', 'edit_mailbox_state', 'edit_password');

    if(!in_array($action, $action_list)) {
        die("Invalid log action : $action");   // could do with something better?
    }

    if ($CONF['logging'] == 'YES')
    {
        $logdata = array(
            'username'  => "$username ($REMOTE_ADDR)",
            'domain'    => $domain,
            'action'    => $action,
            'data'      => $data,
        );
        $result = db_insert('log', $logdata, array('timestamp') );
        #$result = db_query ("INSERT INTO $table_log (timestamp,username,domain,action,data) VALUES (NOW(),'$username ($REMOTE_ADDR)','$domain','$action','$data')");
        if ($result != 1)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

/**
 * db_in_clause
 * Action: builds and returns the "field in(x, y)" clause for database queries
 * Call: db_in_clause (string field, array values)
 */
function db_in_clause($field, $values) {
    return " $field IN ('"
    . implode("','",escape_string(array_values($values))) 
    . "') "; 
}

//
// table_by_key
// Action: Return table name for given key
// Call: table_by_key (string table_key)
//
function table_by_key ($table_key)
{
    global $CONF;
    $table = $CONF['database_prefix'].$CONF['database_tables'][$table_key];
    if (empty($table)) $table = $table_key;
    return $table;
}



/*
   Called after a mailbox has been created in the DBMS.
   Returns: boolean.
 */
function mailbox_postcreation($username,$domain,$maildir,$quota)
{
    if (empty($username) || empty($domain) || empty($maildir))
    {
        trigger_error('In '.__FUNCTION__.': empty username, domain and/or maildir parameter',E_USER_ERROR);
        return FALSE;
    }

    global $CONF;
    $confpar='mailbox_postcreation_script';

    if (!isset($CONF[$confpar]) || empty($CONF[$confpar])) return TRUE;

    $cmdarg1=escapeshellarg($username);
    $cmdarg2=escapeshellarg($domain);
    $cmdarg3=escapeshellarg($maildir);
    if ($quota <= 0) $quota = 0;
    $cmdarg4=escapeshellarg($quota);
    $command=$CONF[$confpar]." $cmdarg1 $cmdarg2 $cmdarg3 $cmdarg4";
    $retval=0;
    $output=array();
    $firstline='';
    $firstline=exec($command,$output,$retval);
    if (0!=$retval)
    {
        error_log("Running $command yielded return value=$retval, first line of output=$firstline");
        print '<p>WARNING: Problems running mailbox postcreation script!</p>';
        return FALSE;
    }

    return TRUE;
}

/*
   Called after a mailbox has been altered in the DBMS.
   Returns: boolean.
 */
function mailbox_postedit($username,$domain,$maildir,$quota)
{
    if (empty($username) || empty($domain) || empty($maildir))
    {
        trigger_error('In '.__FUNCTION__.': empty username, domain and/or maildir parameter',E_USER_ERROR);
        return FALSE;
    }

    global $CONF;
    $confpar='mailbox_postedit_script';

    if (!isset($CONF[$confpar]) || empty($CONF[$confpar])) return TRUE;

    $cmdarg1=escapeshellarg($username);
    $cmdarg2=escapeshellarg($domain);
    $cmdarg3=escapeshellarg($maildir);
    if ($quota <= 0) $quota = 0;
    $cmdarg4=escapeshellarg($quota);
    $command=$CONF[$confpar]." $cmdarg1 $cmdarg2 $cmdarg3 $cmdarg4";
    $retval=0;
    $output=array();
    $firstline='';
    $firstline=exec($command,$output,$retval);
    if (0!=$retval)
    {
        error_log("Running $command yielded return value=$retval, first line of output=$firstline");
        print '<p>WARNING: Problems running mailbox postedit script!</p>';
        return FALSE;
    }

    return TRUE;
}


/*
   Called after a mailbox has been deleted in the DBMS.
   Returns: boolean.
 */
function mailbox_postdeletion($username,$domain)
{
    global $CONF;
    $confpar='mailbox_postdeletion_script';

    if (!isset($CONF[$confpar]) || empty($CONF[$confpar]))
    {
        return true;
    }

    if (empty($username) || empty($domain))
    {
        print '<p>Warning: empty username and/or domain parameter.</p>';
        return false;
    }

    $cmdarg1=escapeshellarg($username);
    $cmdarg2=escapeshellarg($domain);
    $command=$CONF[$confpar]." $cmdarg1 $cmdarg2";
    $retval=0;
    $output=array();
    $firstline='';
    $firstline=exec($command,$output,$retval);
    if (0!=$retval)
    {
        error_log("Running $command yielded return value=$retval, first line of output=$firstline");
        print '<p>WARNING: Problems running mailbox postdeletion script!</p>';
        return FALSE;
    }

    return TRUE;
}

/*
   Called after a domain has been added in the DBMS.
   Returns: boolean.
 */
function domain_postcreation($domain)
{
    global $CONF;
    $confpar='domain_postcreation_script';

    if (!isset($CONF[$confpar]) || empty($CONF[$confpar]))
    {
        return true;
    }

    if (empty($domain))
    {
        print '<p>Warning: empty domain parameter.</p>';
        return false;
    }

    $cmdarg1=escapeshellarg($domain);
    $command=$CONF[$confpar]." $cmdarg1";
    $retval=0;
    $output=array();
    $firstline='';
    $firstline=exec($command,$output,$retval);
    if (0!=$retval)
    {
        error_log("Running $command yielded return value=$retval, first line of output=$firstline");
        print '<p>WARNING: Problems running domain postcreation script!</p>';
        return FALSE;
    }

    return TRUE;
}

/*
   Called after a domain has been deleted in the DBMS.
   Returns: boolean.
 */
function domain_postdeletion($domain)
{
    global $CONF;
    $confpar='domain_postdeletion_script';

    if (!isset($CONF[$confpar]) || empty($CONF[$confpar]))
    {
        return true;
    }

    if (empty($domain))
    {
        print '<p>Warning: empty domain parameter.</p>';
        return false;
    }

    $cmdarg1=escapeshellarg($domain);
    $command=$CONF[$confpar]." $cmdarg1";
    $retval=0;
    $output=array();
    $firstline='';
    $firstline=exec($command,$output,$retval);
    if (0!=$retval)
    {
        error_log("Running $command yielded return value=$retval, first line of output=$firstline");
        print '<p>WARNING: Problems running domain postdeletion script!</p>';
        return FALSE;
    }

    return TRUE;
}

/*
   Called after an alias_domain has been deleted in the DBMS.
   Returns: boolean.
 */
function alias_domain_postdeletion($alias_domain)
{
    global $CONF;
    $confpar='alias_domain_postdeletion_script';

    if (!isset($CONF[$confpar]) || empty($CONF[$confpar]))
    {
        return true;
    }

    if (empty($alias_domain))
    {
        print '<p>Warning: empty alias_domain parameter.</p>';
        return false;
    }

    $cmdarg1=escapeshellarg($alias_domain);
    $command=$CONF[$confpar]." $cmdarg1";
    $retval=0;
    $output=array();
    $firstline='';
    $firstline=exec($command,$output,$retval);
    if (0!=$retval)
    {
        error_log("Running $command yielded return value=$retval, first line of output=$firstline");
        print '<p>WARNING: Problems running alias_domain postdeletion script!</p>';
        return FALSE;
    }

    return TRUE;
}

/*
   Called by mailbox_postcreation() after a mailbox has been
   created. Immediately returns, unless configuration indicates
   that one or more sub-folders should be created.

   Triggers E_USER_ERROR if configuration error is detected.

   If IMAP login fails, the problem is logged to the system log
   (such as /var/log/httpd/error_log), and the function returns
   FALSE.

   Returns FALSE on all other errors, or TRUE if everything
   succeeds.

   Doesn't clean up, if only some of the folders could be
   created.
 */
function create_mailbox_subfolders($login,$cleartext_password)
{
    global $CONF;

    if (empty($login))
    {
        trigger_error('In '.__FUNCTION__.': empty $login',E_USER_ERROR);
        return FALSE;
    }

    if (!isset($CONF['create_mailbox_subdirs']) || empty($CONF['create_mailbox_subdirs'])) return TRUE;

    if (!is_array($CONF['create_mailbox_subdirs']))
    {
        trigger_error('create_mailbox_subdirs must be an array',E_USER_ERROR);
        return FALSE;
    }

    if (!isset($CONF['create_mailbox_subdirs_host']) || empty($CONF['create_mailbox_subdirs_host']))
    {
        trigger_error('An IMAP/POP server host ($CONF["create_mailbox_subdirs_host"]) must be configured, if sub-folders are to be created',E_USER_ERROR);
        return FALSE;
    }

    $s_host=$CONF['create_mailbox_subdirs_host'];
    $s_prefix=$CONF['create_mailbox_subdirs_prefix'];
    $s_options='';
    $s_port='';

    if (
        isset($CONF['create_mailbox_subdirs_hostoptions'])
        && !empty($CONF['create_mailbox_subdirs_hostoptions'])
            ) {
                if (!is_array($CONF['create_mailbox_subdirs_hostoptions']))
                {
                    trigger_error('The $CONF["create_mailbox_subdirs_hostoptions"] parameter must be an array',E_USER_ERROR);
                    return FALSE;
                }
                foreach ($CONF['create_mailbox_subdirs_hostoptions'] as $o)
                {
                    $s_options.='/'.$o;
                }
            }

    if (isset($CONF['create_mailbox_subdirs_hostport']) && !empty($CONF['create_mailbox_subdirs_hostport']))
    {
        $s_port=$CONF['create_mailbox_subdirs_hostport'];
        if (intval($s_port)!=$s_port)
        {
            trigger_error('The $CONF["create_mailbox_subdirs_hostport"] parameter must be an integer',E_USER_ERROR);
            return FALSE;
        }
        $s_port=':'.$s_port;
    }

    $s='{'.$s_host.$s_port.$s_options.'}';

    sleep(1); # give the mail triggering the mailbox creation a chance to do its job

    $i=@imap_open($s,$login,$cleartext_password);
    if (FALSE==$i)
    {
        error_log('Could not log into IMAP/POP server: '.imap_last_error());
        return FALSE;
    }

    foreach($CONF['create_mailbox_subdirs'] as $f)
    {
        $f='{'.$s_host.'}'.$s_prefix.$f;
        $res=imap_createmailbox($i,$f);
        if (!$res) {
            error_log('Could not create IMAP folder $f: '.imap_last_error());
            @imap_close($i);
            return FALSE;
        }
        @imap_subscribe($i,$f);
    }

    @imap_close($i);
    return TRUE;
}


//
// gen_show_status
// Action: Return a string of colored &nbsp;'s that indicate 
//         the if an alias goto has an error or is sent to
//         addresses list in show_custom_domains 
// Call: gen_show_status (string alias_address)
//
function gen_show_status ($show_alias)
{
    global $CONF, $table_alias;
    $stat_string = "";

    $show_alias = escape_string($show_alias);

    $stat_goto = "";
    $stat_result = db_query ("SELECT goto FROM $table_alias WHERE address='$show_alias'");
    if ($stat_result['rows'] > 0)
    {
        $row = db_row ($stat_result['result']);
        $stat_goto = $row[0];
    }

    // UNDELIVERABLE CHECK
    if ( $CONF['show_undeliverable'] == 'YES' )
    {
        $gotos=array();
        $gotos=explode(',',$stat_goto);
        $undel_string="";

        //make sure this alias goes somewhere known
        $stat_ok = 1;
        while ( ($g=array_pop($gotos)) && $stat_ok )
        {
            $stat_catchall = substr($g,strpos($g,"@"));
            $stat_delimiter = "";
            if (!empty($CONF['recipient_delimiter'])) {
                $delimiter = preg_quote($CONF['recipient_delimiter'], "/");
                $stat_delimiter = preg_replace('/' .$delimiter. '[^' .$delimiter. ']*@/', "@", $g);
                $stat_delimiter = "OR address = '$stat_delimiter'";
            }
            $stat_result = db_query ("SELECT address FROM $table_alias WHERE address = '$g' OR address = '$stat_catchall' $stat_delimiter");
            if ($stat_result['rows'] == 0)
            {
                $stat_ok = 0;
            }
            if ( $stat_ok == 0 )
            {
                $stat_domain = substr($g,strpos($g,"@")+1);
                $stat_vacdomain = substr($stat_domain,strpos($stat_domain,"@")+1);
                if ( $stat_vacdomain == $CONF['vacation_domain'] )
                {
                    $stat_ok = 1;
                    break;
                }
                for ($i=0; $i < sizeof($CONF['show_undeliverable_exceptions']);$i++)
                {
                    if ( $stat_domain == $CONF['show_undeliverable_exceptions'][$i] )
                    {
                        $stat_ok = 1;
                        break;
                    }
                }
            }
        } // while
        if ( $stat_ok == 0 )
        {
            $stat_string .= "<span style='background-color:" . $CONF['show_undeliverable_color'] .
                "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
        }
        else
        {
            $stat_string .= $CONF['show_status_text'] . "&nbsp;";
        } 

    }
    else
    {
        $stat_string .= $CONF['show_status_text'] . "&nbsp;";
    } 

    // POP/IMAP CHECK
    if ( $CONF['show_popimap'] == 'YES' )
    {
        $stat_delimiter = "";
        if (!empty($CONF['recipient_delimiter'])) {
            $delimiter = preg_quote($CONF['recipient_delimiter'], "/");
            $stat_delimiter = preg_replace('/' .$delimiter. '[^' .$delimiter. '@]*@/', "@", $stat_goto);
            $stat_delimiter = ',' . $stat_delimiter;
        }

        //if the address passed in appears in its own goto field, its POP/IMAP
        if ( preg_match ('/,' . $show_alias . ',/', ',' . $stat_goto . $stat_delimiter . ',') )
        {
            $stat_string .= "<span  style='background-color:" . $CONF['show_popimap_color'] .
                "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
        }
        else
        {
            $stat_string .= $CONF['show_status_text'] . "&nbsp;";
        } 
    }

    // CUSTOM DESTINATION CHECK
    if ( count($CONF['show_custom_domains']) > 0 )
    {
        for ($i = 0; $i < sizeof ($CONF['show_custom_domains']); $i++)
        {
            if (preg_match ('/^.*' . $CONF['show_custom_domains'][$i] . '.*$/', $stat_goto))
            {
                $stat_string .= "<span  style='background-color:" . $CONF['show_custom_colors'][$i] .
                    "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
            }
            else
            {
                $stat_string .= $CONF['show_status_text'] . "&nbsp;";
            } 
        } 
    }
    else
    {
        $stat_string .= ";&nbsp;";
    } 

    //   $stat_string .= "<span style='background-color:green'> &nbsp; </span> &nbsp;" .
    //                  "<span style='background-color:blue'> &nbsp; </span> &nbsp;";
    return $stat_string;
}

/*
   Called by create-admin.php and setup.php

   Returns:
   array(
      'error' => 0,                             # 0 on success, otherwise > 0
      'tMessage' => '',                         # success / failure message
      'pAdminCreate_admin_username_text' => '', # help text / error message for username
      'pAdminCreate_admin_password_text' => ''  # error message for username
   )
 */

function create_admin($fUsername, $fPassword, $fPassword2, $fDomains, $no_generate_password=0)
{
    global $PALANG;
    global $CONF;
    $error = 0;
    $tMessage = '';
    $pAdminCreate_admin_username_text = '';
    $pAdminCreate_admin_password_text = '';

    if (!check_email ($fUsername))
    {
        $error = 1;
        $pAdminCreate_admin_username_text = $PALANG['pAdminCreate_admin_username_text_error1'];
    }

    if (empty ($fUsername) or admin_exist ($fUsername))
    {
        $error = 1;
        $pAdminCreate_admin_username_text = $PALANG['pAdminCreate_admin_username_text_error2'];
    }

    if (empty ($fPassword) or empty ($fPassword2) or ($fPassword != $fPassword2))
    {
        if (empty ($fPassword) and empty ($fPassword2) and $CONF['generate_password'] == "YES" && $no_generate_password == 0)
        {
            $fPassword = generate_password ();
        }
        else
        {
            $error = 1;
            $pAdminCreate_admin_username_text = $PALANG['pAdminCreate_admin_username_text'];
            $pAdminCreate_admin_password_text = $PALANG['pAdminCreate_admin_password_text_error'];
        }
    }

    if ($error != 1)
    {
        $password = pacrypt($fPassword);
        $pAdminCreate_admin_username_text = $PALANG['pAdminCreate_admin_username_text'];

        $result = db_query ("INSERT INTO " . table_by_key('admin') . " (username,password,created,modified) VALUES ('$fUsername','$password',NOW(),NOW())");
        if ($result['rows'] != 1)
        {
            $tMessage = $PALANG['pAdminCreate_admin_result_error'] . "<br />($fUsername)<br />";
        }
        else
        {
            if (!empty ($fDomains[0]))
            {
                for ($i = 0; $i < sizeof ($fDomains); $i++)
                {
                    $domain = escape_string($fDomains[$i]);
                    $result = db_query ("INSERT INTO " . table_by_key ('domain_admins') . " (username,domain,created) VALUES ('$fUsername','$domain',NOW())");
                }
            }
            $tMessage = $PALANG['pAdminCreate_admin_result_success'] . "<br />($fUsername";
            if ($CONF['generate_password'] == "YES" && $no_generate_password == 0)
            {
                $tMessage .= " / $fPassword)</br />";
            }
            else
            {
                if ($CONF['show_password'] == "YES" && $no_generate_password == 0)
                {
                    $tMessage .= " / $fPassword)</br />";
                }
                else
                {
                    $tMessage .= ")</br />";
                }
            }
        }
    }

    # TODO: should we log creation, editing and deletion of admins?
    # Note: needs special handling in viewlog, because domain is empty
    # db_log ($SESSID_USERNAME, '', 'create_admin', "$fUsername");

    return array(
        $error,
        $tMessage,
        $pAdminCreate_admin_username_text,
        $pAdminCreate_admin_password_text
    );


}



/*
   Convert $CONF['whatever'] to boolean
   (obviously only useful for settings that can be YES or NO)

   Returns: TRUE (on YES/yes) or FALSE (on NO/no/not set/unknown value)
 */

function boolconf($setting) {
    global $CONF;
    if (!isset($CONF[$setting])) { # not set
        # TODO: show/log error message on unknown settings?
        return false;
    } elseif (strtoupper($CONF[$setting]) == 'YES') { # YES
        return true;
    } else { # NO, unknown value
        # TODO: show/log error message on unknown value?
        return false;
    }
}

$table_admin = table_by_key ('admin');
$table_alias = table_by_key ('alias');
$table_alias_domain = table_by_key ('alias_domain');
$table_domain = table_by_key ('domain');
$table_domain_admins = table_by_key ('domain_admins');
$table_log = table_by_key ('log');
$table_mailbox = table_by_key ('mailbox');
$table_vacation = table_by_key ('vacation');
$table_vacation_notification = table_by_key('vacation_notification');
$table_quota = table_by_key ('quota');
$table_quota2 = table_by_key ('quota2');
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */