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

    use Module\Support\Dns;
    use Opcenter\Account\Ephemeral;
    use Opcenter\SiteConfiguration;

    /**
     * Provides DNS functions to apnscp.
     *
     * @package core
     */
    class Dns_Module extends Dns
    {
        use NamespaceUtilitiesTrait;

        const DEPENDENCY_MAP = [
            'siteinfo'
        ];
        /**
         * apex markers are marked with @
         */
        protected const HAS_ORIGIN_MARKER = false;
        /** primary nameserver */
        const MASTER_NAMESERVER = DNS_INTERNAL_MASTER;
        /**
         * @var array 1 or more authoritative nameservers
         */
        const AUTHORITATIVE_NAMESERVERS = DNS_AUTHORITATIVE_NS;
        /**
         * @var array 1 or more recursive nameservers
         */
        const RECURSIVE_NAMESERVERS = DNS_RECURSIVE_NS;
        const UUID_RECORD = DNS_UUID_NAME;

        // default DNS TTL for records modified via update()
        const DYNDNS_TTL = 300;

        // @var int minimum module TTL
        const DNS_TTL_MIN = 5;

        // @var int default DNS TTL
        const DNS_TTL = DNS_DEFAULT_TTL;

        const HOSTS_FILE = '/etc/hosts';
        // standard hosts file location

        /** @var array quick lookup */
        protected static $zoneExistsCache = [];
        /**
         * @var string TSIG key
         * @ignore
         */
        protected static $dns_key = DNS_TSIG_KEY;
        /** mapping of RR types to constants */
        protected static $rec_2_const = array(
            'ANY'   => DNS_ANY,
            'A'     => DNS_A,
            'AAAA'  => DNS_AAAA,
            'MX'    => DNS_MX,
            'NS'    => DNS_NS,
            'SOA'   => DNS_SOA,
            'TXT'   => DNS_TXT,
            'CNAME' => DNS_CNAME,
            'SRV'   => DNS_SRV,
            'PTR'   => DNS_PTR,
            'HINFO' => DNS_HINFO,
            'A6'    => DNS_A6,
            'NAPTR' => DNS_NAPTR,
            'CAA'   => DNS_CAA,
            'SSHFP' => 0,
            'SPF'   => 0,
            'URI'   => 0,
            'CERT'  => 0

        );
        /** array of 1 or more nameservers used */
        protected static $nameservers;

        /**
         * Legal DNS resource records permitted by provider
         * A
         * AAAA
         * MX
         * CNAME
         * DNAME
         * HINFO
         * TXT
         * NS
         * SRV
         *
         * @var array
         */
        protected static $permitted_records = array(
            'A',
            'AAAA',
            'A6',
            'CAA',
            'CNAME',
            'DNAME',
            'HINFO',
            'MX',
            'NAPTR',
            'NS',
            'SOA',
            'SRV',
            'TXT',
        );

        protected $exportedFunctions = [
            '*'                      => PRIVILEGE_SITE,
            'get_public_ip'          => PRIVILEGE_SITE | PRIVILEGE_USER,
            'get_public_ip6'         => PRIVILEGE_SITE | PRIVILEGE_USER,
            'configured'             => PRIVILEGE_ALL,
            'get_whois_record'       => PRIVILEGE_ALL,
            'get_records_by_rr'      => PRIVILEGE_SITE | PRIVILEGE_ADMIN,
            'get_records'            => PRIVILEGE_SITE | PRIVILEGE_ADMIN,
            'record_exists'          => PRIVILEGE_ALL,
            'modify_record'          => PRIVILEGE_SITE | PRIVILEGE_ADMIN,
            'remove_record'          => PRIVILEGE_SITE | PRIVILEGE_ADMIN,
            'add_record'             => PRIVILEGE_SITE | PRIVILEGE_ADMIN,
            'get_zone_information'   => PRIVILEGE_SITE | PRIVILEGE_ADMIN,
            'get_all_domains'        => PRIVILEGE_ADMIN,
            'get_parent_domain'      => PRIVILEGE_ADMIN,
            'get_server_from_domain' => PRIVILEGE_ADMIN,
            'release_ip'             => PRIVILEGE_ADMIN,
            'ip_allocated'           => PRIVILEGE_ADMIN,
            'gethostbyaddr_t'        => PRIVILEGE_ALL,
            'gethostbyname_t'        => PRIVILEGE_ALL,
            'get_provider'           => PRIVILEGE_ALL,
            'uuid'                   => PRIVILEGE_ALL,
            'provisioning_records'   => PRIVILEGE_SITE,
            'remove_zone'            => PRIVILEGE_ADMIN | PRIVILEGE_SITE | PRIVILEGE_SERVER_EXEC,
            'remove_zone_backend'    => PRIVILEGE_ADMIN | PRIVILEGE_SITE | PRIVILEGE_SERVER_EXEC,
            'add_zone'               => PRIVILEGE_ADMIN,
            'add_zone_backend'       => PRIVILEGE_ADMIN | PRIVILEGE_SITE | PRIVILEGE_SERVER_EXEC,
            'providers'              => PRIVILEGE_ADMIN,
            'zone_exists'            => PRIVILEGE_ADMIN | PRIVILEGE_SITE,
            'validate_template'      => PRIVILEGE_ADMIN,
            'import_from_domain'     => PRIVILEGE_ADMIN | PRIVILEGE_SITE,
            'export'                 => PRIVILEGE_ADMIN | PRIVILEGE_SITE,
            'import'                 => PRIVILEGE_ADMIN | PRIVILEGE_SITE,
            'auth_test'              => PRIVILEGE_SITE | PRIVILEGE_ADMIN
        ];

        /**
         * Provider loader
         *
         * @return Module_Skeleton
         */
        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\Dns::default();
            }

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

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

        /**
         * Get DNS provider
         *
         * @return string
         */
        public function get_provider(): string
        {
            if ($this->permission_level & (PRIVILEGE_SITE|PRIVILEGE_USER)) {
                if (!$this->enabled()) {
                    return 'null';
                }
                return $this->getServiceValue('dns', 'provider', DNS_PROVIDER_DEFAULT);
            }
            return \Opcenter\Dns::default();
        }

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

        /**
         * Get DNS UUID record name
         *
         * @return string
         */
        public function uuid_name(): string
        {
            return static::UUID_RECORD;
        }

        /**
         * Query database for domain expiration
         *
         * On multi-server lookups that perform DNS lookups independent,
         * perform batch lookups and pull those records from the database
         *
         *
         * A return of 0 indicates failure
         * null indicates unknown expiration
         *
         * @param string $domain domain owned by the account
         * @return null|int expiration as unix timestamp
         */
        public function domain_expiration(string $domain): ?int
        {
            return null;
        }

        /**
         * Fetches all domains across all servers
         *
         * Used in multi-server layouts
         *
         * @return array
         */
        public function get_all_domains(): array
        {
            return array_keys(\Opcenter\Map::load(\Opcenter\Map::DOMAIN_MAP)->fetchAll());
        }

        /**
         * Get server on which a domain is hosted
         *
         * @param string $domain
         * @param bool   $all show all server matches, $all = true: array of all servers, else server
         * @return string|array
         */
        public function get_server_from_domain(string $domain, bool $all = false)
        {
            return SERVER_NAME_SHORT;
        }

        /**
         * Get primary domain affiliated with account
         *
         * In multi-server setups query the master DB to find
         * domains whose invoice matches the parent invoice or domains
         * that share the same site ID
         *
         * @param string $domain
         * @return bool|string primary domain or false on error
         */
        public function get_parent_domain(string $domain)
        {
            if (false === ($id = \Opcenter\Map::load(\Opcenter\Map::DOMAIN_MAP)->fetch($domain))) {
                return false;
            }

            return \Auth::get_domain_from_site_id((int)substr($id, 4));
        }

        /**
         * Query WHOIS server for record
         *
         * @param  string $domain domain name to look up the whois record for
         * @return string|bool whois data
         *
         */
        public function get_whois_record(string $domain)
        {
            Error_Reporter::suppress_php_error('require_once');
            if (!preg_match(Regex::DOMAIN, $domain)) {
                return error('%s: invalid domain', $domain);
            }
            if (!class_exists('Net_Whois', false) &&
                !include 'Net/Whois.php'
            ) {
                return error('Unable to include Whois module');
            }

            $whois = new Net_Whois();
            $data = $whois->query($domain);
            if (PEAR::isError($data)) {
                return error("Failed to lookup whois data: `%s'", $data->message);
            }

            return $data;
        }

        /**
         * DNS zone exists
         *
         * @param string $zone
         * @return bool
         */
        public function zone_exists(string $zone): bool
        {
            if (!$this->configured()) {
                return false;
            }
            if (!$this->owned_zone($zone)) {
                return false;
            }
            if (!isset(self::$zoneExistsCache[$zone])) {
                self::$zoneExistsCache[$zone] = (null !== $this->zoneAxfr($zone));
            }

            return self::$zoneExistsCache[$zone];
        }

        /**
         * DNS handler is configured for account
         *
         * Weaker form of enabled()
         *
         * @return bool
         */
        public function configured(): bool
        {
            return static::class !== self::class;
        }

        /**
         * DNS is enabled for account
         *
         * Stricter version of configured().
         * Requires module to faithfully implement DNS functions.
         *
         * @return bool
         */
        public function enabled(): bool
        {
            return (bool)$this->getServiceValue('dns', 'enabled');
        }

        /**
         * Requested domain is manageable by the account
         *
         * @param  string $zone zone name
         * @return bool
         */
        protected function owned_zone(string $zone): bool
        {
            if ($this->getAuthContext()->level & PRIVILEGE_ADMIN) {
                return true;
            }

            if ($this->parented($zone)) {
                return true;
            }

            $aliases = $this->aliases_list_aliases();

            if ( ($zone === $this->domain) || in_array($zone, $aliases, true) ) {
                return true;
            }
            if ($zone === array_get((array)$this->getOldServices('siteinfo'), 'domain', null)) {
                return true;
            }
            return \in_array($zone, array_get((array)$this->getOldServices('aliases'), 'aliases', []), true);
        }

        /**
         * Perform a full zone transfer
         *
         * @param string $domain
         * @return null|string
         */
        protected function zoneAxfr($domain): ?string
        {
            if (!static::MASTER_NAMESERVER) {
                error("Cannot fetch zone information for `%s': no master nameserver configured in config.ini",
                    $domain);

                return null;
            }
            $data = Util_Process::exec('dig -t AXFR -y %s @%s %s',
                escapeshellarg($this->getTsigKey($domain)), static::MASTER_NAMESERVER, $domain, [-1, 0]);

            // AXFR can fail yet return a success RC
            if (false !== strpos($data['output'], '; Transfer failed.')) {
                return null;
            }

            return $data['success'] ? $data['output'] : null;
        }

        /**
         * Get AXFR key for domain
         *
         * @param string $domain
         * @return null|string
         */
        private function getTsigKey(string $domain): ?string
        {
            return static::$dns_key;
        }

        /**
         * Export zone configuration in BIND-friendly notation
         *
         * @param string|null $zone
         * @return bool|string
         */
        public function export(string $zone = null)
        {
            if (null === $zone) {
                $zone = $this->domain;
            }

            if (!$this->permission_level & PRIVILEGE_ADMIN && !$this->owned_zone($zone)) {
                return error("access denied - cannot view zone `%s'", $zone);
            }
            $recs = $this->get_zone_data($zone);
            if (null === $recs) {
                return error("failed to export zone `%s'", $zone);
            }
            $soa = $recs['SOA'][0];
            $soadata = preg_split('/\s+/', $soa['parameter']);
            $format = ';; ' . "\n" .
                ";; Domain:\t" . $zone . "\n" .
                ";; Exported:\t" . date('r') . "\n" .
                ';; ' . "\n" .
                '$ORIGIN . ' . "\n" .
                "@\t" . $soa['ttl'] . "\tIN\tSOA\t$zone.\t" . $soadata[1] . ' ( ' . "\n" .
                "\t" . $soadata[2] . "\t; serial" . "\n" .
                "\t" . $soadata[3] . "\t; refresh" . "\n" .
                "\t" . $soadata[4] . "\t; retry" . "\n" .
                "\t" . $soadata[5] . "\t; expire" . "\n" .
                "\t" . $soadata[6] . ")\t; minimum" . "\n\n";
            $buffer = array();
            $buffer[] = ';; NS Records (YOU MUST CHANGE THIS)';
            foreach ($recs['NS'] as $ns) {
                $ns['parameter'] = 'YOU_MUST_CHANGE_THIS_VALUE';
                $buffer[] = $ns['name'] . "\t" . $ns['ttl'] .
                    "\t" . "IN NS\t" . $ns['parameter'];
            }
            $buffer[] = '';
            $ignore = array('SOA', 'NS', 'TSIG');
            foreach (static::$permitted_records as $rr) {
                $rr = strtoupper($rr);
                if (!isset($recs[$rr]) || in_array($rr, $ignore, true)) {
                    continue;
                }
                $buffer[] = ';; ' . $rr . ' Records';
                foreach ($recs[$rr] as $r) {
                    $buffer[] = $r['name'] . "\t" . $r['ttl'] .
                        "\t" . 'IN ' . $rr . "\t" . $r['parameter'];
                }
                $buffer[] = "\n";
            }
            $format .= implode("\n", $buffer);

            return $format;
        }

        /**
         * Get all zone records parsed
         *
         * @param string $domain
         * @return array|null zone data or null if zone not present
         */
        protected function get_zone_data(string $domain): ?array
        {
            if (!$this->owned_zone($domain)) {
                error("Domain `%s' not owned by account", $domain);

                return null;
            }
            if (null === ($data = $this->zoneAxfr($domain))) {
                return $data;
            }

            $zoneData = array();
            $offset = strlen($domain) + 1; // domain.com.
            $regexp = \Regex::compile(\Regex::DNS_AXFR_REC,
                ['rr' => implode('|', static::$permitted_records + [99999 => 'SOA'])]);

            foreach (explode("\n", $data) as $line) {
                if (false !== strpos($line, 'Transfer failed.')) {
                    return null;
                }
                if (!preg_match($regexp, $line, $match)) {
                    continue;
                }
                [$name, $ttl, $class, $rr, $parameter] = array_slice($match, 1);
                $rr = strtoupper($rr);
                // TXT records should always be balanced with quotes
                // assume this to be the case if " present
                // don't pretty-print if more than 1 quote pair present
                if ($rr == 'TXT' && $parameter[0] == '"') {
                    $end = strlen($parameter) - 1;
                    if (strpos($parameter, '"', 1) === $end && strpos($parameter, '"', 1) === $end) {
                        // parameter formatted as "foobar"
                        // preserve TXT records formatted as '"foo" "bar" "baz"'
                        $parameter = substr($parameter, 1, -1);
                    }
                }
                $zoneData[$rr][] = array(
                    'name'      => $name,
                    'subdomain' => rtrim(substr($name, 0, strlen($name) - $offset), '.'),
                    'domain'    => $domain,
                    'class'     => $class,
                    'ttl'       => (int)$ttl,
                    'parameter' => $parameter
                );
            }

            return $zoneData;
        }

        /**
         * Get permitted records for DNS provider
         *
         * @return array
         */
        public function permitted_records(): array
        {
            return static::$permitted_records;
        }

        /**
         * Get DNS record(s) from a third-party nameserver
         *
         * When using same nameservers as hosting ns, ensure ns uses split-view
         *
         * @param  string $subdomain   optional subdomain
         * @param  string $rr          optional RR type
         * @param  string $domain      optional domain
         * @param  array  $nameservers optional nameserver to query
         * @return array|bool false on error
         */
        public function get_records_external(
            string $subdomain = '',
            string $rr = 'any',
            string $domain = null,
            array $nameservers = null
        ) {
            if (!$domain) {
                $domain = $this->domain;
            }
            $host = $domain;
            if ($subdomain) {
                $host = $subdomain . '.' . $host;
            }
            $rr = strtoupper($rr);
            if (null === self::record2const($rr)) {
                return error("unknown rr record type `%s'", $rr);
            }
            if (!$nameservers) {
                $nameservers = static::RECURSIVE_NAMESERVERS;
            }
            $resolvers = [];
            foreach ($nameservers as $ns) {
                if (strspn($ns, '1234567890.') === \strlen($ns)) {
                    $resolvers[] = $ns;
                } else if ($ip = Net_Gethost::gethostbyname_t($ns)) {
                    $resolvers[] = $ip;
                }
            }
            $resolver = new Net_DNS2_Resolver([
                'nameservers' => $resolvers,
                'ns_random'   => true
            ]);

            for ($i = 0; $i < 5; $i++) {
                // @todo remove dependency on dig
                $recraw = Error_Reporter::silence(function () use ($host, $rr, $resolver) {
                    try {
                        return $resolver->query($host, $rr);
                    } catch (Net_DNS2_Exception $e) {
                        return false;
                    }
                });
                if (!empty($recraw->answer)) {
                    break;
                }
                usleep(50000);
            }
            if (empty($recraw->answer)) {
                $host = ltrim(implode('.', array($subdomain, $domain)), '.');
                warn("failed to get external raw records for `%s' on `%s'", $rr, $host);

                return [];
            }

            $records = array();
            foreach ($recraw->answer as $r) {
                $target = null;

                // most records
                if (isset($r->target)) {
                    $target = $r->target;
                }
                // A
                if (isset($r->ip)) {
                    $target = $r->ip;
                }
                // SRV
                if (isset($r->weight)) {
                    // ignore PRI that comes before WEIGHT
                    // it is handled next
                    $target = $r->weight . ' ' . $target .
                        $r->port;
                }
                // MX, SRV
                if (isset($r->pri)) {
                    $target = $r->pri . ' ' . $target;
                }
                // TXT
                if (isset($r->txt)) {
                    $target = $r->txt;
                }
                // HINFO
                if (isset($r->cpu)) {
                    $target = $r->cpu . ' ' . $r->os;
                }
                // SOA
                if (isset($r->mname)) {
                    $target = $r->mname . ' ' . $r->rname . ' ' .
                        $r->serial . ' ' . $r->refresh . ' ' .
                        $r->retry . ' ' . $r->expire . ' ' .
                        $r->minimum;
                }
                // AAAA, A6
                if (isset($r->ipv6)) {
                    $target = $r->ipv6;
                }
                // A6
                if (isset($r->masklen)) {
                    $target = $r->masklen . ' ' . $target . ' ' .
                        $r->chain;
                }
                // NAPTR
                if (isset($r->order)) {
                    $target = $r->order . ' ' . $r->pref . ' ' .
                        $r->flags . ' ' . $r->services . ' ' .
                        $r->regex . ' ' . $r->replacement;
                }
                $records[] = array(
                    'name'      => $host,
                    'subdomain' => $subdomain,
                    'domain'    => $domain,
                    'class'     => 'IN',
                    'type'      => $rr,
                    'ttl'       => $r->ttl,
                    'parameter' => $target
                );
            }

            return $records;
        }

        /**
         * Translate RR into PHP constant
         *
         * NB Used by DNS Manager
         *
         * @param string $rr
         * @return int
         */
        public static function record2const($rr): ?int
        {
            $rr = strtoupper($rr);

            return static::$rec_2_const[$rr] ?? null;
        }

        /**
         * Returns the host name of the Internet host specified by $ip with timeout
         *
         * @param string $ip
         * @param int    $timeout
         * @return string|null|bool
         */
        public function gethostbyaddr_t(string $ip, int $timeout = 1000)
        {
            return Net_Gethost::gethostbyaddr_t($ip, $timeout);
        }

        /**
         * Returns the IP of the Internet host specified by $host with timeout
         *
         * @param string $name
         * @param int    $timeout
         * @return bool|null|string
         */
        public function gethostbyname_t(string $name, int $timeout = 1000)
        {
            return Net_Gethost::gethostbyname_t($name, $timeout);
        }

        /**
         * Check whether a domain is hosted on any server
         *
         * In multi-server setups, ensure all servers are named
         * SERVER_NAME_SHORT (first component of "hostname" command)
         *
         * @param string $domain
         * @param bool   $ignore_on_account domains hosted on account ignored
         * @return bool
         */
        public function domain_hosted(string $domain, bool $ignore_on_account = false): bool
        {
            $domain = strtolower($domain);
            if (0 === strpos($domain, "www.")) {
                $domain = substr($domain, 4);
            }

            $site_id = \Auth::get_site_id_from_domain($domain);
            // check if on same server
            if ($ignore_on_account && $site_id) {
                return $site_id !== $this->site_id;
            }

            // check if elsewhere
            if (false === ($server = \Auth_Redirect::lookup($domain))) {
                return warn("Domain validation endpoint failed. Treating lookup result as positive.");
            }

            // on another server
            if ($server && $server !== SERVER_NAME_SHORT) {
                return true;
            }

            // domain exists on server
            return (bool)$site_id;
        }

        /**
         * Domain exists and is under the account on a multi-server instance
         *
         * Useful when doing cross-server transfers to ensure the domain to add
         * is part of the account, which will allow the domain to be added via
         * the aliases_add_domain @{see Aliases_Module::add_domain}
         *
         * Implementation details are available on github.com/apisnetworks/apnscp-modules
         *
         * @param string $domain
         * @return bool
         */
        public function domain_on_account(string $domain): bool
        {
            return false;
        }

        /**
         * Get recently expiring domains
         *
         * Sample response:
         * Array(
         *  [0] => Array(
         *      'domain' => 'apnscp.com',
         *      'ts' => 1469937612
         *  )
         * )
         *
         * @param int  $days        lookahead n days
         * @param bool $showExpired show domains expired within the last 10 days
         *
         * @return array
         */
        public function get_pending_expirations(int $days = 30, bool $showExpired = true): array
        {
            return [];
        }

        /**
         * Check zone data with bind
         *
         * @param string $zone
         * @param Record[]  $recs
         * @return bool
         */
        public function check_zone(string $zone, array $recs = []): bool
        {
            if (!file_exists('/usr/sbin/named-checkzone')) {
                return warn("bind package is not installed - cannot check zone");
            }
            $tmpfile = tempnam('/tmp', 'f');
            if (null === ($axfr = $this->zoneAxfr($zone))) {
                return error("Failed to transfer zone `%s' - cannot check", $zone);
            }

            if ($recs) {
                $axfr .= "\n" . implode("\n", array_filter(array_map(function ($r) {
                    if (!$r instanceof \Opcenter\Dns\Record) {
                        return $r[0] . ' ' . $r[1] . ' ' . $r[2] . ' ' . $r[3];
                    }
                    return (string)$r;
                })));

            }
            file_put_contents($tmpfile, $axfr);
            $status = Util_Process_Safe::exec('/usr/sbin/named-checkzone %s %s', [$zone, $tmpfile]);
            unlink($tmpfile);

            return $status['success'];
        }

        /**
         * Update hostname with caller's IP4 address
         *
         * @param string $hostname fqdn
         * @param string $ip       optional ip address to skip detection
         * @return string|bool ip address or false on failure
         */
        public function update(string $hostname, string $ip = null)
        {
            $chunk = $this->web_split_host($hostname);
            $domain = $chunk['domain'];
            $subdomain = $chunk['subdomain'];
            if (!$this->owned_zone($domain)) {
                return error("restricted zone `%s' specified", $domain);
            }
            if (!$ip) {
                $ip = Auth::client_ip();
            }
            if (false === ip2long($ip)) {
                return error('cannot detect ip!');
            }
            $record = $this->get_records($subdomain, 'A', $domain);
            if (count($record) > 1) {
                warn("%d records found for `%s'", count($record), $hostname);
            }
            if (!$record) {
                // no record set
                warn("no DNS record exists, setting new record for `%s'", $hostname);
                $add = $this->add_record($domain, $subdomain, 'A', $ip, static::DYNDNS_TTL);
                if (!$add) {
                    return $add;
                }

                return $ip;
            }

            $newparams = array('ttl' => static::DYNDNS_TTL, 'parameter' => $ip);
            $ret = true;
            foreach ($record as $r) {
                if (!$this->modify_record($domain, $subdomain, $r['rr'], $r['parameter'], $newparams)) {
                    $ret = false;
                    error("record modification failed for `%s'", $hostname);
                }
            }

            return $ret ? $ip : $ret;
        }

        /*
         * Check zone for errors
         *
         * Additional DNS records are formatted as arguments
         * to add_record()-
         * check_zone("debug.com",["mail","a",86400,"127.0.0.1"])
         *
         * Hostname, RR, TTL, and parameter are required
         *
         * @param $zone zone - usually a domain
         * @param $recs additional DNS records used in check
         *
         * @return bool
         */

        /**
         * Get DNS record(s)
         *
         * @param string $subdomain optional subdomain
         * @param string $rr        optional RR type
         * @param string $domain    optional domain
         * @return array|bool
         */
        public function get_records(?string $subdomain = '', string $rr = 'any', string $domain = null)
        {
            if (!$domain) {
                $domain = $this->domain;
            }
            if (!$this->owned_zone($domain)) {
                return error('cannot view DNS information for unaffiliated domain `' . $domain . "'");
            }
            if (null === $subdomain) {
                $records = $this->get_zone_information($domain);
                $rr = strtoupper($rr);
                if ($rr === 'ANY') {
                    return $records;
                }

                return $records[$rr] ?? [];
            }
            if (false === ($recs = $this->get_records_raw($subdomain, $rr, $domain))) {
                // provisioning/internal error
                return false;
            }

            return (array)$recs;

        }

        /**
         * get_records() unauthenticated DNS wrapper
         *
         * @param string $subdomain optional subdomain
         * @param string $rr        optional RR type
         * @param string $domain    optional domain
         * @return array|bool records or false on failure
         */
        protected function get_records_raw(string $subdomain = '', string $rr = 'ANY', string $domain = null)
        {
            if ($subdomain == '@') {
                $subdomain = '';
                warn("record `@' alias for domain - record stripped");
            }
            $rr = strtoupper($rr);
            if ($rr !== 'ANY' && !in_array($rr, static::$permitted_records, true)) {
                return error('%s: invalid resource record type', $rr);
            }
            $rr = strtoupper($rr);
            $recs = $this->get_zone_data($domain);
            // zone error, Transfer failed, i.e. zone not provisioned
            if (null === $recs) {
                return false;
            }
            $domain .= '.';
            if ($subdomain !== '') {
                $domain = $subdomain . '.' . $domain;
            }

            $newrecs = [];
            $keys = [$rr];
            if ($rr == 'ANY') {
                $keys = array_keys($recs);
            } else if (!isset($recs[$rr])) {
                return $newrecs;
            }
            foreach ($keys as $tmp) {
                foreach ($recs[$tmp] as $rec) {
                    $rec['rr'] = $tmp;
                    if ($rec['name'] === $domain) {
                        $newrecs[] = $rec;
                    }
                }
            }

            return $newrecs;
        }

        /**
         * Add a DNS record to a domain
         *
         * @param string $zone      zone name (normally domain name)
         * @param string $subdomain name of the record to add
         * @param string $rr        resource record type [MX, A, AAAA, CNAME, NS, TXT, DNAME]
         * @param string $param     parameter value
         * @param int    $ttl       TTL value, default value 86400
         *
         * @return bool
         */
        public function add_record(
            string $zone,
            string $subdomain,
            string $rr,
            string $param,
            int $ttl = self::DNS_TTL
        ): bool {
            if (!$this->owned_zone($zone)) {
                return error('%s not owned by account', $zone);
            }
            if (!$this->canonicalizeRecord($zone, $subdomain, $rr, $param, $ttl)) {
                return false;
            }

            /**
             * Implement your own!
             */
            return true;
        }

        /**
         * Add a DNS record to a domain if no other record exists
         *
         * Purposed for Lararia\Jobs\SimpleCommandJob
         *
         * @param string $zone      zone name (normally domain name)
         * @param string $subdomain name of the record to add
         * @param string $rr        resource record type [MX, A, AAAA, CNAME, NS, TXT, DNAME]
         * @param string $param     parameter value
         * @param int    $ttl       TTL value, default value 86400
         *
         * @return bool
         */
        public function add_record_conditionally(
            string $zone,
            string $subdomain,
            string $rr,
            string $param,
            int $ttl = self::DNS_TTL
        ): bool
        {
            if (!$this->owned_zone($zone)) {
                return error('%s not owned by account', $zone);
            }
            if (!$this->configured()) {
                return info('DNS not configured for account - cannot add record');
            }
            if (!$this->zone_exists($zone)) {
                return warn("DNS zone `%s' does not exist, skipping", $zone);
            }
            if (!$this->canonicalizeRecord($zone, $subdomain, $rr, $param, $ttl)) {
                return false;
            }
            if ($this->record_exists($zone, $subdomain, $rr)) {
                return info("Record %s%s already exists - not overwriting", ltrim($subdomain . '.', '.'), $zone);
            }
            if ($rr === 'CNAME' && $this->record_exists($zone, $subdomain, 'ANY')) {
                return info("Record %s%s already has existing record - not adding CNAME", ltrim($subdomain . '.', '.'), $zone);
            }
            if (($rr === 'A' || $rr === 'AAAA') && $this->record_exists($zone, $subdomain, 'CNAME')) {
                return info("Record %s%s already exists as CNAME - not adding %s", ltrim($subdomain . '.', '.'), $zone, $rr);
            }
            if (!$this->add_record($zone, $subdomain, $rr, $param)) {
                return error('%s%s: DNS master returned bad value', ltrim($subdomain . '.', '.'), $zone);
            }
            return true;
        }

        /**
         * Fixup a DNS record before submitting
         *
         * @param string $zone
         * @param string $subdomain
         * @param string $rr
         * @param string $param
         * @param int    $ttl
         * @return bool
         */
        protected function canonicalizeRecord(
            string &$zone,
            string &$subdomain,
            string &$rr,
            string &$param,
            int &$ttl = null
        ): bool {

            $rr = strtoupper($rr);
            $subdomain = rtrim($subdomain, '.');
            if ($rr == 'CNAME') {
                if (!$subdomain && $this->hasCnameApexRestriction()) {
                    return error('CNAME record cannot coexist with zone root, see RFC 1034 section 3.6.2');
                }
                if (0 === strpos($subdomain, 'http:') || 0 === strpos($subdomain, 'https:')) {
                    return error('CNAME must be a hostname. A protocol was specified (http://, https://)');
                }
            }

            if ($rr === 'NS' && !$subdomain) {
                return error("Set nameserver records for zone root through domain registrar");
            }

            if ($rr !== 'ANY' && !\in_array($rr, static::$permitted_records, true)) {
                return error('%s: invalid resource record type', $rr);
            }

            if (false !== strpos($subdomain, ' ')) {
                return error("DNS record `%s' must not contain any spaces", $subdomain);
            }
            if (!static::HAS_ORIGIN_MARKER && substr($subdomain, -\strlen($zone)) === $zone) {
                $subdomain = substr($subdomain, 0, -\strlen($zone));
            }

            if (!static::HAS_ORIGIN_MARKER && $subdomain === '@') {
                $subdomain = '';
                warn("record `@' alias for domain - record stripped");
            }

            // many DNS services do not allow hosting a child as a standalone, work up the
            // chain to see if user added a subdomain as an addon domain (for "miscellaneous reasons")
            if (null !== ($parent = $this->getParent($zone))) {
                $subdomain = ltrim($subdomain . '.' . substr($zone, 0, -strlen($parent) - 1 /* period */), '.');
                $zone = $parent;
            }

            if (static::HAS_ORIGIN_MARKER && $subdomain === '') {
                $subdomain = '@';
            }

            if (!$param) {
                return true;
            }

            if ($rr == 'MX' && preg_match('/(\S+) (\d+)$/', $param, $mx_flip)) {
                // user entered MX record in reverse, e.g. mail.apisnetworks.com 10
                $param = $mx_flip[2] . ' ' . $mx_flip[1];
            }

            // per RFC 4408 section 3.1.3,
            // TXT records limits contiguous length to 255 characters, but
            // may also concatenate
            if ($rr == 'TXT') {
                $param = '"' . implode('" "', str_split(trim($param, '"'), 253)) . '"';
                if ($param[0] !== '"' && $param[strlen($param) - 1] !== '"') {
                    $param = '"' . str_replace('"', '\\"', $param) . '"';
                }
            }

            return true;
        }

        /**
         * Abides by DNS RFC that restricts DNS records from having an apex CNAME
         *
         * See also RFC 1034 section 3.6.2
         *
         * @return bool
         */
        protected function hasCnameApexRestriction(): bool
        {
            return true;
        }

        /**
         * Modify a DNS record
         *
         * @param string $zone
         * @param string $subdomain
         * @param string $rr
         * @param string $parameter
         * @param array  $newdata new zone data (name, rr, ttl, parameter)
         * @return bool
         */
        public function modify_record(
            string $zone,
            string $subdomain,
            string $rr,
            string $parameter,
            array $newdata
        ): bool {
            if (!$this->owned_zone($zone)) {
                return error($zone . ': not owned by account');
            }

            $ttl = (int)$this->get_default('ttl');
            if (!$this->canonicalizeRecord($zone, $subdomain, $rr, $parameter, $ttl)) {
                return false;
            }

            $newdata = static::createRecord($zone, array_merge([
                'name'      => $subdomain,
                'rr'        => $rr,
                'ttl'       => null,
                'parameter' => $parameter
            ], $newdata));

            if (!$this->canonicalizeRecord($zone, $newdata['name'], $newdata['rr'], $newdata['parameter'],
                $newdata['ttl'])) {
                return false;
            }

            $rectmp = preg_replace('/\.?' . $zone . '\.?$/', '', $newdata['name']);

            if ($newdata['name'] !== $subdomain && $newdata['rr'] !== $rr &&
                $this->record_exists($zone, $rectmp, $newdata['rr'], $parameter)
            ) {
                return error('Target record `' . $newdata['name'] . "' exists");
            }

            $old = static::createRecord($zone, [
                'name'      => $subdomain,
                'rr'        => $rr,
                'parameter' => $parameter
            ]);

            if (false === ($ret = $this->atomicUpdate($zone, $old, $newdata))) {
                // nsUpdate failed, rollback records
                warn('record update failed');

                return (($subdomain === $newdata['name'] && $rr === $newdata['rr']) ||
                        !$this->record_exists($zone, $subdomain, $rr, $parameter)) &&
                    $this->record_exists($zone, $newdata['name'], $newdata['rr'], $newdata['parameter']);
            }

            return (bool)$ret;
        }

        /**
         * Create a record using appropriate driver
         *
         * @param string $zone
         * @param array  $data
         * @return mixed
         */
        protected static function createRecord(string $zone, array $data = [])
        {
            $cls = static::getNamespace() . '\\Record';
            if (!class_exists($cls)) {
                $cls = \Opcenter\Dns\Record::class;
            }

            return new $cls($zone, $data);
        }

        /**
         * DNS record exists
         *
         * @param string $zone
         * @param string $subdomain
         * @param string $rr
         * @param string $parameter
         * @return bool
         */
        public function record_exists(
            string $zone,
            string $subdomain,
            string $rr = 'ANY',
            string $parameter = ''
        ): bool {
            static $failed = [];
            if ($subdomain == '@') {
                $subdomain = '';
                if (!static::HAS_ORIGIN_MARKER) {
                    warn("record `@' alias for domain - record stripped");
                }
            }
            // args passed as [zone:domain.com, subdomain:sub.domain.com]
            if ($subdomain && $subdomain[-1] === '.' && substr($subdomain, -\strlen($zone) - 1, -1) === $zone) {
                $subdomain = rtrim(substr($subdomain, 0, -\strlen($zone)-1), '.');
            }
            $record = trim($subdomain . '.' . $zone, '.');
            $rr = strtoupper($rr);
            if (null === static::record2const($rr)) {
                return error("unknown RR class `%s'", $rr);
            }
            $hostingns = array_diff($this->get_hosting_nameservers($zone), $failed);
            if (!$hostingns) {
                return warn("No hosting nameservers configured for `%s', cannot determine if record exists", $zone);
            }
            $status = Util_Process::exec('dig +norec +aaonly +time=3 +tcp +short @%s %s %s',
                $ns = $hostingns[array_rand($hostingns)],
                escapeshellarg($record),
                array_key_exists($rr, static::$rec_2_const) ? $rr : 'ANY'
            );
            if ($status['return'] === 9) {
                // nameserver timed out
                $failed[] = $ns;
                return warn("Query to `%s' failed - disabling from future queries", $ns);
            }
            // make sure there is some data in the response
            if (!$parameter) {
                $parameter = '.';
            } else {
                $parameter = str_replace("'", "\\'", preg_quote($parameter, '!'));
            }

            return (bool)preg_match('!' . $parameter . '!i', $status['output']);
        }

        /**
         * Perform an atomic update of a record allowing reversion on failure
         *
         * @param string               $zone
         * @param \Opcenter\Dns\Record $old
         * @param \Opcenter\Dns\Record $newdata
         * @return bool record succeeded
         */
        protected function atomicUpdate(string $zone, \Opcenter\Dns\Record $old, \Opcenter\Dns\Record $newdata): bool
        {
            // Throw an exception to halt reversion
            return false;
        }

        /**
         * Create DNS zone privileged mode
         *
         * @param string $domain
         * @param string $ip
         * @return bool
         */
        public function add_zone_backend(string $domain, string $ip): bool
        {
            if (!static::MASTER_NAMESERVER) {
                return error("rndc not configured in config.ini. Cannot add zone `%s'", $domain);
            }
            $buffer = Error_Reporter::flush_buffer();
            $res = $this->get_zone_data($domain);

            if (null !== $res) {
                Error_Reporter::set_buffer($buffer);
                warn("DNS for zone `%s' already exists, not overwriting", $domain);

                return true;
            }
            // make sure DNS does not exist yet for the parent
            [$a, $b] = explode('.', $domain, 2);
            $res = $this->get_zone_data($b);
            Error_Reporter::set_buffer($buffer);
            if (null !== $res) {
                warn("DNS for zone `%s' already exists, not overwriting", $b);

                return true;
            }

            if (is_array($ip)) {
                $ip = array_pop($ip);
            }

            if (inet_pton($ip) === false) {
                return error("`%s': invalid address", $ip);
            }

            info("Added domain `%s'", $domain);

            return true;
        }

        /**
         * Check whether IP is assigned
         *
         * Assigned IP addresses will have PTRs. Unassigned will be empty.
         *
         * @param $ip string ip address
         * @return bool
         */
        public function ip_allocated($ip): bool
        {
            return \Opcenter\Net\IpCommon::ip_allocated($ip);
        }

        /**
         * Import zone data for domain, overwriting configuration on server
         *
         * @param string      $domain
         * @param string      $nameserver
         * @param string|null $key
         * @return bool
         */
        public function import_from_ns(string $domain, string $nameserver, $key = null): bool
        {
            $myip = Util_Conf::server_ip();
            $domain = strtolower($domain);
            if (!preg_match(Regex::DOMAIN, $domain)) {
                return error("invalid zone `%s' - not a domain name", $domain);
            }

            if (!preg_match(Regex::DOMAIN, $nameserver)) {
                return error("invalid nameserver to query `%s'", $nameserver);
            }

            if ($key && false === strpos($key, ':')) {
                return error("invalid dns key `%s', must be in format name:key", $key);
            }
            if ($key) {
                $key = '-y' . $key;
            }

            $cmd = 'dig %(key)s -b%(ip)s @%(nameserver)s %(zone)s +norecurse +nocmd +nonssearch +noadditional +nocomments +nostats AXFR ';
            $proc = Util_Process_Safe::exec($cmd, array(
                'key'        => $key,
                'ip'         => $myip,
                'zone'       => $domain,
                'nameserver' => $nameserver
            ));
            $output = $proc['output'];
            if (!$proc['success'] || false !== strpos($output, '; Transfer failed')) {
                $output = $proc['stderr'] ?: $proc['output'];

                return error('axfr failed: %s', $output);
            }

            return $this->import($domain, output);
        }

        /**
         * Import records from hosted domain
         *
         * @param string $domain target domain to import records into
         * @param string $src    hosted domain to derive records from
         * @return bool
         */
        public function import_from_domain(string $domain, string $src): bool
        {
            if ($domain === $src) {
                return error("Cannot import - target is same as source");
            }
            if (false === ($recs = $this->export($src))) {
                return false;
            }
            return $this->import(
                $domain,
                preg_replace('!(\b|^)' . preg_quote($src, '!') . '(\b|$)!m', $domain, $recs)
            );
        }

        /**
         * Import raw AXFR records into zone
         *
         * @param string $domain
         * @param string $axfr
         * @return bool
         */
        public function import(string $domain, string $axfr): bool
        {
            // empty out old zone first
            $nrecs = 0;
            $zoneinfo = $this->get_zone_information($domain);
            if (null === $zoneinfo) {
                return error('unable to get old zone information - is this domain added to your account?');
            }
            foreach ($zoneinfo as $rr => $recs) {
                foreach ($recs as $rec) {
                    $tmp = strtoupper($rr);
                    // skip SOA + apex record
                    if ($tmp === 'SOA' || ($tmp === 'NS' && !$rec['subdomain'])) {
                        continue;
                    }
                    if (!$this->remove_record($domain, $rec['subdomain'], $rr, $rec['parameter'])) {
                        warn('failed to purge record `%s` %s %s %s',
                            $rec['name'],
                            $rr,
                            $rec['ttl'],
                            $rec['parameter']
                        );
                        continue;
                    }
                    $nrecs++;
                }
            }
            info('purged %d old records', $nrecs);

            $nrecs = 0;
            $regex = \Regex::compile(\Regex::DNS_AXFR_REC_DOMAIN,
                [
                    'rr' => implode('|', static::$permitted_records + [99999 => 'SOA']),
                    'domain' => str_replace('.', '\\.', $domain)
                ]);
            foreach (preg_split("/[\r\n]{1,2}/", $axfr) as $line) {

                if ('' === $line || $line[0] == ';') {
                    continue;
                }
                if (!preg_match($regex, $line, $rec)) {
                    continue;
                }
                $tmp = strtoupper($rec['rr']);
                // skip SOA + apex record
                if ($tmp === 'SOA' || ($tmp === 'NS' && !$rec['subdomain']) || ($rec['class'] ?? 'IN') !== 'IN') {
                    continue;
                }
                $subdomain = trim($rec['subdomain'], '.');
                $rec['parameter'] = preg_replace('/\s+/', ' ', $rec['parameter']);
                if (!$this->add_record($domain, $subdomain, $rec['rr'], $rec['parameter'], (int)$rec['ttl'])) {
                    warn('failed to add record `%s` -> `%s` (RR: %s, TTL: %s)',
                        $subdomain,
                        $rec['parameter'],
                        $rec['rr'],
                        $rec['ttl']
                    );
                    continue;
                }
                $nrecs++;
            }

            return info('imported %d records', $nrecs);
        }

        /**
         * Validate DNS template
         *
         * @param string $file
         * @param array  $overrideParams additional params to pass to site creation
         * @return bool
         */
        public function validate_template(string $file, array $overrideParams = []): bool
        {
            $blade = BladeLite::factory('templates/dns');
            if (!$blade->exists($file)) {
                return error("Requested DNS template `%s' does not exist", $file);
            }
            $acct = \Error_Reporter::silence(static function() use ($overrideParams) {
                return Ephemeral::create($overrideParams);
            });

            if (null === $acct) {
                return error('Failed to create test account to evaluate DNS template');
            }

            $zoneTxt = $blade->render($file, [
                'svc'       => SiteConfiguration::import($acct->getContext()),
                'ttl'       => 1800,
                'zone'      => $acct->getContext()->domain,
                'subdomain' => '',
                'hostname'  => $acct->getContext()->domain,
                'ips'       => array_filter([\Opcenter\Net\Ip4::my_ip(), \Opcenter\Net\Ip6::my_ip()])
            ]);

            \Error_Reporter::silence(static function() use ($acct) {
                return $acct->destroy();
            });

            $regex = \Regex::compile(\Regex::DNS_AXFR_REC_DOMAIN,
                [
                    'rr'        => implode('|', static::$permitted_records + [99999 => 'SOA']),
                    'domain'    => str_replace('.', '\\.', $acct->getContext()->domain),
                ]);

            foreach (explode("\n", $zoneTxt) as $line) {
                if (empty(trim($line))) {
                    continue;
                }
                if (!preg_match($regex, $line)) {
                    return error("Zone template `%s' failed on line: %s", $file, $line);
                }
            }
            return true;
        }

        /**
         * array get_zone_information (string)
         *
         * Reads zone information for a given domain on the nameservers.
         *
         * @param string|null $domain domain or current domain to check
         * @return array
         */
        public function get_zone_information(string $domain = null): ?array
        {
            $domain = $domain ?? $this->domain;

            if (!$this->permission_level & PRIVILEGE_ADMIN && !$this->owned_zone($domain)) {
                error('access denied - cannot view zone `' . $domain . "'");

                return null;
            }
            $rec = $this->get_zone_data($domain);
            if (null === $rec) {
                error('Non-authoritative for zone ' . $domain);

                return null;
            }

            return $rec;

        }

        /**
         * bool remove_record (string, string)
         * Removes a record from a zone.
         *
         * @param  string $zone      base domain
         * @param  string $subdomain subdomain, leave blank for base domain
         * @param  string $rr        resource record type, possible values:
         *                           [MX, TXT, A, AAAA, NS, CNAME, DNAME, SRV]
         * @param  string $param     record context
         * @return bool operation completed successfully or not
         *
         */
        public function remove_record(string $zone, string $subdomain, string $rr, string $param = ''): bool
        {
            $subdomain = rtrim($subdomain, '.');
            if (!$zone) {
                $zone = $this->domain;
            }
            if (!$this->owned_zone($zone)) {
                return error($zone . ': not owned by account');
            }

            if (!$this->canonicalizeRecord($zone, $subdomain, $rr, $param)) {
                return false;
            }
            // only supply parameter if parameter is provided


            /**
             * Now purge the record
             */

            return true;
        }

        public function release_ip(string $ip): bool
        {
            deprecated_func('use ipinfo_release_ip');

            return $this->ipinfo_release_ip($ip);
        }

        /**
         * Get module default
         *
         * @param string $key
         * @return mixed|null
         */
        public function get_default(string $key)
        {
            switch (strtolower($key)) {
                case 'ttl':
                    return static::DNS_TTL;
                default:
                    return null;
            }
        }

        /**
         * Get DNS minimum TTL
         *
         * @XXX DO NOT USE FOR VALIDATING TTL. DEFER TO API ALWAYS.
         *      Modules have special restrictions: CloudFlare allows "1" for automatic
         *
         * @return int
         */
        public function min_ttl(): int
        {
            return static::DNS_TTL_MIN;
        }

        public function _delete()
        {
            if (!$this->configured()) {
                return info("DNS not configured for `%s', bypassing DNS hooks", $this->domain);
            }
            if (!$this->getServiceValue('ipinfo', 'namebased')) {
                $ips = (array)$this->getServiceValue('ipinfo', 'ipaddrs');
                // pass the domain to verify the PTR isn't detached incorrectly
                // from another domain that has recycled it
                $domain = $this->getServiceValue('siteinfo', 'domain');
                foreach ($ips as $ip) {
                    $this->__deleteIP($ip, $domain);
                }
            }
            if (platform_is('7.5')) {
                return true;
            }
            foreach (array_keys($this->web_list_domains()) as $domain) {
                if ($this->owned_zone($domain)) {
                    $this->remove_zone($domain);
                } else {
                    dlog("Skipping stray zone $domain");
                }
            }

            return true;
        }

        /**
         * Release PTR assignment from an IP
         *
         * @param        $ip
         * @param string $domain confirm PTR rDNS matches domain
         * @return bool
         */
        protected function __deleteIP(string $ip, string $domain = null): bool
        {
            // @todo move to ipinfo
            return true;
        }

        /**
         * Remove zone from nameserver
         *
         * @param string $domain
         * @return bool
         */
        public function remove_zone_backend(string $domain): bool
        {
            return warn("cannot remove zone - DNS provider `%s' not configured fully",
                $this->getServiceValue('dns', 'provider', 'builtin'));
        }

        public function _edit()
        {
            if (!$this->configured()) {
                return info("DNS not configured for `%s', skipping edit hook", $this->domain);
            }
            $conf_old = $this->getAuthContext()->conf('ipinfo', 'old');
            $conf_new = $this->getAuthContext()->conf('ipinfo', 'new');
            $domainold = \array_get($this->getAuthContext()->conf('siteinfo', 'old'), 'domain');
            $domainnew = \array_get($this->getAuthContext()->conf('siteinfo', 'new'), 'domain');
            if (\array_get($this->getAuthContext()->conf('dns', 'old'), 'provider') !== array_get($this->getAuthContext()->conf('dns', 'new'), 'provider'))
            {
                $this->_create();
            }
            // domain name change via auth_change_domain()
            if ($domainold !== $domainnew) {
                $ip = (array)$this->publicIpWrapper('new', 4);
                $this->remove_zone($domainold);
                $this->add_zone($domainnew, $ip[0]);
                // domain name changed
                if (!$conf_new['namebased']) {
                    $this->__changePTR($ip[0], $domainnew, $domainold);
                }
            }

            $aliasesnew = array_get($this->getAuthContext()->conf('aliases', 'new'), 'aliases', []);
            $aliasesold = array_get($this->getAuthContext()->conf('aliases', 'old'), 'aliases', []);
            $ip = $this->get_public_ip();

            $add = array_diff($aliasesnew, $aliasesold);
            $rem = array_diff($aliasesold, $aliasesnew);
            foreach ($add as $a) {
                $this->add_zone($a, $ip);
            }

            foreach ($rem as $r) {
                $this->remove_zone($r);
            }

            // enable ip hosting
            if ($conf_new === $conf_old && $this->getAuthContext()->conf('dns', 'old') === $this->getAuthContext('dns', 'new')) {
                return;
            }

            $ipadd = $ipdel = [];
            $ipnew = $this->publicIpWrapper('new', 4, 'ipaddrs');
            $ipold = $this->publicIpWrapper('old', 4, 'ipaddrs');
            if ($conf_old['namebased'] && !$conf_new['namebased']) {
                // enable ip hosting
                $ipadd = $ipnew;
            } else if (!$conf_old['namebased'] && $conf_new['namebased']) {
                // disable ip hosting
                $ipdel = $ipold;
            } else {
                // add/remove ip hosting
                $ipdel = array_diff((array)$ipold, (array)$ipnew);
                $ipadd = array_diff((array)$ipnew, (array)$ipold);
            }

            foreach ($ipdel as $ip) {
                // NB __changePTR is called before to update domain on change
                $this->__deleteIP($ip, $domainnew);
            }

            foreach ($ipadd as $ip) {
                $this->__addIP($ip, $domainnew);
            }

            // update nbaddrs
            $ipnew = $this->publicIpWrapper('new', 4, 'nbaddrs');
            $ipold = $this->publicIpWrapper('old', 4, 'nbaddrs');
            if ($conf_old['namebased'] && !$conf_new['namebased']) {
                // added ip-based hosting
                $ipadd = $this->publicIpWrapper('new', 4, 'ipaddrs');
                $ipdel = $ipold;
            } else if (!$conf_old['namebased'] && $conf_new['namebased']) {
                // removed ip-based hosting
                $ipdel = $this->publicIpWrapper('old', 4, 'ipaddrs');
                $ipadd = $ipnew;
            } else if ($conf_old['namebased'] === $conf_new['namebased'] && $conf_new['namebased']) {
                // no namebased change
                $ipdel = array_diff(
                    (array)$this->publicIpWrapper('old', 4, 'nbaddrs'),
                    (array)$this->publicIpWrapper('new', 4, 'nbaddrs')
                );
                $ipadd = array_diff(
                    (array)$this->publicIpWrapper('new', 4, 'nbaddrs'),
                    (array)$this->publicIpWrapper('old', 4, 'nbaddrs')
                );
            }

            // change DNS
            // there will always be a 1:1 pairing for IP addresses
            $domains = array_keys($this->web_list_domains());
            foreach ($ipadd as $newip) {
                $oldip = array_pop($ipdel);
                $newparams = array('ttl' => static::DNS_TTL, 'parameter' => $newip);
                foreach ($domains as $domain) {
                    $records = $this->get_records_by_rr('A', $domain);
                    foreach ($records as $r) {
                        if ($r['parameter'] !== $oldip) {
                            continue;
                        }
                        if (!$this->modify_record($r['domain'], $r['subdomain'], 'A', $oldip, $newparams)) {
                            $frag = ltrim($r['subdomain'] . '.' . $r['domain'], '.');
                            error('failed to modify record for `' . $frag . "'");
                        } else {
                            $pieces = array($r['subdomain'], $r['domain']);
                            $host = trim(implode('.', $pieces), '.');
                            info("modified `%s'", $host);
                        }
                    }
                }
            }

            return;
        }

        public function _create()
        {
            if (platform_is('7.5')) {
                return true;
            }
            if (!$this->configured()) {
                return info("DNS not configured for `%s', bypassing DNS hooks", $this->domain);
            }
            $ipinfo = $this->getAuthContext()->conf('ipinfo');
            $siteinfo = $this->getAuthContext()->conf('siteinfo');
            $domain = $siteinfo['domain'];
            $ip = (array)$this->publicIpWrapper('cur');
            $this->add_zone($domain, $ip[0]);

            if (!$ipinfo['namebased']) {
                $ips = array_merge($ip, (array)$ipinfo['ipaddrs']);
                foreach(array_unique($ips) as $ip) {
                    $this->__addIP($ip, $siteinfo['domain']);
                }
            }
            if (!$this->domain_uses_nameservers($domain)) {
                warn("Domain `%s' doesn't use assigned nameservers. Change nameservers to %s",
                    $domain, implode(',', $this->get_hosting_nameservers($domain))
                );
            }

            return true;
        }

        /**
         * Helper function to fetch IP address from config
         *
         * @param string      $which
         * @param int         $class
         * @param string|null $svcvar class
         * @return string
         */
        protected function publicIpWrapper(string $which = 'cur', int $class = 4, string $svcvar = null)
        {
            if ($class !== 4 && $class !== 6) {
                fatal("Unknown IP class `%s'", $class);
            }
            if ($which === 'current') {
                $which = 'cur';
            }
            $confctx = $this->getAuthContext()->conf('dns', $which);
            $proxyvar = 'proxy' . ($class === 4 ? '' : '6') . 'addr';
            if ($info = ($confctx[$proxyvar] ?? null)) {
                return $info;
            }
            $svccls = 'ipinfo' . ($class === 6 ? '6' : '');
            $confctx = $this->getAuthContext()->conf($svccls, $which);
            if (null === $svcvar) {
                $svcvar = $confctx['namebased'] ? 'nbaddrs' : 'ipaddrs';
            }
            return $confctx[$svcvar];
        }

        /**
         * Add zone to DNS server
         *
         * @param string $domain
         * @param string $ip
         * @return bool
         */
        public function add_zone(string $domain, string $ip): bool
        {
            if (!$this->configured()) {
                return warn("cannot create DNS zone for `%s' - DNS is not configured for account", $domain);
            }

            $buffer = Error_Reporter::flush_buffer();

            if (($parent = $this->getParent($domain)) || $this->zone_exists($domain)) {
                Error_Reporter::set_buffer($buffer);
                if ($parent) {
                    warn("DNS for zone `%(domain)s' parented under `%(parent)s', not extending as separate zone",
                        ['domain' => $domain, 'parent' => $parent]);
                } else {
                    warn("DNS for zone `%s' already exists, not overwriting", $domain);
                }

                return true;
            }

            if (!$this->query('dns_add_zone_backend', $domain, $ip)) {
                return false;
            }

            // verify zone present; this is often async
            // @todo extend or exponential backoff?
            $data = null;
            $totalWait = 0;
            for ($i = 0; $i < 100; $i++) {
                if (null !== ($data = $this->zoneAxfr($domain))) {
                    break;
                }
                $wait = 250000 * $i;
                $totalWait += ($wait/1000000);
                if ($totalWait >= DNS_VALIDATION_WAIT) {
                    break;
                }
                usleep($wait);
            }
            if ($data !== null) {
                self::$zoneExistsCache[$domain] = true;
            } else {
                warn("%s master not reporting authoritative for zone `%s' - continuing to add DNS records",
                    ucwords($this->get_provider()),
                    $domain
                );
            }
            if ($this->permission_level & PRIVILEGE_ADMIN) {
                return warn("Zone added as administrator - unable to provision records automatically");
            }
            $records = $this->provisioning_records($domain) +
                append_config($this->email_provisioning_records($domain));
            foreach ($records as $record) {
                if ($this->record_exists($domain, $record['name'], $record['rr'], $record['parameter'])) {
                    continue;
                }
                if (!$this->add_record($domain, $record['name'], $record['rr'], $record['parameter'],
                    $record['ttl'])) {
                    warn("Failed to add DNS record `%s' on `%s' (rr: %s)", $domain, $record['name'], $record['rr']);
                }
            }

            return true;
        }

        /**
         * Hostname has parent
         *
         * @param string $hostname
         * @return bool
         */
        public function parented(string $hostname): bool
        {
            return $this->getParent($hostname) !== null;
        }

        /**
         * Get hostname parent
         *
         * @param string $hostname
         * @return string|null
         */
        protected function getParent(string $hostname): ?string
        {
            // let's assume admin knows what she's doing
            if ($this->permission_level & PRIVILEGE_ADMIN) {
                return null;
            }
            $count = substr_count($hostname, '.');
            if ($count < 2) {
                return null;
            }
            $pieces = explode('.', $hostname, $count);
            // aliases:list-shared-domains lists domains *attached* with a defined document root,
            // we need to inspect all aliases attached to the site as well as the domain itself to see if this
            // domain is explicitly defined or fallthrough to /var/www/html
            $domains = [$this->getConfig('siteinfo', 'domain')] + append_config($this->aliases_list_aliases());

            $tmp = array_pop($pieces);
            do {
                if (\in_array($tmp, $domains, true)) {
                    return $tmp;
                }
                $chk = array_pop($pieces);
                $tmp = "$chk.$tmp";
            } while ($tmp !== $hostname);

            return null;
        }

        /**
         * Get public IPv4 address(es)
         *
         * @return string|array|null single IP, multiple IPs, or null if not configured
         */
        public function get_public_ip()
        {
            $addr = $this->getServiceValue('dns','proxyaddr') ?: $this->common_get_ip_address();
            return \count($addr) > 1 ? $addr : ($addr[0] ?? null);
        }

        /**
         * Get public IPv6 address(es)
         *
         * @return string|array|null single IP, multiple IPs, or null if not configured
         */
        public function get_public_ip6()
        {
            $addr = $this->getServiceValue('dns', 'proxy6addr') ?: $this->common_get_ip6_address();

            return \count($addr) > 1 ? $addr : ($addr[0] ?? null);
        }

        /**
         * Get base provisioning DNS records to setup automatically
         *
         * @param string $zone zone name
         * @return \Opcenter\Dns\Record[]
         */
        public function provisioning_records(string $zone): array
        {
            if (!IS_CLI) {
                return $this->query('dns_provisioning_records', $zone);
            }

            if (!$this->getConfig('dns','enabled')) {
                return [];
            }

            $ttl = $this->dns_get_default('ttl');
            $ips = [];
            if ($this->getServiceValue('ipinfo', 'enabled')) {
                $ips += (array)$this->get_public_ip();
            }
            if ($this->getServiceValue('ipinfo6', 'enabled')) {
                $ips += append_config((array)$this->get_public_ip6());
            }

            $template = BladeLite::factory('templates/dns')->render('dns', [
                'svc'       => \Opcenter\SiteConfiguration::import($this->getAuthContext()),
                'ttl'       => $ttl,
                'zone'      => $zone,
                'subdomain' => '',
                'hostname' => ltrim(implode('.', ['', $zone]), '.'),
                'ips'       => (array)$ips
            ]);
            $regex = Regex::compile(Regex::DNS_AXFR_REC_DOMAIN, [
                'rr'     => implode('|', $this->dns_permitted_records() + [99999 => 'SOA']),
                'domain' => $zone
            ]);
            if (!preg_match_all($regex, $template, $matches, PREG_SET_ORDER)) {
                debug('No provisioning records discovered from template');

                return [];
            }
            $records = [];
            foreach ($matches as $record) {
                $records[] = static::createRecord($zone, [
                    'ttl'       => $record['ttl'],
                    'parameter' => $record['parameter'],
                    'rr'        => $record['rr'],
                    'name'      => rtrim($record['subdomain'], '.')
                ]);
            }

            return $records;
        }

        /**
         * Get DNS UUID for host
         *
         * @return null|string
         */
        public function uuid(): ?string
        {
            return DNS_UUID ?: null;
        }

        /**
         * Add an IP address to hosting
         *
         * @param string $ip
         * @param string $hostname
         * @return bool
         */
        protected function __addIP(string $ip, string $hostname = ''): bool
        {
            return true;
        }

        /**
         * Lookup and compare nameservers for domain to host
         *
         * @param string $domain
         * @return bool
         */
        public function domain_uses_nameservers(string $domain): bool
        {
            if (!preg_match(Regex::DOMAIN, $domain)) {
                return error("malformed domain `%s'", $domain);
            }
            $hostingns = $this->get_hosting_nameservers($domain);
            if (!$hostingns) {
                // not configured under [dns] hosting_ns in config.ini
                return true;
            }
            $dns = mute(function () use ($domain) {
                return $this->get_authns_from_host($domain);
            });
            $found = false;
            if (!$dns) {
                return $found;
            }
            if (DNS_VANITY_NS) {
                $hostingns += append_config(DNS_VANITY_NS);
            }
            foreach ($dns as $ns) {
                if (in_array($ns, $hostingns, true)) {
                    return true;
                }
            }

            return false;
        }

        /**
         * Get configured hosting nameservers
         *
         * Toggled via config.ini > [dns] > hosting_ns
         *
         * @return array
         */
        public function get_hosting_nameservers(string $domain = null): array
        {
            return DNS_HOSTING_NS;
        }

        /**
         * Get authoritative nameservers for given hostname
         *
         * Example response:
         *  Array
         *   (
         *   [0] => Array
         *      (
         *      [host] => ns2.apisnetworks.com
         *      [type] => A
         *      [ip] => 96.126.122.82
         *      [class] => IN
         *      [ttl] => 83137
         *   )
         * )
         *
         * @param string $host hostname
         * @return array|null authoritative nameservers or resolver chain incomplete
         */
        public function get_authns_from_host($host): ?array
        {
            $nameservers = static::RECURSIVE_NAMESERVERS;
            $authns = silence(function () use ($host, $nameservers) {
                return dns_get_record($host, static::record2const('ns'), $nameservers);
            });
            if ($authns) {
                // domain is properly delegated, nameserver returns affirmative
                $tmp = array();
                foreach ($authns as $a) {
                    if ($a['type'] == 'NS') {
                        $tmp[] = $a['target'];
                    }
                }

                return $tmp;
            }

            // domain delegated to hosting nameservers, but hosting servers don't
            // have dns provisioned yet for domain
            //
            // crawl
            $resolver = new Net_DNS2_Resolver([
                'nameservers' => $nameservers,
                'recurse'     => true
            ]);
            try {
                $nameservers = $this->get_authns_from_host_recursive($host, $resolver);
            } catch (Net_DNS2_Exception $e) {
                warn("NS lookup failed for `%s': %s", $host, $e->getMessage());

                return array();
            }

            return $nameservers;
        }

        /**
         * Fallback authoritative NS lookup
         *
         * Crawl the entire TLD hierarchy to find the last known nameserver
         *
         * @param string            $host
         * @param Net_DNS2_Resolver $resolver
         * @param string            $seen
         * @return array|null nameservers or null if resolve failed before reaching end
         */
        protected function get_authns_from_host_recursive($host, Net_DNS2_Resolver $resolver, $seen = ''): ?array
        {
            $components = explode('.', $host);
            $nameservers = null;
            try {
                $lookup = array_pop($components) . '.' . $seen;
                $res = silence(function () use ($resolver, $lookup) {
                    return $resolver->query($lookup, 'NS');
                });
                if ($res->answer) {
                    $nameservers = array_filter(array_map(function ($arr) {
                        return gethostbyname($arr->nsdname);
                    }, $res->answer));
                    $resolver->setServers($nameservers);
                }
            } catch (Net_DNS2_Exception | \Error $e) {
                if ($components) {
                    if (false !== strpos($e->getMessage(), "member function open() on null")) {
                        // invalid tld extension
                        return null;
                    }
                    // resolver chain broken
                    warn("failed to recurse on `%s': %s", $lookup, $e->getMessage());
                }

                return null;
            }
            if (!$components) {
                return array_map(function ($a) {
                    return $a->nsdname;
                }, $res->authority);
            }
            $resolver->recurse = 0;

            return $this->get_authns_from_host_recursive(implode('.', $components), $resolver, $lookup);

        }

        /**
         * Remove a zone from DNS management
         *
         * No direct access to method.
         * Use EditDomain or aliases:remove-domain to manage zone attachments.
         * Certain DNS providers may also soft delete zones requiring manual removal.
         *
         * @param string $domain
         * @return bool
         */
        public function remove_zone(string $domain): bool
        {
            if ($this->permission_level & PRIVILEGE_SITE && !$this->owned_zone($domain)) {
                return error("Unusual call to remove_zone() with specified unowned zone `%s' blocked", $domain);
            }
            if (!$this->configured()) {
                return warn("cannot remove DNS zone for `%s' - DNS is not configured for account", $domain);
            }

            if (null !== ($parent = $this->getParent($domain))) {
                // @TODO cleaning up a parented domain and its children will be messy
                return true;
            }

            if (!$this->zone_exists($domain)) {
                return true;
            }
            if (false === ($record = $this->get_records(static::UUID_RECORD, 'TXT', $domain))) {
                // zone axfr failed?
                return warn("Zone transfer failed - ignoring removal of `%s'", $domain);
            }
            if (null !== ($uuid = $this->uuid()) && $uuid !== ($record = array_get($record, '0.parameter', null))) {
                return warn("Bypassing DNS removal. DNS UUID for `%s' is `%s'. Server UUID is `%s'", $domain, $record,
                    $uuid);
            }
            if ($ret = $this->query('dns_remove_zone_backend', $domain)) {
                self::$zoneExistsCache[$domain] = null;
            }

            return $ret;
        }

        /**
         * Test credentials against configured module
         *
         * @param string $provider DNS provider to test
         * @param mixed  $key authentication key
         * @return bool
         */
        public function auth_test(string $provider = DNS_PROVIDER_DEFAULT, $key = ''): bool {
            if (!is_debug()) {
                return error("Only available in debug mode");
            }

            if (!\Opcenter\Dns::providerValid($provider)) {
                return error("DNS provider `%s' invalid", $provider);
            }

            if (!\Opcenter\Dns::providerHasHelper($provider)) {
                return true;
            }
            $helper = \Opcenter\Dns::getProviderHelper($provider);
            $ctx = new \Opcenter\Service\ConfigurationContext('dns', new SiteConfiguration($this->site));
            return $helper->valid($ctx, $key);
        }

        /**
         * Change PTR name
         *
         * @param string $ip       IP address to alter
         * @param string $hostname new PTR name
         * @param string $chk      optional check hostname to verify
         * @return bool
         */
        protected function __changePTR(string $ip, string $hostname, string $chk = ''): bool
        {
            return true;
        }

        /**
         * Query hosting nameservers for DNS records of named category
         *
         * {@see get_zone_information()}
         *
         * example:
         * Account has two MX records assigned, first the
         * default MX on debug.com, and a second user-created MX on debug.debug.com.
         * debug.debug.com was designated an e-mail domain through Mail Routing
         * {@see Email_Module::add_virtual_transport()}
         *
         * apis> $c->dns_get_records_by_rr("MX");
         *
         * array(2)
         *    apis>
         *    array(2) {
         *      [0]=>
         *      array(4) {
         *        ["name"]=>
         *        string(10) "debug.com."
         *        ["class"]=>
         *        string(2) "IN"
         *        ["ttl"]=>
         *        string(5) "86400"
         *        ["parameter"]=>
         *        string(18) "10 mail.debug.com."
         *      }
         *      [1]=>
         *      array(4) {
         *        ["name"]=>
         *        string(16) "debug.debug.com."
         *        ["class"]=>
         *        string(2) "IN"
         *        ["ttl"]=>
         *        string(5) "86400"
         *        ["parameter"]=>
         *        string(24) "10 mail.debug.debug.com."
         *      }
         *    }
         *
         * @param  string $rr resource record [MX, A, AAAA, CNAME, DNAME, TXT, SRV]
         * @param  string $zone
         * @return array|null resource records
         *
         */
        public function get_records_by_rr(string $rr, string $zone = null): ?array
        {
            if (null === $zone) {
                $zone = $this->domain;
            }

            if (!$this->owned_zone($zone)) {
                if (!$this->owned_zone($rr)) {
                    error('access denied - cannot view zone `' . $zone . "'");

                    return null;
                }
                // confusing half-assed backwards
                // accept arguments in either form
                $t = $rr;
                $rr = $zone;
                $zone = $t;
            }

            $rr = strtoupper($rr);
            if ($rr !== 'ANY' && !in_array($rr, static::$permitted_records, true)) {
                error('%s: invalid resource record type', $rr);

                return null;
            }

            $recs = $this->get_zone_information($zone);
            if (!$recs) {
                return array();
            }
            if ($rr == 'ANY') {
                return $recs;
            }
            if (!isset($recs[strtoupper($rr)])) {
                return array();
            }

            return $recs[strtoupper($rr)];
        }

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

        public function _create_user(string $user)
        {
            return;
        }

        public function _delete_user(string $user)
        {
            return;
        }

        public function _edit_user(string $userold, string $usernew, array $oldpwd)
        {
            return;
        }
    }