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: 
<?php
    declare(strict_types=1);
    /**
     *  +------------------------------------------------------------+
     *  | apnscp                                                     |
     *  +------------------------------------------------------------+
     *  | Copyright (c) Apis Networks                                |
     *  +------------------------------------------------------------+
     *  | Licensed under Artistic License 2.0                        |
     *  +------------------------------------------------------------+
     *  | Author: Matt Saladna (msaladna@apisnetworks.com)           |
     *  +------------------------------------------------------------+
     */

    use Module\Provider;
    use Module\Skeleton\Contracts\Proxied;
    use Opcenter\Account\Enumerate;
    use Opcenter\Contracts\Hookable;
    use Opcenter\Crypto\Ssl;
    use Opcenter\Dns\Record;
    use Opcenter\Filesystem;
    use Opcenter\Mail\Services\Dovecot;
    use Opcenter\Mail\Services\Haproxy;
    use Opcenter\Mail\Services\Postfix;
    use Opcenter\Mail\Services\Webmail;
    use Opcenter\Mail\Storage;
    use Opcenter\Mail\Vacation;
    use Opcenter\Service\ConfigurationContext;

    /**
     * E-mail functions (aliases, virtual mailboxes)
     *
     * @package core
     */
    class Email_Module extends Module_Skeleton implements Hookable, Proxied
    {
        const DEPENDENCY_MAP = [
            'siteinfo',
            'ipinfo',
            'ipinfo6',
            'users',
            'aliases',
            'dns'
        ];
        const MAILDIR_HOME = Storage::MAILDIR_HOME;
        const MAILBOX_SPECIAL = 's';
        const MAILBOX_FORWARD = 'a';
        const MAILBOX_USER = 'v';
        const MAILBOX_DISABLED = 'd';
        const MAILBOX_ENABLED = 'e';
        const MAILBOX_SINGLE = '1';
        const MAILBOX_DESTINATION = 'destination';

        const VACATION_PREFKEY = 'mail.vacapref';
        // webmail installations
        const POSTFIX_CMD = '/usr/sbin/postfix';
        const SSL_PROXY_DIR = '/etc/haproxy/ssl.d';
        private $_webmail = array(
            'sqmail'    => array(
                'subdomain' => 'mail',
                'path'      => '/var/www/html/mail'
            ),
            'horde'     => array(
                'subdomain' => 'horde',
                'path'      => '/var/www/html/horde'
            ),
            'roundcube' => array(
                'subdomain' => 'roundcube',
                'path'      => '/var/www/html/roundcube'
            )
        );

        protected $exportedFunctions = [
            'address_exists'          => PRIVILEGE_SITE | PRIVILEGE_USER,
            'create_maildir_backend'  => PRIVILEGE_SITE | PRIVILEGE_SERVER_EXEC,
            'get_spool_size_backend'  => PRIVILEGE_SITE | PRIVILEGE_SERVER_EXEC,
            /** Vacation methods */
            'add_vacation'            => PRIVILEGE_SITE | PRIVILEGE_USER,
            'add_vacation_backend'    => PRIVILEGE_SITE | PRIVILEGE_USER,
            'set_vacation'            => PRIVILEGE_SITE | PRIVILEGE_USER,
            'set_vacation_options'    => PRIVILEGE_SITE | PRIVILEGE_USER,
            'get_vacation_options'    => PRIVILEGE_SITE | PRIVILEGE_USER,
            'vacation_exists'         => PRIVILEGE_SITE | PRIVILEGE_USER,
            'enable_vacation'         => PRIVILEGE_SITE | PRIVILEGE_USER,
            'remove_vacation'         => PRIVILEGE_SITE | PRIVILEGE_USER,
            'get_vacation_message'    => PRIVILEGE_SITE | PRIVILEGE_USER,
            'change_vacation_message' => PRIVILEGE_SITE | PRIVILEGE_USER,
            'get_webmail_location'    => PRIVILEGE_SITE | PRIVILEGE_USER,
            'webmail_apps'            => PRIVILEGE_SITE | PRIVILEGE_USER,
            'create_maildir'          => PRIVILEGE_SITE | PRIVILEGE_USER,
            'remove_maildir'          => PRIVILEGE_SITE | PRIVILEGE_USER,
            'user_enabled'            => PRIVILEGE_SITE | PRIVILEGE_USER,
            'get_mail_ip'             => PRIVILEGE_SITE | PRIVILEGE_USER,
            'user_mailboxes'          => PRIVILEGE_SITE | PRIVILEGE_USER,
            '*'                       => PRIVILEGE_SITE,
            'get_provider'            => PRIVILEGE_ALL,
            'providers'               => PRIVILEGE_ADMIN,
            'merge_ssl'               => PRIVILEGE_ADMIN,
        ];

        /**
         * {{{ void __construct(void)
         *
         * @ignore
         */
        public function __construct()
        {
            parent::__construct();
        }

        public function _proxy(): \Module_Skeleton
        {
            $provider = $this->get_provider();

            if ($provider === \Opcenter\Service\Contracts\DefaultNullable::NULLABLE_MARKER) {
                // BUG. An account's provider is substituted with the provider default at creation
                // Check for an in-place upgrade. If plan wasn't substituted because no prior def exists
                // the marker is used.
                $provider = \Opcenter\Mail::default();
            }

            if ($provider === 'builtin') {
                return $this;
            }

            return Provider::get('mail', $provider, $this->getAuthContext());
        }

        /**
         * Get DNS provider
         *
         * @return string
         */
        public function get_provider(): string
        {
            $provider = $this->getServiceValue('mail', 'provider', MAIL_PROVIDER_DEFAULT);

            if ($provider === \Opcenter\Service\Contracts\DefaultNullable::NULLABLE_MARKER) {
                // BUG. An account's provider is substituted with the provider default at creation
                // Check for an in-place upgrade. If plan wasn't substituted because no prior def exists
                // the marker is used.
                $provider = \Opcenter\Mail::default();
            }

            if ($this->permission_level & PRIVILEGE_SITE|PRIVILEGE_USER) {
                if (self::class !== static::class && !$this->enabled()) {
                    // block _proxy() load, which calls this helper in early init
                    return 'null';
                }
                return $provider;
            }

            return \Opcenter\Mail::default();
        }

        /**
         * Mail configured for account
         *
         * @return bool
         */
        public function configured(): bool
        {
            $provider = $this->get_provider();
            return $provider !== 'null';
        }

        /**
         * Get known mail providers
         *
         * @return array
         */
        public function providers(): array
        {
            return \Opcenter\Mail::providers();
        }

        public function list_aliases()
        {
            return $this->list_mailboxes('forward');
        }

        /**
         * List all mailboxes deliverable to user
         *
         * @param string|null $username
         */
        public function user_mailboxes(string $username = null)
        {
            if ($username && ($this->permission_level & PRIVILEGE_USER)) {
                return error('%(param)s disallowed as user', ['$username']);
            }
            $username = $username ?? $this->username;
            if (!$this->user_exists($username)) {
                return error('user %s does not exist', $username);
            }

            if (!$uid = $this->user_get_uid_from_username($username)) {
                return false;
            }
            // @TODO recursively solve alias destinations
            $q = 'SELECT
                    CONCAT("user", \'@\', e1."domain") AS email
                FROM email_lookup e1
                    JOIN domain_lookup USING (domain)
                WHERE
                    domain_lookup.site_id = ' . $this->site_id . ' AND
                    uid = ' . $uid . ' AND type = \'' . self::MAILBOX_USER . '\'';

            $addresses = [];

            $pgdb = \PostgreSQL::initialize();
            $pgdb->query($q);
            while (null !== ($row = $pgdb->fetch_object())) {
                $addresses[] = $row->email;
            }
            return $addresses;
        }

        /**
         * Retrieve mailbox delivery maps from system
         *
         * @param $filter  string optional filter, possible values: forward, local, special, single, enabled, disabled, destination
         * @param $address string supplementary argument to 'single', restrict address to %expr%. Mandatory for destination filter type
         * @param $domain  string optionally restrict to all addresses matching domain
         *
         * @return array
         *
         */
        public function list_mailboxes($filter = null, $address = null, $domain = null)
        {
            $filter_clause = '1=1';


            if ($filter == 'forward') {
                $filter = self::MAILBOX_FORWARD;
            } else if ($filter == 'local') {
                $filter = self::MAILBOX_USER;
            } else if ($filter == 'special') {
                $filter = self::MAILBOX_SPECIAL;
            } else if ($filter == 'disabled') {
                $filter = self::MAILBOX_DISABLED;
            } else if ($filter == 'enabled') {
                $filter = self::MAILBOX_ENABLED;
            }

            if ($filter && !in_array($filter, array(
                    self::MAILBOX_FORWARD,
                    self::MAILBOX_USER,
                    self::MAILBOX_SPECIAL,
                    self::MAILBOX_DISABLED,
                    self::MAILBOX_ENABLED,
                    self::MAILBOX_SINGLE,
                    self::MAILBOX_DESTINATION
                ))
            ) {
                return error("invalid filter specification `%s'", $filter);
            }

            if ($filter == self::MAILBOX_FORWARD) {
                $filter_clause = 'type = \'' . self::MAILBOX_FORWARD . '\'';
            } else if ($filter == self::MAILBOX_USER) {
                $filter_clause = 'type = \'' . self::MAILBOX_USER . '\'';
            } else if ($filter == self::MAILBOX_SPECIAL) {

            } else if ($filter == self::MAILBOX_SINGLE) {
                $filter_clause = 'email_lookup."user" ' . (false !== strpos($address,
                        '%') ? 'LIKE' : '=') . ' \'' . pg_escape_string($address) . '\'';
            } else if ($filter == self::MAILBOX_ENABLED) {
                $filter_clause = 'enabled = 1::bit';
            } else if ($filter == self::MAILBOX_DISABLED) {
                $filter_clause = 'enabled = 0::bit';
            } else if ($filter == self::MAILBOX_DESTINATION) {
                $filter_clause = 'COALESCE(uids."user",alias_destination) = ' . pg_escape_literal($address);
            }

            if (null !== $address && $filter !== self::MAILBOX_DESTINATION) {
                // @TODO nasty
                $filter_clause .= ' AND email_lookup.user = \'' . pg_escape_string(strtolower($address)) . '\'';
            }
            if ($domain) {
                $filter_clause .= ' AND email_lookup.domain = \'' . pg_escape_string(strtolower($domain)) . '\'';
            }
            $mailboxes = array();
            $query = '
            SELECT
                email_lookup."user",
                email_lookup.domain as domain,
                type,
                enabled,
                fs_destination AS target,
                uid,
                COALESCE(uids."user",alias_destination) as destination
            FROM
                email_lookup
            JOIN
                domain_lookup
            ON
                (email_lookup.domain = domain_lookup.domain)
            LEFT JOIN
                uids
            USING(uid)
            WHERE
                (domain_lookup.site_id = ' . $this->site_id . ') AND ' . $filter_clause . ' ORDER BY "user", domain;';
            $pgdb = \PostgreSQL::initialize();
            $pgdb->query($query);
            while (null !== ($row = $pgdb->fetch_object())) {
                $mailboxes[] = array(
                    'user'        => trim($row->user),
                    'domain'      => trim($row->domain),
                    'type'        => $row->type,
                    'enabled'     => (int)$row->enabled,
                    'mailbox'     => $row->destination,
                    'uid'         => (int)$row->uid,
                    'custom'      => ($filter === 'local' ? $row->target : null),
                    'destination' => $row->destination
                );
            }

            return $mailboxes;
        }

        public function enable_address($account, $domain = null)
        {
            $where = 'AND email_lookup.domain = domain_lookup.domain AND domain_lookup.site_id = ' . $this->site_id;
            if ($domain) {
                $where .= 'AND domain_lookup.domain = \'' . pg_escape_string($domain) . '\'';
            }
            $pgdb = \PostgreSQL::initialize();
            $pgdb->query('UPDATE email_lookup SET enabled = 1::bit FROM domain_lookup WHERE "user" = \'' . pg_escape_string($account) . '\' ' . $where . ';');

            return $pgdb->affected_rows() > 0;
        }

        /**
         * @deprecated @link modify_mailbox
         */
        public function rename_mailbox($olduser, $olddomain, $newuser, $newdomain, $newmailbox, $newtype = null)
        {
            return $this->modify_mailbox($olduser, $olddomain, $newuser, $newdomain, $newmailbox, $newtype);
        }

        /**
         * Rename a mailbox
         *
         * IMPORTANT: a mailbox may not be remapped into a catchall here
         *
         * @param string      $olduser
         * @param string      $olddomain
         * @param string      $newuser
         * @param string      $newdomain
         * @param string      $newdestination
         * @param string|null $newtype
         * @return bool
         */
        public function modify_mailbox(
            string $olduser,
            string $olddomain,
            string $newuser = '',
            string $newdomain = '',
            string $newdestination = '',
            string $newtype = null
        ): bool {
            $args = array(
                'olduser',
                'olddomain',
                'newuser',
                'newdomain',
                'newtype'
            );

            foreach ($args as $var) {
                ${$var} = strtolower((string)${$var});
            }
            if (!$newuser && !$newdomain) {
                $newuser = $olduser;
                $newdomain = $olddomain;
            }

            if ($olduser === 'majordomo' && $this->majordomo_enabled() && $this->majordomo_list_mailing_lists()) {
                return error('cannot remove majordomo email address while mailing lists exist');
            }

            if ($olduser && !$this->address_exists($olduser, $olddomain)) {
                return error("Address `%s@%s' does not exist", $olduser, $olddomain);
            }

            if ($newuser && !preg_match(Regex::EMAIL, "${newuser}@${newdomain}")) {
                return error("Invalid email `%s'", "${newuser}@${newdomain}");
            }

            if (($olduser . '@' . $olddomain != $newuser . '@' . $newdomain) && $this->address_exists($newuser,
                    $newdomain)
            ) {
                return error("Email address %s@%s already exists. Can't rename!",
                    $newuser, $newdomain);
            }

            if (!$this->transport_exists($olddomain)) {
                return error("Mail domain `%s' not bound to account", $olddomain);
            }

            if (!$this->transport_exists($newdomain)) {
                return error("Mail domain `%s' not bound to account", $newdomain);
            }

            if (!$newtype) {
                $newtype = $this->mailbox_type($olduser, $olddomain);
            }

            if ($newtype === self::MAILBOX_FORWARD && ($conflicts = $this->checkForwarding($newdestination))) {
                return error('Remote forwarding is disabled. Following addresses would violate forwarding policy: %s',
                    implode(',', $conflicts)
                );
            }

            $pgdb = \PostgreSQL::initialize();
            if ($newtype === self::MAILBOX_USER) {
                if (!ctype_digit($newdestination)) {
                    $newdestination = $this->user_get_uid_from_username($newdestination);
                }
                if (false !== ($uid = (int)$newdestination)) {
                    $uid = (int)$newdestination;
                    $local_user = $this->user_get_username_from_uid($uid);
                    $newdestination = self::MAILDIR_HOME;
                    if (!$local_user) {
                        return error("Invalid mailbox destination, invalid uid `%d'", $uid);
                    }
                } else if ($newdestination) {
                    if (preg_match('!^/home/([^/]+)/' . self::MAILDIR_HOME . '([/.]*)$!', $newdestination,
                        $match)) {
                        $local_user = $match[1];
                        $newdestination = ltrim(str_replace(array('/', '..'), '.', $match[2]), '.');
                    } else {
                        $local_user = $newdestination;
                        $newdestination = null;
                    }
                } else {
                    // user rename
                    $local_user = $newuser;
                }

                $local_user = strtolower($local_user);
                $users = $this->user_get_users();
                if (!isset($users[$local_user])) {
                    return error("User account `%s' does not exist", $local_user);
                }

                $uid = (int)$users[$local_user]['uid'];
                if ($newdestination == '' || $newdestination === self::MAILDIR_HOME) {
                    $newdestination = null;
                } else {
                    $this->query('email_create_maildir_backend', $local_user, $newdestination);
                }
                $pgdb->query("UPDATE email_lookup SET \"user\" = '" . $newuser . "', domain = '" . $newdomain . "', " .
                    'fs_destination = ' . (($newdestination != null) ? "'" . pg_escape_string(rtrim($newdestination,
                                ' /') . '/') . "'" : 'NULL') . ', ' .
                    'alias_destination = NULL, uid = ' . $uid . ", type = '" . self::MAILBOX_USER . "' WHERE \"user\" = '" . pg_escape_string($olduser) . "' " .
                    "AND domain = '" . pg_escape_string($olddomain) . "';");
            } else {
                if (!$newuser) {
                    return error('cannot forward catch-alls to external e-mail accounts');
                }
                $newdestination = preg_replace('/\s+/m', ',', trim($newdestination, ' ,'));
                if (!$newdestination) {
                    return error('no forwarding destination set for `%s@%s`', $newuser, $newdomain);
                }
                $pgdb->query("UPDATE email_lookup SET \"user\" = '" . pg_escape_string($newuser) . "', domain = '" . pg_escape_string($newdomain) . "', " .
                    "alias_destination = '" . pg_escape_string($newdestination) . "', uid = NULL, type = '" .
                    self::MAILBOX_FORWARD . "', fs_destination = NULL WHERE \"user\" = '" .
                    pg_escape_string($olduser) . "' AND domain = '" . pg_escape_string($olddomain) . "';");

            }
            $rows = $pgdb->affected_rows();
            $this->_shutdown_save_mailboxes();

            return $rows > 0;
        }

        /**
         * Validate an input type if forwarded
         *
         * @param $destination
         * @return null|array
         */
        protected function checkForwarding($destination): ?array {
            /**
             * Presently a loophole exists that would allow a domain to be attached to an account for mail,
             * forwarding aliases created, then that domain detached. Denying such a task piles admin
             * duties upon account holder to detach all aliases from an email account.
             */
            if (!MAIL_DISABLED_FORWARDING) {
                return null;
            }

            if (!is_array($destination)) {
                $destination = preg_split('/\s*,+\s*/', $destination);
            }

            $bad = [];
            $whitelisted = [];
            foreach ($destination as $chk) {
                if (false === ($pos = strpos($chk, '@'))) {
                    continue;
                }
                $domain = substr($chk, ++$pos);
                if (!isset($whitelisted[$domain])) {
                    $whitelisted[$domain] = $this->transport_exists($domain);
                }

                if (!$whitelisted[$domain]) {
                    $bad[] = $chk;
                }
            }

            return $bad;
        }

        public function address_exists($user, $domain)
        {
            $user = strtolower($user);
            $domain = strtolower($domain);
            if ($user && !preg_match(Regex::EMAIL, "${user}@${domain}")) {
                return false;
            }
            $pgdb = \PostgreSQL::initialize();
            $pgdb->query('SELECT 1 FROM email_lookup JOIN domain_lookup ON (site_id = ' . $this->site_id . ') ' .
                "WHERE \"user\" = '" . pg_escape_string($user) . "' AND email_lookup.domain = '" . pg_escape_string($domain) . "'");

            return $pgdb->num_rows() > 0;
        }

        /**
         * Get mailbox type
         *
         * @param $user
         * @param $domain
         * @return bool|null|string
         * @throws PostgreSQLError
         */
        public function mailbox_type($user, $domain)
        {
            $user = strtolower($user);
            $domain = strtolower($domain);
            if (!preg_match(Regex::EMAIL, $user . '@' . $domain)) {
                return error('invalid address `' . $user . '@' . $domain . "'");
            }
            $pgdb = \PostgreSQL::initialize();
            $pgdb->query("SELECT type FROM email_lookup WHERE \"user\" = '" . $user . "' AND domain = '" . $domain . "'");

            if ($pgdb->num_rows() < 1) {
                return null;
            }

            return $pgdb->fetch_object()->type;
        }

        private function _shutdown_save_mailboxes()
        {
            if (!IS_ISAPI) {
                $this->save_mailboxes();
            }
            static $called;
            if (isset($called)) {
                return;
            }
            $called = 1;

            return register_shutdown_function(array($this, 'save_mailboxes'));
        }

        /**
         * Save all mailboxes to a serialized file
         *
         * @see restore_mailboxes()
         *
         * @return boolean
         */
        public function save_mailboxes()
        {
            if (!IS_CLI) {
                if (!\apnscpSession::init()->exists($this->session_id)) {
                    // check session is active. Unit tests can trigger this.
                    return true;
                }
                return $this->query('email_save_mailboxes');
            }
            $path = $this->domain_info_path();
            if (!is_dir($path)) {
                // site deleted, ignore save
                return true;
            }
            $path .= '/email_addr';
            $email = $this->dump_mailboxes();

            return (bool)file_put_contents($path, serialize($email), LOCK_EX);
        }

        /**
         * List all mailboxes for backup/restore purposes
         *
         * @return array
         * @throws PostgreSQLError
         */
        public function dump_mailboxes(): array {
            $q = 'SELECT * FROM email_lookup WHERE domain IN
                (select domain FROM domain_lookup WHERE site_id = ' . $this->site_id . ')';
            $db = \PostgreSQL::pdo();
            $email = array();
            $rs = $db->query($q);
            while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
                $email[] = array_map('trim', $row);
            }
            return $email;
        }
        /**
         * Remove an e-mail alias
         *
         * @param string $user
         * @param string $domain
         */
        public function remove_alias($user, $domain)
        {
            return $this->delete_mailbox($user, $domain, self::MAILBOX_FORWARD);
        }

        public function delete_mailbox($user, $domain, $type = '')
        {
            $type = strtolower($type);
            if ($type == 'l' || $type == self::MAILBOX_USER) {
                $type = self::MAILBOX_USER;
            } else if ($type == 'f' || $type == self::MAILBOX_FORWARD) {
                $type = self::MAILBOX_FORWARD;
            } else if ($type != '') {
                return error("unknown address type `%s'", $type);
            }
            /**
             * otherwise we can clog up an mqueue pretty fast
             */
            if ($user === 'majordomo' && $this->majordomo_enabled() && $this->majordomo_list_mailing_lists()) {
                return error('cannot remove majordomo email address while mailing lists exist');
            }

            $clause = '';
            if ($type) {
                $clause = "AND type = '$type' ";
            }
            $pgdb = \PostgreSQL::initialize();
            $pgdb->query('DELETE FROM
                email_lookup
                WHERE
                "user" = \'' . pg_escape_string($user) . "'
                AND
                domain = '" . pg_escape_string($domain) . "'
                $clause
                AND '" . pg_escape_string($domain) . "' IN
                    (SELECT domain from domain_lookup WHERE site_id = " . $this->site_id . ');');
            $rows = $pgdb->affected_rows();
            $this->_shutdown_save_mailboxes();

            return $rows > 0;
        }

        public function get_mailbox($user, $domain)
        {
            $address = $this->list_mailboxes(self::MAILBOX_SINGLE, $user, $domain);

            return $address ? array_pop($address) : array();
        }

        public function remove_maildir($mailbox)
        {
            // assume remove_maildir() is only called by the owner
            if (!IS_CLI) {
                return $this->query('email_remove_maildir', $mailbox);
            }
            $mailbox = trim($mailbox);
            if ($mailbox[0] != '.') {
                $mailbox = '.' . $mailbox;
            }
            if (!preg_match(Regex::EMAIL_MAILDIR_FOLDER, $mailbox)) {
                return error("invalid maildir folder name `%s'", $mailbox);
            }
            $home = $this->user_get_user_home();
            $path = join(DIRECTORY_SEPARATOR, array($home, self::MAILDIR_HOME, $mailbox));
            if (!$this->file_delete($path, true)) {
                return error("failed to remove maildir `%s'", $mailbox);
            }

            $subscriptions = join(DIRECTORY_SEPARATOR,
                array(
                    $this->domain_fs_path(),
                    $home,
                    self::MAILDIR_HOME,
                    'subscriptions'
                )
            );
            $sname = trim($mailbox, '.');
            if (!file_exists($subscriptions)) {
                $contents = array();
            } else {
                $contents = file($subscriptions, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            }
            if (false === ($key = array_search($sname, $contents))) {
                return true;
            }
            unset($contents[$key]);
            file_put_contents($subscriptions, join("\n", $contents) . "\n");

            return Filesystem::chogp($subscriptions, $this->user_id, $this->group_id, 0600);

        }

        /**
         * Restore a saved copy of mailboxes
         *
         * @return boolean
         */
        public function restore_mailboxes($file = 'email_addr')
        {
            if (!IS_CLI) {
                return $this->query('email_restore_mailboxes', $file);
            }
            if (!preg_match('/^[\w_-]+$/', $file)) {
                return error("invalid mailbox backup `%s'", $file);
            }
            $file = $this->domain_info_path() . '/' . $file;
            if (!file_exists($file)) {
                warn("mailbox backup `%s' not found", basename($file));
                return -1;
            } else if (is_link($file)) {
                return error("restoration file `%s' must be regular file", $this->file_unmake_path($file));
            }
            $recs = \Util_PHP::unserialize(file_get_contents($file));
            $escapef = static function ($rec) {
                return '"' . $rec . '"';
            };
            $domainHash = [];
            $escapev = static function ($rec) {
                // empty values inserted as NULL
                if ($rec === '') {
                    return 'NULL';
                }

                if (ctype_digit($rec)) {
                    if ($rec == 0 || $rec == 1) {
                        /*
                         * assume this is the "enabled" column,
                         * which mandates a bit
                         */
                        $rec .= '::bit';
                    }

                    return $rec;
                }

                return "'" . pg_escape_string($rec) . "'";
            };
            $db = \PostgreSQL::initialize()->getHandler();
            foreach ($recs as $r) {
                $hostname = $r['domain'];
                if (!isset($domainHash[$hostname])) {
                    if ($this->transport_exists($hostname)) {
                        $domainHash[$hostname] = true;
                    } else {
                        // try first to automatically add
                        [$spltsb, $spltd] = $this->web_split_host($r['domain']);
                        if ( !($domainHash[$hostname] = $this->add_virtual_transport($spltd, $spltsb)) ) {
                            warn("Failed to add mail transport `%s'", $hostname);
                        }
                    }
                }
                if (!$domainHash[$hostname]) {
                    warn("Host `%s' not attached as mail transport - skipping `%s@%s'", $hostname, $r['user'], $r['domain']);
                    continue;
                }
                $fields = array_map($escapef, array_keys($r));
                $values = array_map($escapev, array_values($r));
                $q = 'INSERT INTO email_lookup (' . implode(',', $fields) .
                    ') VALUES(' . implode(',', $values) . ')';
                pg_send_query($db, $q);
                while (pg_connection_busy($db)) {
                    usleep(50);
                }
                $res = pg_get_result($db);

                if (false !== ($err = pg_result_error($res))) {
                    $errid = pg_result_error_field($res, PGSQL_DIAG_SQLSTATE);
                    /**
                     * 23505 (unique_violation) Query violates unique key
                     *
                     * @link http://www.postgresql.org/docs/8.2/static/errcodes-appendix.html
                     */
                    if ($errid === 23505) {
                        warn("skipped duplicate entry `%s@%s'",
                            $r['user'], $r['domain']);
                    } else if ($errid === 23514) {
                        warn("skipped entry `%s@%s': domain for `%s' not " .
                            'assigned to handle mail', $r['user'],
                            $r['domain'], $r['domain']);
                    } else {
                        error("skipped `%s@%s': unknown query error",
                            $r['user'], $r['domain']);
                    }
                }
            }

            return true;
        }

        public function remove_mailbox($user, $domain)
        {
            return $this->delete_mailbox($user, $domain);
        }

        /**
         * Domain is designated to receive e-mail on hosting server
         *
         * @param string $domain
         * @return bool
         */
        public function transport_exists($domain)
        {
            $q = \PostgreSQL::initialize()->query("SELECT site_id FROM domain_lookup WHERE domain = '" . pg_escape_string($domain) . "'");

            return $q->num_rows() > 0 && $q->fetch_object()->site_id == $this->site_id;
        }

        /***
         * int get_spool_size (string)
         *
         * @privilege PRIVILEGE_SITE
         * @return int size of the spool in bytes
         * @param $username username of the spool; note well this differs from
         *                  {@link File_Module::report_quota} in that the username is used instead of the uid.
         *                  This may change in the future.  There is a limitation in this process
         *                  in that it solely scans the main spool file for a user and excludes
         *                  all other inboxes created from IMAP applications (such as SquirrelMail).
         */
        public function get_spool_size($username)
        {

            if (!array_key_exists($username, $this->user_get_users())) {
                return error("Invalid user `%s'", $username);
            }

            return $this->query(
                'email_get_spool_size_backend',
                $this->domain_fs_path() . '/home/' . $username . '/' . self::MAILDIR_HOME
            );

        }

        /**
         * Get mail folder size
         *
         * @param string $path
         * @return bool|int
         */
        public function get_spool_size_backend($path)
        {
            if (!file_exists($path)) {
                return 0;
            }
            $proc = Util_Process_Safe::exec('du -s %s', $path);
            if (!$proc['success']) {
                return false;
            }

            return intval($proc['output']) * 1024;
        }

        /**
         * Get vacation options
         *
         * @return array
         */
        public function get_vacation_options(): array
        {
            $prefs = array_get(\Preferences::factory($this->getAuthContext()), self::VACATION_PREFKEY, []);
            $mb = Vacation::get($this->getAuthContext());
            $defaults = $mb->getDefaults();

            return array_merge($defaults, array_intersect_key($prefs, $defaults));
        }

        public function get_vacation_message($user = null)
        {
            if (!IS_CLI) {
                return $this->query('email_get_vacation_message', $user);
            }
            if (null !== $user && !($this->permission_level & PRIVILEGE_SITE)) {
                return error('unprivileged user may not setup vacation responder for other users');
            }

            if (null === $user) {
                $user = $this->username;
            } else if (!$this->user_exists($user)) {
                return error("unknown user `%s'", $user);
            }
            $svc = Vacation::getActiveService();
            $class = 'Vacation\\Providers\\' . $svc . '\\Options\\Message';
            $fqns = Vacation::appendNamespace($class);

            return (new $fqns)->getFromUser($user);
        }

        /**
         * Wrapper to set_vacation
         *
         * @deprecated
         * @param            $response
         * @param null       $user
         * @param array|null $flags
         * @return bool|mixed|void
         */
        public function add_vacation($response, $user = null, array $flags = null)
        {
            deprecated_func('use enable_vacation()');

            return $this->enable_vacation($response, $user, $flags);
        }

        /**
         * Enable vacation auto-responder
         *
         * @param null|string $user
         * @param array|null  $flags optional flags
         * @return bool|mixed|void
         */
        public function enable_vacation($user = null, array $flags = null)
        {
            if (!IS_CLI) {
                return $this->query('email_enable_vacation', $user, $flags);
            }
            if (null !== $user && !($this->permission_level & PRIVILEGE_SITE)) {
                return error('Non-privileged user may not setup vacation responder for other users');
            }

            if (null === $user) {
                $ctx = $this->getAuthContext();
            } else if (!$this->user_exists($user)) {
                return error("user `%s' does not exist", $user);
            } else if ($user && $flags) {
                return error('changing flags of secondary users not implemented');
            } else {
                $ctx = Auth::context($user, $this->site);
            }

            $driver = Vacation::get($ctx);
            $afi = \apnscpFunctionInterceptor::factory($ctx);
            if ($flags) {
                $afi->email_set_vacation_options($flags);
            }

            return $driver->enable();
        }

        /**
         * Set vacation options
         *
         * @param array $options
         * @return bool
         */
        public function set_vacation_options(array $options): bool
        {
            $driver = Vacation::get($this->getAuthContext());
            foreach ($driver->getDefaults() as $k => $v) {
                if (isset($options[$k]) && !$driver->setOption($k, $options[$k])) {
                    unset($options[$k]);
                }
            }
            $pref = \Preferences::factory($this->getAuthContext());
            $pref->unlock(apnscpFunctionInterceptor::factory($this->getAuthContext()));
            array_set($pref, self::VACATION_PREFKEY, $options);

            return true;
        }

        public function vacation_exists($user = null)
        {
            if (null !== $user && (($this->permission_level & PRIVILEGE_SITE) !== PRIVILEGE_SITE)) {
                return error('Unable to check vacation for non-admin account');
            }

            if (null === $user) {
                $ctx = $this->getAuthContext();
            } else {
                if (!$this->user_exists($user)) {
                    return false;
                }
                $ctx = Auth::context($user, $this->site);
            }

            if (!$this->user_exists($ctx->username)) {
                return error("Invalid user `%s'", $ctx->username);
            }

            return Vacation::get($ctx)->enabled();
        }

        /**
         * Change existing vacation message
         *
         * @param string      $response
         * @param string|null $user
         * @param array|null  $flags
         * @return bool
         */
        public function change_vacation_message($response, $user = null, array $flags = [])
        {
            deprecated_func('use set_vacation');

            return $this->enable_vacation($response, $user, $flags);
        }

        /**
         * Disable vacation status
         *
         * @param string|null user
         * @return bool
         */
        public function remove_vacation(string $user = null)
        {
            if (!IS_CLI) {
                return $this->query('email_remove_vacation', $user);
            }

            if ($user && ($this->permission_level & PRIVILEGE_SITE) !== PRIVILEGE_SITE) {
                return error('Unable to check vacation for non-admin account');
            }

            if ($user && !$this->user_exists($user)) {
                return error($user . ': invalid user');
            }

            $ctx = !$user ? $this->getAuthContext() : \Auth::context($user, $this->site);

            return Vacation::get($ctx)->disable();
        }

        /**
         * Clone inboxes from domain
         *
         * Wrapper to emulate dns:import-from-domain similarity
         *
         * @param string $domain domain to import into
         * @param string $src    domain to derive mailboxes from
         * @return bool
         * @throws PostgreSQLError
         */
        public function import_from_domain(string $domain, string $src): bool
        {
            return $this->clone_domain_mailboxes($src, $domain);
        }

        /**
         * Clone inboxes from domain
         *
         * @param $source
         * @param $destination
         * @return bool
         * @throws PostgreSQLError
         */
        public function clone_domain_mailboxes($source, $destination)
        {
            if ($source === $destination) {
                return error('cannot clone, source and destination same');
            }
            $this->remove_virtual_transport($destination);
            if (!$this->add_virtual_transport($destination)) {
                return false;
            }

            foreach ($this->list_mailboxes(null, null, $source) as $mailbox) {
                if ($mailbox['type'] == self::MAILBOX_USER) {
                    if (preg_match('!^/home/([^/]+)/' . self::MAILDIR_HOME . '/?(.*)$!', $mailbox['destination'],
                        $mailbox_dest)) {
                        $username = $mailbox_dest[1];
                        $subfolder = $mailbox_dest[2];
                    } else {
                        $subfolder = '';
                        $username = $mailbox['destination'];
                    }

                    $this->add_mailbox($mailbox['user'],
                        $destination,
                        $this->user_get_uid_from_username($username),
                        $subfolder);
                } else if ($mailbox['type'] == self::MAILBOX_FORWARD) {
                    $this->add_alias($mailbox['user'],
                        $destination,
                        str_replace($source,
                            $destination,
                            $mailbox['destination']));
                }

                if (!$mailbox['enabled']) {
                    $this->disable_address($mailbox['user'], $mailbox['domain']);
                }

            }

            return true;
        }

        /**
         * Deauthorize server from handling mail for domain
         *
         * @param string $domain  domain name to deauthorize
         * @param bool   $keepdns purge DNS MX settings, null auto-detect to purge
         * @return bool|int
         */
        public function remove_virtual_transport($domain, $keepdns = null)
        {
            $pgdb = \PostgreSQL::initialize();
            $q = $pgdb->query("SELECT site_id FROM domain_lookup WHERE domain = '" . pg_escape_string($domain) . "'");
            if ($q->num_rows() < 1) {
                return false;
            }

            $site_id = $pgdb->fetch_object()->site_id;

            if ($site_id && $site_id != $this->site_id) {
                return error('Table entry ' . $domain . ' owned by another site (' . $site_id . ')');
            } else if ($pgdb->num_rows() < 1) {
                return error('Domain ' . $domain . ' not found in table');
            }
            if ($this->majordomo_enabled()) {
                foreach ($this->majordomo_list_mailing_lists() as $list) {
                    $tmp = $this->majordomo_get_domain_from_list_name($list);
                    if ($tmp == $domain) {
                        warn("Mailing list `%s' sends from `%s'. Delete via Mail > Mailing Lists", $list, $domain);
                    }
                }
            }
            $pgdb->query("DELETE FROM domain_lookup WHERE domain = '" . pg_escape_string($domain) . "' AND site_id = " . (int)$this->site_id . ';');
            $ok = $pgdb->affected_rows() > 0;

            if (!$this->dns_configured()) {
                return warn("DNS is not configured for `%s' - unable to remove MX records automatically", $domain);
            }

            if (!$this->dns_zone_exists($domain)) {
                // zone removed
                return true;
            }

            if ($keepdns) {
                return $ok;
            }

            $split = $this->web_split_host($domain);
            $mailrecords = $this->provisioning_records($split['domain'], $split['subdomain']);
            if (null === $keepdns) {
                // do an intelligent lookup to see if MX is default
                $hostname = ltrim($split['subdomain'] . '.' . $split['domain'], '.');
                $rec = $this->dns_get_records($split['subdomain'], 'MX', $split['domain']);
                // record exists, confirm MX value
                if (!is_array($rec)) {
                    warn("error retrieving mx records for `%s'", $hostname);
                    Error_Reporter::report("unable to remove record for `%s'", $hostname);
                    return $ok;
                }
                if (!count($rec)) {
                    // MX record exists remotely but not on the server
                    info("no MX records found for hostname `%s'", $hostname);
                    return $ok;
                }

                // check last record
                $rec = array_pop($rec);

                // determine if MX record is unchanged from stock records
                // @XXX this algorithm is terrible
                $match = new Record($hostname, [
                    'name' => $rec['subdomain'],
                    'rr' => 'MX',
                    'parameter' => $rec['parameter'],
                ]);
                $match2 = $match;

                foreach ($mailrecords as $r) {
                    if (!$r->is($match)) {
                        continue;
                    }
                    [$priority, $target] = preg_split('/\s+/', $match['parameter'], 2, PREG_SPLIT_NO_EMPTY);
                    foreach ($mailrecords as $r2) {
                        if ($r2->matches('hostname', $target)) {
                            $match2 = $r2;
                            break;
                        }
                    }

                    break;
                }

                $keepdns = $match2 === $match;

                if ($keepdns) {
                    warn("MX record for `%s' points to third-party server and thus will not be removed from local DNS",
                        $domain);
                    return -1;
                }
            }

            foreach ($mailrecords as $r) {
                if ($this->dns_record_exists($r->getZone(), $r['name'], $r['rr'], $r['parameter'])) {
                    if (!$this->dns_remove_record($r->getZone(), $r['name'], $r['rr'], $r['parameter'])) {
                        warn(
                            'Failed to remove record %s.%s (%s) => %s',
                            $r['name'],
                            $r->getZone(),
                            $r['rr'],
                            $r['parameter']
                        );
                    }
                }
            }

            return $ok;
        }

        /**
         * Get DNS records
         *
         * @deprecated use provisioning_records()
         *
         * @param string $domain
         * @param string $subdomain
         * @return array
         */
        public function get_records(string $domain, string $subdomain = ''): array
        {
            deprecated_func('use provisioning_records()');
            return $this->provisioning_records($domain, $subdomain);
        }

        /**
         * Get DNS records
         *
         * @param string $domain
         * @param string $subdomain
         * @return Record[]
         */
        public function provisioning_records(string $domain, string $subdomain = ''): array
        {
            if (!$this->enabled() || ($this->getServiceValue('mail', 'provider') === 'builtin' &&
                !$this->transport_exists(ltrim("$subdomain.$domain", '.'))))
            {
                // dns calls email_provisioning_records, email depends upon dns - without
                // a callback there's no way to know for sure if a domain is authoritative
                // for mail; transport_exists() doesn't work at this stage
                return [];
            }

            $ttl = $this->dns_get_default('ttl');
            $myips = $this->get_mail_ip();
            $template = BladeLite::factory('templates/dns')->render('email', [
                'svc'        => \Opcenter\SiteConfiguration::shallow($this->getAuthContext()),
                'ttl'        => $ttl,
                'zone'       => $domain,
                'subdomain'  => $subdomain,
                'hostname'  => ltrim(implode('.', [$subdomain, $domain]), '.'),
                'ips'        => (array)$myips
            ]);
            $regex = Regex::compile(Regex::DNS_AXFR_REC_DOMAIN, [
                'rr' => implode('|', $this->dns_permitted_records() + [99999 => 'SOA']),
                'domain' => $domain
            ]);
            if (!preg_match_all($regex, $template, $matches, PREG_SET_ORDER)) {
                debug('No provisioning records discovered from template');
                return [];
            }
            $records = [];
            foreach ($matches as $record) {
                $records[] = new Record($domain, [
                    'ttl'       => $record['ttl'],
                    'parameter' => $record['parameter'],
                    'rr'        => $record['rr'],
                    'name'      => rtrim($record['subdomain'], '.')
                ]);
            }
            return $records;
        }

        /**
         * Add transport to handle mail
         * @param string $domain    primary domain
         * @param string $subdomain optional subdomain
         * @return bool|void
         * @throws PostgreSQLError
         */
        public function add_virtual_transport($domain, $subdomain = '')
        {
            $aliases = $this->aliases_list_aliases();
            if (($domain !== $this->domain) && !in_array($domain, $aliases, true)) {
                return error("domain `%s' not owned by site", $domain);
            }
            $transport = ($subdomain ? $subdomain . '.' : '') . $domain;
            $pgdb = \PostgreSQL::initialize();
            $rs = $pgdb->query("SELECT site_id FROM domain_lookup WHERE domain = '" . pg_escape_string($transport) . "'");
            $nr = $pgdb->num_rows();

            if ($nr > 0) {
                $site = (int)$rs->fetch_object()->site_id;
                if ($site !== $this->site_id) {
                    return error("table entry `%(transport)s' owned by another site (%(id)d)",
                        ['transport' => $transport, 'id' => $site]);
                }

                return true;
            }
            $pgdb->query("INSERT INTO domain_lookup (domain, site_id) VALUES('" . pg_escape_string($transport) . "', " . (int)$this->site_id . ');');
            if ($pgdb->affected_rows() < 1) {
                return error("failed to add e-mail transport `%s'", $transport);
            }

            if (!$this->dns_domain_uses_nameservers($domain)) {
                $nsrecs = join(', ', $this->dns_get_hosting_nameservers($domain));
                warn('Domain %(domain)s uses third-party nameservers to provide DNS. Continuing to make ' .
                    'local MX records on local nameservers. Email configuration in Mail > Manage Mailboxes ' .
                    'will not be reflected until nameservers are changed to %(nsrecs)s',
                    ['domain' => $domain, 'nsrecs' => $nsrecs]
                );
            }

            /**
             * forcefully set the record just in case, if external DNS is used or
             * if MX destination record is already present, elicit a warning
             */
            if (!$this->dns_configured() || !$this->dns_zone_exists($domain)) {
                return warn("DNS is not configured for `%s' - unable to provision DNS automatically", $domain);
            }
            $mailrecords = $this->provisioning_records($domain, $subdomain);
            $srvrec = $this->dns_get_records($subdomain, 'MX', $domain);

            if ($srvrec) {
                // MX exists, examine for completeness
                $srvrec = array_pop($srvrec);

                $match = new Record($domain, [
                    'name'      => $srvrec['subdomain'],
                    'rr'        => 'MX',
                    'parameter' => $srvrec['parameter'],
                ]);
                $match2 = $match;

                foreach ($mailrecords as $r) {
                    if (!$r->is($match)) {
                        continue;
                    }

                    [$priority, $target] = preg_split('/\s+/', $match['parameter'], 2, PREG_SPLIT_NO_EMPTY);
                    foreach ($mailrecords as $r2) {
                        if ($r2->matches('hostname', $target)) {
                            $match2 = $r2;
                            break;
                        }
                    }

                    break;
                }
                // wasn't updated
                $hasCustomRecords = $match2 === $match;

                if ($hasCustomRecords) {
                    $hostname = trim(implode('.', [$match['name'], $match['zone']]), '.');
                    return warn('MX record for %s points to %s, not overwriting! Email will not ' .
                        'route properly until MX records are reset via Toolbox in DNS Manager.',
                        $hostname,
                        $srvrec['parameter']
                    );
                }
                // make sure records are present
            }

            foreach ($mailrecords as $r) {
                if (!$this->dns_record_exists($r->getZone(), $r['name'], $r['rr'], $r['parameter'])) {
                    $this->dns_add_record($r->getZone(), $r['name'], $r['rr'], $r['parameter']);
                }
            }

            return true;
        }

        /**
         * Add mailbox for account
         *
         * @param        $user
         * @param        $domain
         * @param        $uid
         * @param string $mailbox
         * @return bool|void
         * @throws PostgreSQLError
         */
        public function add_mailbox($user, $domain, $uid, $mailbox = '')
        {
            $user = strtolower(trim($user));
            $domain = strtolower(trim($domain));
            if ($this->address_exists($user, $domain)) {
                if (!$user) {
                    return error("catch-all for $domain already exists");
                }

                return error('%s@%s: address exists', $user, $domain);
            }

            if ($user && !preg_match(Regex::EMAIL, "${user}@${domain}")) {
                return error("Invalid email `%s'", "${user}@${domain}");
            }

            if (!$this->transport_exists($domain)) {
                return error("Mail transport `%s' not bound to account", $domain);
            }
            $mailbox = ltrim(str_replace(array('/', '..'), '.', $mailbox), '.');
            $uid = (int)$uid;
            $pgdb = \PostgreSQL::initialize();
            if ($mailbox) {
                $pgdb->query('SELECT "user" as name FROM uids WHERE uid = ' . $uid . ' AND site_id = ' . $this->site_id);
                $luser = $pgdb->fetch_object();
                if (!$luser) {
                    return error("lookup failed for `%s' with uid `%s'", $user, $uid);
                }
                $luser = trim($luser->name);
                $this->query('email_create_maildir_backend', $luser, $mailbox);
                $mailbox = pg_escape_string($mailbox);
            }

            $pgdb->query("INSERT INTO email_lookup (\"user\", domain, uid, type, enabled, fs_destination)
                VALUES ('" . pg_escape_string($user) . "',
                    '" . pg_escape_string($domain) . "',
                    " . intval($uid) . ",
                    '" . self::MAILBOX_USER . "',
                    1::bit,
                    " . ($mailbox ? "'" . $mailbox . "'" : 'NULL') . ');');
            $rows = $pgdb->affected_rows();

            $this->_shutdown_save_mailboxes();

            return $rows > 0 ?: error('Failed to create mailbox: %s', $pgdb->error);

        }

        public function add_alias($user, $domain, $destination)
        {
            $user = strtolower($user);
            $domain = strtolower($domain);
            if ($this->address_exists($user, $domain)) {
                return error('%s@%s: address exists', $user, $domain);
            }

            if ($conflicts = $this->checkForwarding($destination)) {
                return error('Remote forwarding is disabled. Following addresses would violate forwarding policy: %s',
                    implode(',', $conflicts)
                );
            }

            if (!$this->transport_exists($domain)) {
                return error("Mail transport `%s' not bound to account", $domain);
            }
            $user = trim($user);
            if (!$user && !MAIL_FORWARDED_CATCHALL) {
                return error('catch-all may not be forwarded');
            }
            $destination = preg_replace('/\s+|,+/', ',', trim($destination, ' ,'));
            if (!$destination) {
                return error('no destination specified');
            }
            $pgdb = \PostgreSQL::initialize();
            $pgdb->query('INSERT INTO email_lookup ' .
                '("user", domain, alias_destination, type, enabled) ' .
                "VALUES('" . pg_escape_string($user) . "', '" . pg_escape_string($domain) . "', '" .
                trim(pg_escape_string($destination), ',') . "', '" . self::MAILBOX_FORWARD . "', 1::bit);");
            $rows = $pgdb->affected_rows();
            $this->_shutdown_save_mailboxes();

            return $rows > 0;
        }

        public function disable_address($account, $domain = null)
        {
            $where = 'AND email_lookup.domain = domain_lookup.domain AND domain_lookup.site_id = ' . $this->site_id;
            if ($domain) {
                $where .= 'AND domain_lookup.domain = \'' . pg_escape_string($domain) . '\'';
            }
            $pgdb = \PostgreSQL::initialize();
            $pgdb->query('UPDATE email_lookup SET enabled = 0::bit FROM domain_lookup WHERE "user" = \'' . pg_escape_string($account) . '\' ' . $where . ';');

            return $pgdb->affected_rows() > 0;
        }

        /**
         * Get mail server IPs
         *
         * @return array
         */
        public function get_mail_ip(): array
        {
            $ips = [];
            if ($tmp = $this->dns_get_public_ip()) {
                $ips = (array)$tmp;
            }
            if ($tmp = $this->dns_get_public_ip6()) {
                $ips = array_merge($ips, (array)$tmp);
            }

            return $ips;
        }

        public function set_webmail_location($app, $subdomain)
        {
            if (!IS_CLI) {
                return $this->query('email_set_webmail_location', $app, $subdomain);
            }

            $webmailInstance = Webmail::instantiateContexted($this->getAuthContext());
            if (!$webmailInstance->exists($app)) {
                return error("unknown webmail app `%s'", $app);
            }

            $subdomain = strtolower($subdomain);
            $locations = $this->webmail_apps();
            $oldsubdomain = $locations[$app];
            if ($oldsubdomain === $subdomain) {
                return true;
            }
            if (!preg_match(Regex::SUBDOMAIN, $subdomain)) {
                return error("invalid subdomain `%s'", $subdomain);
            }

            if ($this->web_subdomain_exists($subdomain)) {
                return error("subdomain `%s' already exists - cannot overwrite", $subdomain);
            }

            // system-default webmail locations won't appear in subdomain_exists() query
            if ($this->web_subdomain_exists($oldsubdomain) && !$this->web_remove_subdomain($oldsubdomain)) {
                warn("cannot remove old webmail location `%s'", $oldsubdomain);
            }
            if (!$webmailInstance->set($app, $subdomain)) {
                return false;
            }

            $fspath = $webmailInstance->getPathFromApp($app);
            if (!$this->web_add_subdomain($subdomain, $fspath)) {
                error("Failed to map webmail `%s' to `%s'", $app, $fspath);
                $webmailInstance->forget($app);
            }

            $cache = Cache_Account::spawn($this->getAuthContext());
            $cache->delete(Webmail::CACHE_KEY);

            return info("webmail location changed from `%s.%s' to `%s.%s'",
                    $oldsubdomain, $this->domain, $subdomain, $this->domain);
        }

        public function webmail_apps()
        {
            if (!IS_CLI) {
                $cache = Cache_Account::spawn($this->getAuthContext());
                if (false !== ($webmail = $cache->get(Webmail::CACHE_KEY))) {
                    return $webmail;
                }
                $apps = $this->query('email_webmail_apps');
                $cache->set(Webmail::CACHE_KEY, $apps);

                return $apps;
            }
            return Webmail::instantiateContexted($this->getAuthContext())->getAll();
        }

        public function get_webmail_location($app)
        {
            $cache = Cache_Account::spawn($this->getAuthContext());
            if (false !== ($webmail = $cache->get(Webmail::CACHE_KEY))) {
                return $webmail[$app];
            }
            $webmail = $this->query('email_webmail_apps');
            if (!isset($webmail[$app])) {
                return error("unknown webmail app `%s'", $app);
            }

            return $webmail[$app];
        }

        public function _create()
        {
            // populate spam folders
            $conf = $this->getAuthContext()->getAccount()->cur;
            $user = $conf['siteinfo']['admin_user'];
            // stupid thor...
            $svcs = array('smtp_relay', 'imap', 'pop3');
            $pam = new Util_Pam($this->getAuthContext());
            foreach ($svcs as $svc) {
                if ($this->auth_is_demo() && $pam->check($user, $svc)) {
                    $pam->remove($user, $svc);
                }
            }
            if (platform_is('7.5', '<')) {
                return true;
            }
            if (!$this->_create_user($user)) {
                return false;
            }
            if (!$this->transport_exists($this->domain)) {
                $this->add_virtual_transport($this->domain);
            }
            $this->add_mailbox('postmaster', $this->domain, $this->user_id);
            $this->add_mailbox($this->username, $this->domain, $this->user_id);
        }

        public function _create_user(string $user)
        {
            // flush Dovecot auth cache to acknowledge pwdb changes
            $this->_reload('adduser');
            if (!$pwd = $this->user_getpwnam($user)) {
                return false;
            }
            // older platforms do this implicitly
            // @TODO when surrogate user drops hook, drop this
            if (!Opcenter\Provisioning\Mail::createUser($this->site_id, $pwd['uid'], $user)) {
                return error("failed to create mail lookup for `%s' on `site%d'", $user, $this->site_id);
            }
            if (!$pwd['home']) {
                return false;
            }

            // use imap as a marker for email creation
            $svc = 'imap';

            $path = $this->domain_fs_path() . DIRECTORY_SEPARATOR . $pwd['home'] .
                DIRECTORY_SEPARATOR . self::MAILDIR_HOME;
            if (!is_dir($path)) {
                Opcenter\Filesystem::mkdir($path, $pwd['uid'], $this->group_id, 0700, false);
                Storage::bindTo($this->domain_fs_path())->createMaildir($this->file_unmake_path($path),
                    $pwd['uid'], $pwd['gid']);
                file_put_contents($path . '/subscriptions', 'INBOX', FILE_APPEND);
            }


            foreach (['Spam', 'Trash', 'Sent'] as $folder) {
                $dir = $path . DIRECTORY_SEPARATOR . ".${folder}";
                if (!is_dir($dir)) {
                    $this->create_maildir_backend($user, $folder);
                }

            }

            return true;
        }

        public function _reload($why = null)
        {

            if ($why === Ssl_Module::USER_RHOOK || $why === Ssl_Module::SYS_RHOOK) {
                if (Haproxy::exists()) {
                    // ignore reloads triggered by admin
                    if ($this->site) {
                        $this->merge_ssl($this->site);
                    }
                    Haproxy::restart(HTTPD_RELOAD_DELAY);
                }
                // update ssl certs
                if (Dovecot::exists()) {
                    Dovecot::restart(HTTPD_RELOAD_DELAY);
                }
                Postfix::restart(HTTPD_RELOAD_DELAY);
                return true;
            }

            if ($why === 'adduser') {
                // just flush auth cache
                if (!Dovecot::exists()) {
                    return warn(
                        "Dovecot appears to not be installed. Mail provider other than 'null' selected. Switch " .
                        "provider module to `null' from `%s' to avoid unexpected side-effects.", $this->get_provider()
                    );
                }
                return Dovecot::flushAuth();
            }

            return true;
        }

        /**
         * Create Maildir backend
         *
         * @param $user
         * @param $mailbox
         * @return bool|void
         */
        public function create_maildir_backend($user, $mailbox)
        {
            $mailbox = '.' . ltrim($mailbox, '.');
            if (!preg_match(Regex::EMAIL_MAILDIR_FOLDER, $mailbox)) {
                return error("invalid maildir folder name `%s'", $mailbox);
            }

            $pwd = $this->user_getpwnam($user);
            if (!$pwd) {
                return error("failed to create Maildir storage, user `%s' does not exist", $user);
            }

            $path = $pwd['home'] . DIRECTORY_SEPARATOR .
                static::MAILDIR_HOME . DIRECTORY_SEPARATOR . Storage::mailbox2Maildir($mailbox);
            $chkvpath = dirname($path);
            $chkrpath = $this->domain_fs_path($chkvpath);
            if (!is_dir($chkrpath)) {
                return error("mail home `%s' does not exist", $chkvpath);
            }

            return Storage::bindTo($this->domain_fs_path())->createMaildir($path, $pwd['uid'],
                $pwd['gid']);
        }

        public function create_maildir($mailbox)
        {
            if (!IS_CLI) {
                return $this->query('email_create_maildir', $mailbox);
            }

            return $this->create_maildir_backend($this->username, $mailbox);
        }

        public function _delete()
        {
            // remove HAproxy is present
            $pemfile = static::SSL_PROXY_DIR . '/' . $this->site . '.pem';
            if (file_exists($pemfile)) {
                unlink($pemfile);
            }
            $conf = $this->getAuthContext()->getAccount()->cur;
            $ips = $conf['ipinfo']['ipaddrs'] + append_config($conf['ipinfo6']['ipaddrs']);
            if (!$ips) {
                return true;
            }
            foreach ($ips as $ip) {
                $this->_removeMTA($ip);
            }
            $this->_removeIMAP($this->site);


        }

        private function _removeMTA($ip)
        {
            $hosts = file(Dns_Module::HOSTS_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            $regex = Regex::compile(
                Regex::EMAIL_MTA_IP_RECORD,
                array(
                    'ip' => preg_quote($ip, '/')
                )
            );

            $new = array();
            $found = false;
            foreach ($hosts as $host) {
                if (preg_match($regex, $host)) {
                    $found = true;
                    continue;
                }
                $new[] = $host;
            }
            $new[] = '';
            if (!$found) {
                return -1;
            }

            /**
             * it's here for future consideration, but likely unnecessary
             * $proc = new Util_Process_Schedule("1 minute");
             * $proc->run(self::POSTFIX_CMD . ' reload');
             */
            return file_put_contents(Dns_Module::HOSTS_FILE, join(PHP_EOL, $new), LOCK_EX) !== false;
        }

        /**
         * Remove site configuration
         *
         * @param $site
         */
        private function _removeIMAP($site)
        {
            $path = self::SSL_PROXY_DIR . '/' . $site;
            $extensions = array('conf', 'crt', 'key', 'pem');
            foreach ($extensions as $ext) {
                $file = $path . '.' . $ext;
                if (file_exists($file)) {
                    unlink($file);
                }
            }
        }

        public function _edit()
        {
            $conf_new = $this->getAuthContext()->getAccount()->new;
            $conf_old = $this->getAuthContext()->getAccount()->old;
            $user = array(
                'old' => $conf_old['siteinfo']['admin_user'],
                'new' => $conf_new['siteinfo']['admin_user']
            );

            /**
             * update alias mapping, mailbox mappings update on the backend
             *
             * @TODO phase out legacy backend
             */
            if ($user['old'] !== $user['new']) {
                // @XXX bug: _edit is called after EVD completes
                // old pwd is lost, but send anyway to placate _edit_user
                $this->_edit_user(
                    $user['old'],
                    $user['new'],
                    $this->user_getpwnam($user['new'])
                );
            }

            // Aliases can be edited in 2 manners: Nexus/EditDomain or aliases:remove-domain
            // It's impractical to move this logic into ServiceValidators\Aliases\Aliases as it couples validation
            // with an unrelated service class. Handle email detachment here so that surrogates/provider modules
            // may override behavior
            $aliases = [
                'old' => array_merge($conf_old['aliases']['aliases'], (array)$conf_old['siteinfo']['domain']),
                'new' => array_merge($conf_new['aliases']['aliases'], (array)$conf_new['siteinfo']['domain'])
            ];
            $toremove = array_diff($aliases['old'], $aliases['new']);

            foreach ($toremove as $domain) {
                if ($this->transport_exists($domain)) {
                    $this->remove_virtual_transport($domain);
                }
            }

            /**
             * Update private smtp routing + whitelabel dovecot config
             */
            $ipcur = $conf_old['ipinfo'];
            $ipnew = $conf_new['ipinfo'];

            if ($ipnew === $ipcur) {
                return true;
            }
            // ip either added or removed
            if (!$ipcur['namebased'] && $ipnew['namebased']) {
                foreach ($ipcur['ipaddrs'] as $ip) {
                    $this->_removeMTA($ip);
                    $this->_removeIMAP($this->site);
                }
            } else if ($ipcur['namebased'] && !$ipnew['namebased']) {
                foreach ($ipnew['ipaddrs'] as $ip) {
                    $this->_addMTA($ip);
                }
            } else if ($ipcur['ipaddrs'] != $ipnew['ipaddrs']) {
                $remove = array_diff($ipcur['ipaddrs'], $ipnew['ipaddrs']);
                $add = array_diff($ipnew['ipaddrs'], $ipcur['ipaddrs']);
                foreach ($remove as $ip) {
                    $this->_removeMTA($ip);
                }
                foreach ($add as $ip) {
                    $this->_addMTA($ip);
                }
                // @TODO update Dovecot config
            }
            return true;
        }

        public function _edit_user(string $userold, string $usernew, array $oldpwd)
        {
            // Dovecot is a finnicky bastard
            $this->_reload('adduser');
            if ($userold === $usernew) {
                return;
            }
            // edit_user hooks enumerated after user changed
            $uid = $this->user_get_uid_from_username($usernew);
            if (!$uid) {
                return error("cannot determine uid from user `%s' in mailbox translation", $userold);
            }
            $pam = new Util_Pam($this->getAuthContext());
            mute_warn();
            foreach ($this->_pam_services() as $svc) {
                if ($this->user_enabled($userold, $svc)) {
                    $pam->remove($userold, $svc);
                    // edit_user hook renames user then calls
                    $pam->add($usernew, $svc);
                }
            }
            unmute_warn();
            // update uids in uids table
            $db = \PostgreSQL::initialize();
            $query = \Opcenter\Database\PostgreSQL::vendor('mail')->renameUser($userold, $usernew, $uid);
            $db->query($query);
            // make 2 sweeps:
            // sweep 1: update mailboxes that refer to the uid
            // sweep 2: update aliases that forward to the user
            // aliases that deliver locally
            $mailboxes = $this->list_mailboxes('local', $userold);
            foreach ($mailboxes as $mailbox) {
                if ($mailbox['type'] === self::MAILBOX_USER) {
                    $target = '/home/' . $mailbox['mailbox'] . '/' .
                        self::MAILDIR_HOME . '/' . $mailbox['custom'];
                } else {
                    $target = $mailbox['mailbox'];
                }
                $this->modify_mailbox($mailbox['user'],
                    $mailbox['domain'],
                    $usernew,
                    $mailbox['domain'],
                    $target,
                    $mailbox['type']
                );
            }
            // sweep 2
            $this->_update_email_aliases($userold, $usernew);

            return true;
        }

        private function _pam_services()
        {
            return ['smtp', 'imap', 'pop3'];
        }

        /**
         * Mail service is enabled for user
         *
         * @param null $user
         * @param null $svc
         * @return bool|void
         */
        public function user_enabled($user = null, $svc = null)
        {
            if (!$user || ($this->permission_level & PRIVILEGE_USER)) {
                $user = $this->username;
            }
            if ($svc && $svc != 'imap' && $svc != 'smtp' && $svc != 'smtp_relay' && $svc !== 'pop3') {
                return error("unknown service `%s'", $svc);
            }
            if (!$this->enabled($svc)) {
                return false;
            }
            $enabled = 1;
            if (!$svc) {
                $enabled = (new Util_Pam($this->getAuthContext()))->check($user, 'imap');
                $svc = 'smtp_relay';
            } else if ($svc == 'smtp') {
                $svc = 'smtp_relay';
            }

            return $enabled && (new Util_Pam($this->getAuthContext()))->check($user, $svc);
        }

        /**
         * Verify service is enabled
         *
         * @param null|string $which
         * @return bool
         */
        public function enabled(string $which = null): bool
        {
            // @TODO rename sendmail to smtp service
            if (platform_is('7.5')) {
                $which = $which === 'smtp_relay' ? 'smtp' : $which;
            } else {
                $which = $which === 'smtp' ? 'smtp_relay' : $which;
            }
            if ($which && $which !== 'smtp' && $which !== 'smtp_relay' && $which !== 'imap' && $which !== 'pop3') {
                return error("unknown service `%s'", $which);
            }
            if ($which) {
                $which = platform_is('7.5') ? 'mail' : 'sendmail';

                return (bool)$this->getServiceValue($which, 'enabled');
            }

            return $this->enabled('smtp') && $this->enabled('imap');
        }

        /**
         * Merge issued certificates into haproxy's SNI
         *
         * @param string|array|null one or more sites to cherry-pick SSL from
         * @return bool
         */
        public function merge_ssl($site = null) {
            if (!IS_CLI) {
                return $this->query('email_merge_ssl', $site);
            }

            if (!MAIL_PROXY) {
                return warn('No mail proxy installed');
            }
            if (!$site) {
                $site = Enumerate::sites();
            }
            try {
                $sites = array_map(static function ($s) {
                    if (!($site = Auth::get_site_id_from_anything($s))) {
                        throw new \Exception("Unknown site `${s}'");
                    }
                    return 'site' . $site;
                }, (array)$site);
            } catch (\Exception $e) {
                return error($e->getMessage());
            }

            $status = true;
            foreach ($sites as $site) {
                $context = Auth::context(null, $site);
                $afi = apnscpFunctionInterceptor::factory($context);
                if (!$afi->ssl_key_exists()) {
                    continue;
                }
                if (!($ssl = $afi->ssl_get_certificates())) {
                    continue;
                }
                $fst = $context->domain_fs_path();
                if ( !($pem = Ssl::unify($ssl[0], $fst)) ) {
                    $status &= error('Failed to unify SSL data into pem: %s', $site);
                    continue;
                }
                $pemfile = static::SSL_PROXY_DIR . "/${site}.pem";
                if (!file_put_contents($pemfile, $pem)) {
                    file_exists($pemfile) && unlink($pemfile);
                    $status &= error("Failed to populate SSL for `%s'", $site);
                }
            }
            call_user_func([\Opcenter\Mail::serviceClass(MAIL_PROXY), 'reload']);

            return $status;

        }

        /**
         * Update forwarded e-mail dependencies on user change
         *
         * @param $user
         * @param $usernew
         * @return int number mailboxes changed, -1 if update fails
         */
        private function _update_email_aliases($user, $usernew)
        {
            $prepfunc = static function ($domain) use ($user) {
                return '\b' . preg_quote($user, '/') . '@(' . preg_quote($domain, '/') . ')\b';
            };

            $regexcb = static function ($matches) use ($usernew) {
                return $usernew . '@' . $matches[1];
            };

            $domains = $this->list_virtual_transports();
            $regex = '/' . join('|', array_map($prepfunc, $domains)) . '/S';

            $forwards = $this->list_mailboxes(self::MAILBOX_FORWARD);
            $changed = 0;
            foreach ($forwards as $forward) {
                $cnt = 0;
                $new = preg_replace_callback($regex, $regexcb, $forward['destination'], -1, $cnt);
                if ($cnt < 1) {
                    continue;
                }
                if ($this->modify_mailbox(
                    $forward['user'],
                    $forward['domain'],
                    $forward['user'],
                    $forward['domain'],
                    $new,
                    $forward['type']
                )
                ) {
                    if ($changed > -1) {
                        $changed++;
                    }
                } else {
                    warn('failed to adjust mailbox `%s@%s`', $forward['user'], $forward['domain']);
                    $changed = -1;
                }

            }

            return $changed;
        }

        public function list_virtual_transports()
        {
            $virtual = array();
            $res = \PostgreSQL::initialize()->query('SELECT domain FROM domain_lookup WHERE site_id = ' . $this->site_id);
            while (null !== ($row = $res->fetch_object())) {
                $virtual[] = trim($row->domain);
            }

            return $virtual;
        }

        private function _addMTA($ip)
        {
            $hosts = file(Dns_Module::HOSTS_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            $regex = Regex::compile(
                Regex::EMAIL_MTA_IP_RECORD,
                array(
                    'ip' => preg_quote($ip, '/')
                )
            );
            foreach ($hosts as $host) {
                if (preg_match($regex, $host)) {
                    return -1;
                }
            }

            $hosts[] = $ip . ' internal-multihome';
            $hosts[] = '';

            return file_put_contents(Dns_Module::HOSTS_FILE, join(PHP_EOL, $hosts), LOCK_EX) !== false;
        }

        public function _delete_user(string $user)
        {
            $pwd = $this->user_getpwnam($user);
            foreach ($this->list_mailboxes(self::MAILBOX_DESTINATION, $user) as $mailbox) {
                $this->delete_mailbox($mailbox['user'], $mailbox['domain']);
            }
            \Opcenter\Provisioning\Mail::deleteUser($this->site_id, $pwd['uid']);
        }

        public function permit_user($user, $svc = null)
        {
            if ($svc && $svc != 'smtp' && $svc != 'imap' && $svc != 'smtp_relay' && $svc !== 'pop3') {
                return error('service ' . $svc . ' is unknown (imap, smtp, pop3)');
            }

            if ($this->auth_is_demo()) {
                return error('Email disabled for demo account');
            }

            $pam = new Util_Pam($this->getAuthContext());
            if (!$svc) {
                $pam->add($user, 'imap');
                $svc = 'smtp_relay';
            } else if ($svc == 'smtp') {
                $svc = 'smtp_relay';
            } else if (platform_is('7.5')) {
                //
                $mirror = $svc === 'imap' ? 'pop3' : 'imap';
                $pam->add($user, $mirror);
            }

            return $pam->add($user, $svc);
        }

        public function deny_user($user, $svc = null)
        {
            if ($svc && $svc != 'smtp' && $svc != 'imap' && $svc != 'smtp_relay' && $svc !== 'pop3') {
                return error('service ' . $svc . ' not in list');
            }
            $pam = new Util_Pam($this->getAuthContext());
            if (!$svc) {
                $pam->remove($user, 'smtp');
                $svc = 'imap';
            } else if ($svc == 'smtp') {
                $svc = 'smtp_relay';
            }
            // v7.5 doesn't differentiate between IMAP/POP3 yet
            if ($svc === 'imap' && platform_is('7.5')) {
                $pam->remove($user, 'pop3');
            } else if ($svc === 'pop3' && platform_is('7.5')) {
                $pam->remove($user, 'imap');
            }

            return $pam->remove($user, $svc);
        }

        public function _verify_conf(ConfigurationContext $ctx): bool
        {
            return true;
        }

        public function _housekeeping()
        {
            $dummyfile = webapp_path('webmail/dummyset.php');
            $dest = '/var/www/html/dummyset.php';
            if (!file_exists($dest) || fileinode($dummyfile) !== fileinode($dest)) {
                file_exists($dest) && unlink($dest);
                $apnscpHome = realpath(INCLUDE_PATH);
                if (!Filesystem\Mount::sameMount('/var/www/html', $apnscpHome)) {
                    warn("/var and %s are on different mount points - copying dummyset", $apnscpHome);
                    copy($dummyfile, $dest);
                } else {
                    link($dummyfile, $dest);
                }
            }
            return true;
        }

        protected function buildWarningTemplates(): void
        {
            $path = '/usr/libexec/dovecot/quota-warning.sh';

            $template = new \Opcenter\Provisioning\ConfigurationWriter('mail.quota-warning-command', null);
            if (!$template->shouldRefresh($path)) {
                return;
            }

            $template->write($path) && Filesystem::chogp($path, 0, 0, 0755);
        }
    }