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

    use Daphnie\Collector;
    use Daphnie\Metrics\Mysql as MysqlMetrics;
    use Module\Support\Sql;
    use Opcenter\Database\MySQL\DefinerRemap;
    use Opcenter\Net\IpCommon;

    /**
     * MySQL and PostgreSQL operations
     *
     * @package core
     */
    class Mysql_Module extends Sql
    {
        const DEPENDENCY_MAP = [
            'siteinfo',
            'diskquota'
        ];
        const MYSQL_DATADIR = '/var/lib/mysql';
        // @var int minimum MySQL version to use new API
        const NEW_API_VERSION = 50720;
        // @var int default concurrency setting for users
        const DEFAULT_CONCURRENCY_LIMIT = 10;
        // @var int maximum concurrent connections per user
        const MAX_CONCURRENCY_LIMIT = MYSQL_CONCURRENCY_LIMIT;

        // @var string MySQL export command
        const EXPORT_CMD = '/usr/bin/mysqldump --add-drop-table --add-drop-trigger --triggers --events -q -R';

        protected $exportedFunctions = array(
            '*'                             => PRIVILEGE_SITE,
            'version'                       => PRIVILEGE_ALL,
            'get_elevated_password_backend' => PRIVILEGE_ALL | PRIVILEGE_SERVER_EXEC,
            'create_database_backend'       => PRIVILEGE_SITE | PRIVILEGE_SERVER_EXEC,
            'delete_database_backend'       => PRIVILEGE_SITE | PRIVILEGE_SERVER_EXEC,
            'get_uptime'                    => PRIVILEGE_ALL,
            'assert_permissions'            => PRIVILEGE_SITE | PRIVILEGE_SERVER_EXEC,
            'set_option'                    => PRIVILEGE_ALL,
            'get_option'                    => PRIVILEGE_ALL,
            'export_pipe_real'              => PRIVILEGE_SITE | PRIVILEGE_SERVER_EXEC,
            'enabled'                       => PRIVILEGE_SITE | PRIVILEGE_USER,
            'repair_mysql_database'         => PRIVILEGE_SITE | PRIVILEGE_ADMIN,
            'get_prefix'                    => PRIVILEGE_SITE | PRIVILEGE_USER,

            // necessary for DB backup routines
            'get_database_size'             => PRIVILEGE_SITE | PRIVILEGE_ADMIN,
            'database_exists'               => PRIVILEGE_SITE | PRIVILEGE_ADMIN,
            '_export_old'                   => PRIVILEGE_SITE | PRIVILEGE_SERVER_EXEC,
            'recover_innodb_from_disk'      => PRIVILEGE_ADMIN,
            'stats'                         => PRIVILEGE_ALL
        );

        public function __destruct()
        {
            foreach ($this->_tempUsers as $user) {
                if (!$this->user_exists($user)) {
                    continue;
                }
                $this->_delete_temp_user($user);
            }
        }

        public function user_exists($user, $host = 'localhost')
        {
            if (!$user) {
                return false;
            }
            $conn = $this->_connect_root();
            $prefix = $this->get_prefix();
            if ($user !== $this->getServiceValue('mysql', 'dbaseadmin') &&
                0 !== strpos($user, $prefix)
            ) {
                $user = $prefix . $user;
            }

            $q = $conn->query("SELECT user FROM user WHERE user = '" .
                $conn->escape_string($user) . "' AND host = '" . $conn->escape_string($host) . "'");

            return !$q || $q->num_rows > 0;
        }

        public function get_prefix()
        {
            return $this->getServiceValue('mysql', 'dbaseprefix');
        }

        /**
         * Delete a temporary MySQL user
         *
         * @warn do not invoke directly, use wrapper _delete_temp_user()
         * @param string $user
         * @return bool
         */
        private function _delete_temp_user($user)
        {
            if (!Opcenter\Database\MySQL::deleteUser($user, 'localhost')) {
                return false;
            }


            $idx = array_search($user, $this->_tempUsers, true);
            if ($idx !== false) {
                unset($this->_tempUsers[$idx]);
            }

            return true;
        }

        /**
         * bool delete_mysql_user(string, string[, bool = false])
         * Delete a MySQL user
         *
         * @param string $user    username
         * @param string $host    hostname
         */
        public function delete_user($user, $host)
        {
            if (!IS_CLI) {
                return $this->query('mysql_delete_user', $user, $host);
            }
            if ($user === $this->username && !Util_Account_Hooks::is_mode('delete')) {
                return error('Cannot remove main user');
            } else if (!$this->user_exists($user, $host)) {
                return error("user `%s' on `%s' does not exist", $user, $host);
            }
            $prefix = $this->get_prefix();
            if ($user !== $this->getConfig('mysql', 'dbaseadmin') && strpos($user, $prefix) !== 0) {
                $user = $prefix . $user;
            }
            if (\Opcenter\Database\MySQL::version() >= static::NEW_API_VERSION) {
                return Opcenter\Database\MySQL::deleteUser($user, $host);
            }
            $conn = new mysqli('localhost', self::MASTER_USER, $this->_get_elevated_password());
            $conn->select_db('mysql');
            $stmt = $conn->prepare('DELETE FROM user WHERE user = ? AND host = ?');
            $stmt->bind_param('ss', $user, $host);
            $stmt->execute();
            if ($stmt->error) {
                return new MySQLError('Invalid query, ' . $stmt->error);
            }

            $stmt2 = $conn->prepare('DELETE FROM db WHERE user = ? AND host = ?');
            $stmt2->bind_param('ss', $user, $host);
            $stmt2->execute();
            if (!$stmt2->error) {
                $conn->query('FLUSH PRIVILEGES');
            } else {
                return new MySQLError('Invalid query, ' . $stmt2->error);
            }

            return ($stmt->affected_rows > 0);

        }

        /**
         * bool store_sql_password (string, string)
         *
         * @param string $sqlpasswd plaintext password
         * @return bool
         */
        public function store_password($sqlpasswd)
        {
            return $this->set_option('password', $sqlpasswd, 'client');
        }

        /**
         * Set MySQL client option
         *
         * Reads from ~/.my.cnf and creates if necessary.
         * Specify a value of null to remove an option.
         *
         * @param string $option
         * @param string $value
         * @param string $group
         * @return bool
         */
        public function set_option($option, $value = null, $group = 'client')
        {
            if (!IS_CLI) {
                return $this->query('mysql_set_option', $option, $value, $group);
            }
            $home = $this->user_get_user_home();
            $path = $this->domain_fs_path() . "${home}/.my.cnf";
            if (is_link($path) && (
                false === ($link = readlink($path)) ||
                0 !== strpos($this->domain_fs_path(), realpath($link)))
            )
            {
                unlink($path);
            }
            if (!file_exists($path)) {
                \Opcenter\Filesystem::touch($path, $this->user_id, $this->group_id, 0600);
            }

            return \Opcenter\Database\MySQL::setUserConfigurationField($path, $option, $value, $group);
        }

        /**
         * string retrieve_sql_password (string)
         *
         * @return string
         */
        public function get_password()
        {
            return $this->get_option('password');
        }

        /**
         * Get option from MySQL client/server configuration
         *
         * @param  string $option option name
         * @param  string $group  option group
         * @return mixed option value, false on failure, null on non-existent value
         */
        public function get_option($option, $group = 'client')
        {
            if (!IS_CLI) {
                return $this->query('mysql_get_option', $option, $group);
            }
            $home = $this->user_get_user_home();
            $paths = [
                $this->domain_fs_path() . "${home}/.my.cnf",
                '/etc/my.cnf'
            ];
            foreach ($paths as $path) {
                if (is_link($path) && 0 !== strpos($this->domain_fs_path(), realpath(readlink($path)))) {
                    // naughty!
                    continue;
                }
                if (null !== ($val = array_get(\Opcenter\Database\MySQL::getUserConfiguration($path),
                        "${group}.${option}", null))) {
                    return $val;
                }
            }

            return null;
        }

        public function get_elevated_password_backend()
        {
            if (!IS_CLI) {
                fatal('needs execution from backend');
            }

            return Opcenter\Database\MySQL::rootPassword();
        }

        /**
         * Import a database from a dump
         *
         * @see Mysql_Module::export()
         *
         * @param string $db   database name
         * @param string $file filename
         * @return bool
         */
        public function import($db, $file)
        {
            if (!IS_CLI) {
                return $this->query('mysql_import', $db, $file);
            }

            $prefix = $this->get_prefix();
            // db name passed without prefix
            if (strncmp($db, $prefix, strlen($prefix))) {
                $db = $prefix . $db;
            }

            $dbs = $this->list_databases();
            if (false === array_search($db, $dbs, true)) {
                return error("database `%s' does not exist", $db);
            }
            $unlink = null;
            if (false === ($realfile = $this->_preImport($file, $unlink))) {
                return false;
            }

            $tempUser = $this->_create_temp_user($db);
            if (!$tempUser) {
                $this->_postImport($unlink);
                return error('unable to import database');
            }

            /**
             * Tricky spot! triggers/events are dumped with definer information, which conflicts
             * with anonymous user imports. Util_Process doesn't handle callbacks on piped input (@todo)
             * Perform an intermediate sed on statements with DEFINER, change to current user, outputting previous,
             * then depending upon whether the user exists (non-prefixed match), apply a second query to translate
             * all triggers/events/procedures to the new user
             *
             * Only one remap is supported at this time
             */

            $bulk = [];
            // @todo refactor to utility class
            if (filetype($realfile) === 'file') {
                $ret = Util_Process_Safe::exec('sed -i %s %s', [
                    '{
                    /DEFINER=[^* ]*\(\*\| \)/w /dev/stdout
                    s/DEFINER=[^* ]*\(\*\| \)/\1/g
                }',
                    $realfile
                ]);

                if (!$ret['success']) {
                    return error("Aborting import from `%s'. Failed to perform DEFINER pass: %s", $file, $ret['error']);
                }

                // make a "best effort" at determining the new ownership
                if (preg_match_all(Regex::SQL_MYSQL_DEFINER, $ret['stdout'], $matches, PREG_SET_ORDER)) {
                    // default to admin@localhost
                    $bulkChangeCredentials = [];
                    $prefix = $this->get_prefix();
                    $users = [];
                    foreach ($this->list_users() as $user => $hosts) {
                        if (0 === strpos($user, $prefix)) {
                            $user = substr($user, \strlen($prefix));
                        }
                        $users[$user] = [];
                        foreach (array_keys($hosts) as $host) {
                            $users[$user][$host] = 1;
                        }
                    }

                    foreach ($matches as $gm) {
                        // PROCEDURE/FUNCTION is the same
                        if ($gm['type'] === 'FUNCTION') {
                            $gm['type'] = 'PROCEDURE';
                        }

                        if (false !== ($pos = strpos($gm['user'], '_'))) {
                            $gm['user'] = substr($gm['user'], ++$pos);
                        }

                        if (!isset($users[$gm['user']])) {
                            warn(
                                'User %s not found in user table. Converting %s grant for %s to %s',
                                $gm['user'], $gm['type'], $gm['name'], $this->getConfig('mysql', 'dbaseadmin')
                            );
                            $gm['user'] = $this->getConfig('mysql', 'dbaseadmin');
                            $gm['host'] = 'localhost';
                        } else if (!isset($users[$gm['user']][$gm['host']])) {
                            warn(
                                'Host %s not found in user table. Converting %s grant for %s to localhost',
                                $gm['host'], $gm['type'], $gm['user']
                            );
                            $gm['host'] = 'localhost';
                        }

                        if (empty($bulkChangeCredentials)) {
                            $bulkChangeCredentials = [
                                $gm['user'],
                                $gm['host']
                            ];
                        } else if ($bulkChangeCredentials !== [$gm['user'], $gm['host']]) {
                            warn(
                                'Import only supports 1 DEFINER adjustment. Converting %s (type: %s) from `%s`@`%s` to `%s`@`%s`',
                                $gm['name'], $gm['type'], $gm['user'], $gm['host'], $bulkChangeCredentials[0],
                                $bulkChangeCredentials[1]
                            );
                        }
                        if (empty($bulk[$gm['type']])) {
                            $bulk[$gm['type']] = [];
                        }
                        $bulk[$gm['type']][] = $gm['name'];
                    }
                    // slip prefix back into user if not main
                    if (isset($bulkChangeCredentials[0]) && $bulkChangeCredentials[0] !== $this->getConfig('mysql',
                            'dbaseadmin')) {
                        $bulkChangeCredentials[0] = $this->getConfig('mysql',
                                'dbaseprefix') . $bulkChangeCredentials[0];
                    }
                }
            }


            $safe = new Util_Process_Safe();
            $safe->setDescriptor(0, 'file', [$realfile, 'rb'], null, ['mute_stdin' => false]);
            $safe->setPriority(19);
            $safe->addCallback(function() use ($unlink, $tempUser) {
                $this->_postImport($unlink);
                $this->_delete_temp_user($tempUser);
                return true;
            }, 'close');

            $status = $safe->run('mysql -u %s %s', $tempUser, $db);
            if (!$status['success']) {
                return false;
            }
            if ($bulk) {
                $handler = new DefinerRemap($db, $this->_connect_root(true));
                // spray and pray
                $handler->remapAll(...$bulkChangeCredentials);
            }

            return $status['success'];
        }

        /**
         * Recover InnoDB from .ibd files
         *
         * Existing .ibd are NOT overwritten.
         *
         * @param string $db      target database
         * @param string $srcdir  source directory containing .ibd files
         * @param bool   $force   overwrite .ibd if it exists
         * @return bool
         */
        public function recover_innodb_from_disk(string $db, string $srcdir, bool $force = false): bool
        {
            if (!IS_CLI) {
                return $this->query('mysql_recover_innodb_from_disk', $db, $srcdir, $force);
            }

            if (!\Opcenter\Database\MySQL::databaseExists($db)) {
                return error("Database `%s' does not exist", $db);
            }
            if (!is_dir($srcdir)) {
                return error("Source path `%s' is not a directory", $srcdir);
            }

            $glob = array_map(
                static function ($file) { return basename($file, '.ibd'); },
                glob("${srcdir}/*.ibd", GLOB_NOESCAPE)
            );

            if (empty($glob)) {
                return error("No matching *.ibd files found in `%s'", $srcdir);
            }
            $tables = \Opcenter\Database\MySQL::getTablesFromDatabase($db);

            // missing from $dir and cannot be recovered
            $missingSource = array_values(array_diff($tables, $glob));
            // present in $dir but missing in database - weird.
            $missingSchema = array_values(array_diff($glob, $tables));

            $user = $this->_create_temp_user($db);

            $datadir = realpath(self::MYSQL_DATADIR . '/' . \Opcenter\Database\MySQL::canonicalize($db));
            if (!$datadir || !($stat = stat($datadir))) {
                return error(
                    "Unable to stat `%s'",
                    self::MYSQL_DATADIR . '/' . \Opcenter\Database\MySQL::canonicalize($db)
                );
            }

            $conn = MySQL::stub();
            $conn->connect('localhost', $user, null, $db);
            $conn->query('SET FOREIGN_KEY_CHECKS=0');

            $importer = static function($table) use ($conn, $srcdir, $datadir, $stat): bool {
                $ex = \Error_Reporter::exception_upgrade(\Error_Reporter::E_FATAL);
                try {
                    $conn->query("LOCK TABLES `${table}` WRITE");
                } catch (apnscpException $e) {
                    // pass
                } finally {
                    \Error_Reporter::exception_upgrade($ex);
                }

                $conn->query("ALTER TABLE `${table}` DISCARD TABLESPACE");

                if (!copy("${srcdir}/${table}.ibd", "${datadir}/${table}.ibd")) {
                    return false;
                }
                if (!\Opcenter\Filesystem::chogp("${datadir}/${table}.ibd", $stat['uid'], $stat['gid'], 0600)) {
                    return false;
                }
                return (bool)$conn->query("ALTER TABLE `${table}` IMPORT TABLESPACE");
            };

            try {
                // these files have both a .ibd and exist in table schema, EZ
                foreach (array_intersect($glob, $tables) as $table) {
                    if (!$force && file_exists("${datadir}/${table}.ibd")) {
                        info("InnoDB file `%(path)s/%(table)s.ibd' already exists - skipping %(db)s.%(table)s",
                            ['path' => $datadir, 'table' => $table, 'db' => $db]);
                        continue;
                    }
                    if (!$importer($table)) {
                        warn('Failed to replace table %(table)s in %(db)s',
                            ['table' => $table, 'db' => $db]);
                    } else {
                        info('Restored %(db)s.%(table)s', ['db' => $db, 'table' => $table]);
                    }
                }

                // these files exist in the backup, but lack  a .frm in data directory - let's try anyway!
                foreach ($missingSchema as $table) {
                    if (!file_exists("$srcdir/${table}.frm")) {
                        // it's fucked
                        continue;
                    }
                    warn('%s.%s present in backup, .frm present in data directory, but .ibd missing - continuing import', $db, $table);
                    foreach (['ibd', 'frm'] as $ext) {
                        if (!$force && file_exists("${datadir}/${table}.${ext}")) {
                            info("InnoDB file `%s/%s.%s' already exists - skipping %s.%s",
                                $datadir, $table, $ext, $db, $table);
                            continue;
                        }
                        $ret = copy("${srcdir}/${table}.${ext}", "${datadir}/${table}.${ext}") &&
                            \Opcenter\Filesystem::chogp("${datadir}/${table}.${ext}", $stat['uid'], $stat['gid'], 0600);

                        if (!$ret) {
                            warn('Failed to replace table %s in %s', $table, $db);
                            continue 2;
                        }
                    }
                    // @TODO import/discard tablespace?
                    info('Restored %s.%s', $db, $table);
                }

                foreach ($missingSource as $table) {
                    if (file_exists("${datadir}/${table}.ibd") || file_exists("${datadir}/${table}.MYI")) {
                        continue;
                    }
                    warn("%(db)s.%(table)s reported in `%(path)s' but no backup in %(srcdir)s",
                        ['db' => $db, 'table' => $table, 'path' => $datadir, 'srcdir' => $srcdir]);
                }
            } catch (\Throwable $e) {
                return error("Failed to restore backup into `%(db)s': %(err)s",
                    ['db' => $db, 'err' => $e->getMessage()]);
            } finally {
                $conn->query('SET FOREIGN_KEY_CHECKS=1');
            }
            // lock is released anyway
            $conn->query('UNLOCK TABLES');
            return true;
        }

        /**
         * array list_mysql_databases ()
         * Queries the db table in the mysql database for applicable grants
         *
         * @return array list of databases
         */
        public function list_databases()
        {
            $prefix = $this->_escape($this->get_prefix());
            if (!$prefix) {
                report('Prefixless site - bug');
                return [];
            }
            $conn = new mysqli('localhost', self::MASTER_USER, $this->_get_elevated_password());
            $conn->select_db('mysql');
            $q = $conn->query("SELECT DISTINCT(REPLACE(db,'\\_','_')) AS db FROM db WHERE db LIKE '" . str_replace('_', '\\_', $prefix) . "%' OR db LIKE '" . str_replace('_', '\\\\_', $prefix) . "%' OR user = '" . $this->username . "'");
            $dbs = array();
            while (null !== ($row = $q->fetch_object())) {
                $dbs[] = $row->db;
            }

            $conn->close();

            return $dbs;
        }

        /**
         * Create a temporary mysql user
         *
         * @param string $db
         * @return string|object
         */
        private function _create_temp_user($db)
        {
            // allow use by admin
            $prefix = (string)$this->get_prefix();
            $maxlen = \Opcenter\Database\MySQL::fieldLength('user') - strlen($prefix);
            if ($maxlen < 1) {
                warn('temp mysql user exceeds field length, cannot create user');
                return false;
            }
            $chars = array(
                'a',
                'b',
                'c',
                'd',
                'e',
                'f',
                '0',
                '1',
                '2',
                '3',
                '4',
                '5',
                '6',
                '7',
                '8',
                '9',
            );
            $maxlen = min(8, $maxlen);

            $user = $prefix;
            for ($i = 0; $i < $maxlen; $i++) {
                $n = mt_rand(0, 15);
                $user .= $chars[$n];
            }

            // could be handled via add_mysql_user()
            $sqldb = $this->_connect_root();
            $q = "SELECT user FROM user WHERE user = '" . $user . "'";
            $rs = $sqldb->query($q);
            if ($rs->num_rows > 0) {
                return error('cannot create temp mysql user');
            }
            $q = "CREATE USER '" . $user . "'@'localhost' IDENTIFIED BY ''";
            $rs = $sqldb->query($q);
            if (!$rs) {
                return error('failed to create temp mysql user');
            }
            $q = 'GRANT ALL ON `' . $db . "`.* to '" . $sqldb->escape_string($user) . "'@localhost";
            $rs = $sqldb->query($q);
            if (!$rs) {
                return error('failed to create temp mysql user');
            }
            $q = "GRANT SELECT ON mysql.proc TO '" . $sqldb->escape_string($user) . "'@localhost";
            $sqldb->query($q);
            $this->_register_temp_user($user);

            return $user;
        }

        /**
         * Change account database prefix
         *
         * @param string $prefix
         * @return bool
         */
        public function change_prefix($prefix)
        {
            return error('use sql_change_prefix');
        }

        public function get_sql_prefix()
        {
            deprecated('use sql_get_prefix');

            return $this->get_prefix();
        }

        /**
         * array list_mysql_users ()
         * Lists all created users for MySQL
         */
        public function list_users()
        {
            // meta is corrupted, let's bail
            if (!$prefix = $this->getServiceValue('mysql', 'dbaseprefix')) {
                return [];
            }

            $prefix = str_replace('_', '\_', $prefix);
            if (!$prefix) {
                report('Prefixless site - bug');

                return [];
            }
            $conn = new mysqli('localhost', self::MASTER_USER, $this->_get_elevated_password());
            $conn->select_db('mysql');
            $q = $conn->query("SELECT host,
                                     user,
                                     password,
                                     ssl_type,
                                     ssl_cipher,
                                     x509_issuer,
                                     x509_subject,
                                     max_questions,
                                     max_updates,
                                     max_connections,
                                     max_user_connections FROM user WHERE user = '" . $this->username . "' OR user LIKE '" . $prefix . "%'");
            $users = array();
            while (null !== ($row = $q->fetch_array(MYSQLI_ASSOC))) {
                $row = array_change_key_case($row, CASE_LOWER);
                $user = $row['user']; $host = $row['host'];
                $users[$user][$host] = array(
                    'ssl_type'             => $row['ssl_type'],
                    'ssl_cipher'           => $row['ssl_cipher'],
                    'x509_issuer'          => $row['x509_issuer'],
                    'x509_subject'         => $row['x509_subject'],
                    'max_questions'        => (int)$row['max_questions'],
                    'max_updates'          => (int)$row['max_updates'],
                    'max_user_connections' => (int)$row['max_user_connections'],
                    'max_connections'      => (int)$row['max_connections'],
                    'password'             => $row['password'],
                );
            }

            return $users;
        }

        /**
         * bool add_mysql_user(string, string, string[, int[, int[, int[, string[, string[, string[, string]]]]]]])
         *
         * @param        $user
         * @param        $host
         * @param        $password
         * @param int    $maxconn
         * @param int    $maxupdates
         * @param int    $maxquery
         * @param string $ssl
         * @param string $cipher
         * @param string $issuer
         * @param string $subject
         * @return bool|MySQLError|void
         */
        public function add_user(
            $user,
            $host,
            $password,
            $maxconn = self::DEFAULT_CONCURRENCY_LIMIT,
            $maxupdates = 0,
            $maxquery = 0,
            $ssl = '',
            $cipher = '',
            $issuer = '',
            $subject = ''
        ) {
            if (!IS_CLI) {
                return $this->query('mysql_add_user', ...func_get_args());
            }
            if (!$user) {
                return error('no username specified');
            }
            $dbaseadmin = $this->getConfig('mysql', 'dbaseadmin');
            if ($user === $dbaseadmin && !IS_SOAP) {
                return error("cannot name user after primary account user, `%s'", $dbaseadmin);
            }

            $ssl = strtoupper($ssl);
            if (!$maxconn) {
                $maxconn = self::DEFAULT_CONCURRENCY_LIMIT;
            }
            $host = trim($host);
            if ($host != 'localhost' && !IpCommon::valid($host) && !preg_match(Regex::SQL_MYSQL_IP_WILDCARD, $host)) {
                return error("rejected host `%s': only numeric IP addresses are permitted, not hostnames", $host);
            }
            if (strlen($password) < self::MIN_PASSWORD_LENGTH) {
                return error('Password must be at least %d characters', self::MIN_PASSWORD_LENGTH);
            } else if ($ssl !== '' && $ssl != 'ANY' && $ssl != 'X509' && $ssl != 'SPECIFIED') {
                return error('Invalid SSL type');
            } else if ($maxconn < 1 || $maxquery < 0 || $maxupdates < 0) {
                return error('Max connections, queries, and updates must be greater than 0');
            } else if ($maxconn > static::MAX_CONCURRENCY_LIMIT) {
                return error('Max concurrent connections cannot exceed %d. ' .
                    'Contact support if you need more than %d.',
                    static::MAX_CONCURRENCY_LIMIT, static::MAX_CONCURRENCY_LIMIT);
            } else if ($this->user_exists($user, $host)) {
                return error("mysql user `$user' on `$host' exists");
            }
            $conn = $this->_connect_root();
            $prefix = $this->get_prefix();
            if ($user !== $this->getConfig('mysql', 'dbaseadmin') && 0 !== strpos($user, $prefix)) {
                // add the prefix if prefix is not provided, this is to workaround cases where user
                // is equal to prefixprefixuser
                $user = $prefix . $user;
            }
            if (Opcenter\Database\MySQL::version() >= static::NEW_API_VERSION) {
                return \Opcenter\Database\MySQL::createUser(
                    $user,
                    $password,
                    $host,
                    [
                        'ssl' => $ssl,
                        'cipher' => $cipher,
                        'issuer' => $issuer,
                        'subject' => $subject
                    ],
                    [
                        'connections' => (int)$maxconn,
                        'query' => (int)$maxquery,
                        'updates' => (int)$maxupdates
                    ]
                ) ?: error("User creation failed on `%s@%s'", $user, $host);
            }
            $pwclause = 'password(?)';
            // password is encrypted in new pw form or old
            if ((\strlen($password) === 16 && ctype_xdigit($password)) ||
                ($password[0] == '*' && \strlen($password) === 41
                && ctype_xdigit(substr($password, 1))))
            {
                $pwclause = '?';
            }
            $needAuth = $conn->columnExists('authentication_string', 'user');
            $query = 'INSERT INTO user
                    (host,
                     user,
                     password,
                     ssl_type,
                     ssl_cipher,
                     x509_issuer,
                     x509_subject,
                     max_questions,
                     max_updates,
                     max_user_connections' . ($needAuth ? ', authentication_string' : '') . ')
                VALUES
                    (?,
                     ?,
                     ' . $pwclause . ',
                     ?,
                     ?,
                     ?,
                     ?,
                     ?,
                     ?,
                     ?' . ($needAuth ? ',""' : '') . ');';
            $stmt = $conn->prepare($query);
            $stmt->bind_param('sssssssiii', $host, $user, $password, $ssl, $cipher,
                $issuer, $subject, $maxquery, $maxupdates, $maxconn);
            $stmt->execute();
            if ($stmt->error) {
                return new MySQLError('Invalid query, ' . $stmt->error);
            }
            $conn->query('FLUSH PRIVILEGES;');
            if ($stmt->affected_rows < 1) {
                return error("user creation `%s@%s' failed", $user, $host);
            }

            return true;
        }

        /**
         * Get charset from database
         *
         * @param $db
         * @return null|string
         */
        public function get_database_charset(string $db): ?string
        {
            if ($this->permission_level & (PRIVILEGE_USER|PRIVILEGE_SITE)) {
                $prefix = $this->getServiceValue('mysql', 'dbaseprefix');
                if (0 !== strpos($db, $prefix)) {
                    $db = $prefix . $db;
                }
            }
            if (!\in_array($db, $this->list_databases(), true)) {
                error('Invalid database %s', $db);
                return null;
            }
            $conn = $this->_connect_root();
            $q = "SELECT default_character_set_name FROM information_schema.SCHEMATA 
                WHERE schema_name = '" . $conn->escape_string($db). "';";
            $rs = $conn->query($q);

            if (!$rs->num_rows) {
                return null;
            }
            return $rs->fetch_object()->default_character_set_name;
        }

        /**
         * Create a new mysql database
         *
         * @param  string $db
         * @param  string $charset   optional default charset
         * @param  string $collation optional default collation
         * @return bool  creation succeeded
         */

        public function create_database($db, $charset = 'latin1', $collation = 'latin1_swedish_ci')
        {
            if (!IS_CLI) {
                return $this->query('mysql_create_database', $db, $charset, $collation);
            }

            $charset = strtolower($charset);
            $collation = strtolower($collation);

            if (!preg_match(Regex::SQL_DATABASE, $db)) {
                return error("invalid database name `%s'", $db);
            }
            if (!$this->charset_valid($charset)) {
                return error("unrecognized mysql charset `%s'", $charset);
            }
            if (!$this->collation_valid($collation)) {
                return error("invalid mysql collation `%s'", $collation);
            } else if (!$this->collation_compatible($collation, $charset)) {
                warn("collation `%s' for charset `%s' not sensible", $collation, $charset);
            }

            $prefix = $this->get_prefix();

            // db name passed without prefix
            if (0 !== strpos($db, $prefix)) {
                $db = $prefix . $db;
            }

            if ($this->database_exists($db)) {
                return error("database `$db' exists");
            }

            if (null !== ($limit = $this->getConfig('mysql', 'dbasenum', null)) && $limit >= 0) {
                $count = \count($this->list_databases());
                if ($count >= $limit) {
                    return error("Database limit `%d' reached - cannot create additional databases", $limit);
                }
            }

            $status = $this->query('mysql_create_database_backend', $db, $charset, $collation);
            if (!$status) {
                return $status;
            }

            $conn = new mysqli('localhost', self::MASTER_USER, $this->_get_elevated_password());
            $conn->select_db('mysql');
            $conn->query('GRANT ALL ON `' . $db . "`.* to '" . $conn->escape_string($this->username) . "'@localhost;");
            if ($conn->error) {
                \Opcenter\Database\MySQL::dropDatabase($db);

                return error("failed to create db `%s'. Error while applying grants: `%s' " .
                    "- is control user `%s' missing?",
                    $db,
                    $conn->error,
                    $this->username
                );
            }

            return info("created database `%s'", $db);

        }

        public function charset_valid($charset): bool
        {
            $charset = strtolower($charset);
            $charsets = $this->get_supported_charsets();

            return array_key_exists($charset, $charsets);
        }

        public function get_supported_charsets(): array
        {
            $cache = Cache_Global::spawn();
            $key = 's:mysql.char';
            $charsets = $cache->get($key);
            if ($charsets) {
                return $charsets;
            }
            $db = MySQL::initialize();
            $rs = $db->query('SELECT CHARACTER_SET_NAME AS charset, DESCRIPTION AS `desc` FROM INFORMATION_SCHEMA.character_sets');
            $charsets = array();
            while (null !== ($row = $rs->fetch_object())) {
                $charsets[$row->charset] = $row->desc;
            }
            $cache->set($key, $charsets);

            return $charsets;
        }

        /**
         * Validate collation name
         *
         * @param string $collation
         * @return bool
         */
        public function collation_valid($collation): bool
        {
            $collations = $this->get_supported_collations();
            $collation = strtolower($collation);
            foreach ($collations as $c) {
                if ($c['collation'] === $collation) {
                    return true;
                }
            }

            return false;
        }

        public function get_supported_collations()
        {
            $cache = Cache_Global::spawn();
            $key = 's:mysql.coll';
            $collations = $cache->get($key);
            if ($collations) {
                return $collations;
            }
            $collations = [];
            $db = MySQL::initialize();
            $q = 'SELECT collation_name, character_set_name FROM ' .
                "INFORMATION_SCHEMA.collations WHERE is_compiled = 'Yes'";
            $rs = $db->query($q);
            if (!$rs) {
                return $collations;
            }

            while (null !== ($row = $rs->fetch_object())) {
                $collations[] = array(
                    'collation' => $row->collation_name,
                    'charset'   => $row->character_set_name
                );
            }
            $cache->set($key, $collations);

            return $collations;
        }

        /**
         * Verify collation + charset combination are compatible
         *
         * @param string $collation
         * @param string $charset
         *
         * @return bool
         */
        public function collation_compatible($collation, $charset): bool
        {
            $db = MySQL::initialize();
            $q = 'SELECT 1 FROM INFORMATION_SCHEMA.COLLATION_CHARACTER_SET_APPLICABILITY ' .
                "WHERE collation_name = '" . $db->escape($collation) . "' AND " .
                "character_set_name = '" . $db->escape($charset) . "'";
            $rs = $db->query($q);
            if (!$rs) {
                return false;
            }

            return $rs->num_rows > 0;
        }

        /**
         * Query information_schema for existence of MySQL database
         *
         * @param  string $db database name
         * @return bool
         */
        public function database_exists($db): bool
        {
            if (!IS_CLI) {
                return $this->query('mysql_database_exists', $db);
            }
            if (!$db) {
                return false;
            }
            $prefix = '';
            if ($this->permission_level & (PRIVILEGE_SITE | PRIVILEGE_USER)) {
                $sqlroot = $this->domain_shadow_path() . self::MYSQL_DATADIR;
                $normal = \Opcenter\Database\MySQL::canonicalize($db);
                $prefix = $this->get_prefix();
                if (!file_exists($sqlroot . '/' . $normal)) {
                    // tut-tut. Resolve db with prefix in mind
                    $db = $prefix . $db;
                }
            }
            if (\Opcenter\Database\MySQL::databaseExists($db)) {
                return true;
            } else if ($this->permission_level & PRIVILEGE_ADMIN) {
                // used by db backup routine, in future the task should be
                // removed from backup, but leave this as it is for now
                return false;
            }
            $user = $this->getConfig('mysql', 'dbaseadmin');
            // double prefix, remove first prefix, then check one last time
            if (0 === strpos($db, $prefix . $prefix)) {
                $db = (string)substr($db, strlen($prefix));
            }
            return \Opcenter\Database\MySQL::databaseExists($db, $user);
        }

        /**
         * bool create_mysql_database_backend (string)
         * {@link create_mysql_database}
         */
        public function create_database_backend($db, $charset, $collation)
        {
            $dboptData = 'default-character-set=' . $charset . "\n" .
                'default-collation=' . $collation;
            /**
             * use shadow/ on OverlayFS platforms too. mysqldump
             * communicates with mysqld to dump tables, so there's
             * no risk of ghosting as seen if we write directly to shadow/
             * and query from the composite path fst/
             */
            $path = $this->domain_shadow_path();
            if (!Opcenter\Database\MySQL::prepBackend($path, $db)) {
                return error('Failed to prepare database backend storage');
            }

            $fp = fopen($path . '/db.opt', 'w');
            fwrite($fp, $dboptData);
            fclose($fp);
            chown($path . '/db.opt', 'mysql');
            chgrp($path . '/db.opt', (int)$this->group_id);

            return file_exists(self::MYSQL_DATADIR . '/' . Opcenter\Database\MySQL::canonicalize($db)) && file_exists($path);
        }

        /**
         * bool add_mysql_user_permissions (string, string, string, array)
         *
         * @deprecated
         * @see Mysql_Module::set_privileges()
         *
         * @param string $user
         * @param string $host
         * @param string $db
         * @param array  $opts
         * @return bool
         */
        public function add_user_permissions($user, $host, $db, array $opts)
        {
            deprecated_func('use set_mysql_privileges()');

            return $this->set_privileges($user, $host, $db, $opts);
        }

        /**
         * Set grants for a MySQL user
         *
         * @param string $user
         * @param string $host
         * @param string $db name or '%' for all
         * @param array  $privileges
         * @return bool
         */
        public function set_privileges(string $user, string $host, string $db, array $privileges): bool
        {
            if (!$host) {
                return error("invalid hostname `$host'");
            }

            $privileges = array_change_key_case($privileges);
            $prefix = $this->get_prefix();
            if ($user != $this->getServiceValue('mysql', 'dbaseadmin') &&
                strncmp($user, $prefix, strlen($prefix))
            ) {
                $user = $prefix . $user;
            }
            if ($user != $this->username && !preg_match('/^' . $prefix . '/', $user)) {
                return error("invalid user `%s'", $user);
            }
            $conn = new mysqli('localhost', self::MASTER_USER, $this->_get_elevated_password());
            $conn->select_db('mysql');
            /** ignore prefixed dbs as they should have ownership rights */
            if ($db === '%') {
                if ($user === $this->getConfig('mysql', 'dbaseadmin')) {
                    return warn('User %s already has permission to all databases - ignoring', $this->getConfig('mysql', 'dbaseadmin'));
                }
                // _ is escaped later on
                $db = $prefix . '%';
            } else if (0 === strpos($db, $prefix)) {
                $rs = $conn->query("SELECT 1 FROM db WHERE user = '" . $this->username . "' AND db = '" . $db . "'");
                if ($rs->num_rows < 1) {
                    return error("No grants found in database on `%s' for user `%s'", $db, $this->username);
                }
            }

            $valid_opts = array(
                'select'           => false,
                'insert'           => false,
                'update'           => false,
                'delete'           => false,
                'create'           => false,
                'drop'             => false,
                'grant'            => false,
                'references'       => false,
                'index'            => false,
                'alter'            => false,
                'create_tmp_table' => false,
                'show_view'        => false,
                'create_view'      => false,
                'create_routine'   => false,
                'alter_routine'    => false,
                'lock_tables'      => false,
                'execute'          => false,
                'event'            => false,
                'trigger'          => false
            );

            if (count($privileges) <= 2 && (isset($privileges['read']) || isset($privileges['write']))) {
                // simplified mode
                $tmp = array();
                if (!empty($privileges['read'])) {
                    $tmp['select'] = $tmp['show_view'] = $tmp['execute'] = true;
                }

                if (!empty($privileges['write'])) {
                    $write = array_diff(array_keys($valid_opts), array('select', 'show_view', 'execute'));
                    $tmp2 = array_fill_keys($write, true);
                    $tmp = array_merge($tmp, $tmp2);
                }
                $privileges = $tmp;
            }

            $opts_copy = $valid_opts;
            foreach ($valid_opts as $opt => $enabled) {
                if (isset($privileges[($opt)]) && $privileges[$opt]) {
                    $valid_opts[$opt] = $opt . '_priv';
                } else {
                    unset($valid_opts[$opt]);
                }
            }

            $revoke_opts = array_diff_key($opts_copy, $valid_opts);
            foreach (array_keys($opts_copy) as $name) {
                $opts[] = (isset($valid_opts[$name])) ? 'Y' : 'N';
            }

            array_walk($opts_copy, static function (&$key, $val) {
                $key = $val . '_priv';
            });
            if ($db !== $prefix . '%') {
                $rs = $conn->query("SELECT db FROM db WHERE user = '" . $user . "' AND host = '" . $host . "' AND db = '" . str_replace('_', '\\_', $prefix) . '%' . "'");
                if ($rs->num_rows > 0) {
                    return error('User %s@%s has wildcard grants applied. Per-database grants cannot be applied over wildcard grant. User may only be deleted.', $user, $host);
                }
            }
            $conn->query('REPLACE INTO db (' . implode(', ',
                    $opts_copy) . ", `host`, `db`, `user`) VALUES ('" . implode("', '", $opts) .
                    "', '" . $host . "', '" . str_replace('_', '\\_', $db) . "', '" . $user . "');");
            $ar = $conn->affected_rows;

            if ($conn->error) {
                return error('Error when applying grants, ' . $conn->error);
            }

            $conn->query('FLUSH PRIVILEGES;');

            return $ar > 0;
        }

        /**
         *
         * @deprecated
         * @see Mysql_Module::revoke_privileges()
         */
        public function delete_user_permissions($user, $host, $db)
        {
            deprecated_func('use revoke_from_mysql_db()');

            return $this->revoke_privileges($user, $host, $db);
        }

        /**
         * Revoke all privileges on a database from a MySQL user
         *
         * @param string $user
         * @param string $host
         * @param string $db
         * @return bool
         */
        public function revoke_privileges($user, $host, $db)
        {
            $prefix = $this->get_prefix();
            if ($user != $this->getServiceValue('mysql', 'dbaseadmin') &&
                strncmp($user, $prefix, strlen($prefix))
            ) {
                $user = $prefix . $user;
            }
            if ($user != $this->username && !preg_match('/^' . $prefix . '/', $user)) {
                return error("invalid user `$user'");
            }
            $conn = new mysqli('localhost', self::MASTER_USER, $this->_get_elevated_password());
            $conn->select_db('mysql');
            $stmt = $conn->prepare('DELETE FROM db WHERE user = ? AND host = ? AND db = ?');
            $stmt->bind_param('sss', $user, $host, $db);
            $res = $stmt->execute();
            if (!$res) {
                return error('Query error while dropping permissions, ' . $stmt->error);
            }

            $conn->query('FLUSH PRIVILEGES;');

            return $stmt->affected_rows > 0;
        }

        // {{{ enabled()

        public function get_user_permissions($user, $host, $db)
        {
            deprecated_func('use get_privileges()');

            return $this->get_privileges($user, $host, $db);
        }

        // }}}

        /**
         * Get MySQL grants for a user on a database
         *
         * @param string $user
         * @param string $host
         * @param string $db
         * @return array
         */
        public function get_privileges($user, $host, $db)
        {
            $prefix = $this->get_prefix();
            if ($user != $this->getServiceValue('mysql', 'dbaseadmin') &&
                strncmp($user, $prefix, strlen($prefix))
            ) {
                $user = $prefix . $user;
            }
            $conn = new mysqli('localhost', self::MASTER_USER, $this->_get_elevated_password());
            $conn->select_db('mysql');

            $stmt = $conn->prepare('SELECT Select_priv, Insert_priv, Update_priv, DELETE_PRIV,
                                     CREATE_PRIV, DROP_PRIV, GRANT_PRIV, REFERENCES_PRIV,
                                     INDEX_PRIV, ALTER_PRIV, CREATE_TMP_TABLE_PRIV,
                                     LOCK_TABLES_PRIV, CREATE_VIEW_PRIV, SHOW_VIEW_PRIV,
                                     CREATE_ROUTINE_PRIV, ALTER_ROUTINE_PRIV, EXECUTE_PRIV,
                                     EVENT_PRIV, TRIGGER_PRIV FROM db WHERE user = ? AND db IN (?,?,?) AND host = ?');
            $dbSafe = str_replace('_', '\\_', $db);
            $wcSafe = str_replace('_', '\\_', $prefix . '%');
            $stmt->bind_param('sssss', $user, $db, $dbSafe, $wcSafe, $host);
            $stmt->execute();
            $select = $insert = $update = $delete = $create = $drop = $domain =
            $grant = $references = $index = $alter = $create_tmp_table =
            $lock_tables = $create_view = $show_view = $create_routine =
            $alter_routine = $execute = $event = $trigger = null;
            $stmt->bind_result($select, $insert, $update, $delete, $create, $drop, $grant,
                $references, $index, $alter, $create_tmp_table, $lock_tables,
                $create_view, $show_view, $create_routine, $alter_routine,
                $execute, $event, $trigger);

            if ($stmt->fetch()) {
                $priv = array(
                    'select'           => $select,
                    'insert'           => $insert,
                    'update'           => $update,
                    'delete'           => $delete,
                    'create'           => $create,
                    'drop'             => $drop,
                    'grant'            => $grant,
                    'references'       => $references,
                    'index'            => $index,
                    'alter'            => $alter,
                    'create_tmp_table' => $create_tmp_table,
                    'lock_tables'      => $lock_tables,
                    'create_view'      => $create_view,
                    'show_view'        => $show_view,
                    'create_routine'   => $create_routine,
                    'alter_routine'    => $alter_routine,
                    'execute'          => $execute,
                    'trigger'          => $trigger,
                    'event'            => $event
                );
                array_walk($priv, static function (&$key, &$val) {
                    $key = $key == 'Y';
                });
                $stmt->close();
            } else {
                $priv = array(
                    'select'           => false,
                    'insert'           => false,
                    'update'           => false,
                    'delete'           => false,
                    'create'           => false,
                    'drop'             => false,
                    'grant'            => false,
                    'references'       => false,
                    'index'            => false,
                    'alter'            => false,
                    'create_tmp_table' => false,
                    'lock_tables'      => false,
                    'create_view'      => false,
                    'show_view'        => false,
                    'create_routine'   => false,
                    'alter_routine'    => false,
                    'execute'          => false,
                );
            }
            return $priv;
        }

        /**
         * Returns the version of the MySQL server as an integer
         *
         * The form of this version number is
         * main_version * 10000 + minor_version * 100 + sub_version
         * (i.e. version 4.1.0 is 40100)
         *
         * @param $pretty bool pretty-print version
         *
         * @return int|string integer representing the server version or string
         */
        public function version($pretty = false)
        {
            $version = \Opcenter\Database\MySQL::version();
            if (!$pretty) {
                return $version;
            }

            $mysqlver = array();
            foreach (array('patch', 'minor', 'major') as $v) {
                $mysqlver[$v] = $version % 100;
                $version /= 100;
            }

            return $mysqlver['major'] . '.' . $mysqlver['minor'] . '.' .
                $mysqlver['patch'];

        }

        /**
         * Delete MySQL database from system
         *
         * @param  string $db database
         * @return bool
         */
        public function delete_database($db)
        {
            $db = str_replace('\\\\', '\\', $db);
            $prefix = $this->get_prefix();
            if (!$prefix) {
                report('Prefixless site - bug');

                return false;
            }
            $prefixwc = str_replace('_', '\_', $prefix) . '%';
            $conn = new mysqli('localhost', self::MASTER_USER, $this->_get_elevated_password());
            $conn->select_db('mysql');
            $stmt = $conn->prepare('SELECT user FROM db WHERE (user = ? OR db LIKE ?) AND db = ?');
            $stmt->bind_param('sss', $this->username, $prefixwc, $db);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows < 1) {
                $stmt->free_result();
                // db name passed without prefix, db not found,
                // don't coerce db to prefix + db unless db deletion failed
                if (strncmp($db, $prefix, strlen($prefix))) {
                    $db = $prefix . $db;

                    return $this->delete_database($db);
                }

                return error("Unknown database `%s'", $db);
            }
            $stmt->free_result();
            $this->query('mysql_assert_permissions');

            \Opcenter\Database\MySQL::dropDatabaseGrants($db);
            // FLUSH is necessary, because MySQL will permit a separate CREATE DATABASE
            // query by the former owner bypassing this requirement
            // (it also bypasses filesystem namespacing + quota attribution)
            \Opcenter\Database\MySQL::flush();
            \Opcenter\Database\MySQL::dropDatabase($db);

            $this->query('mysql_delete_database_backend', $db);

            $this->delete_backup($db);


            if ($conn->error) {
                return error("error while removing database `$db' - " . $conn->error);
            }

            return true;
        }

        /**
         * Remove MySQL Backup
         *
         * @param string $db
         * @return bool
         */
        public function delete_backup($db)
        {
            return parent::delete_backup_real('mysql', $db);
        }

        /**
         * Ensure that /var/lib/mysql/ has mysql:<group id> ownership
         */
        public function assert_permissions()
        {
            if (!file_exists($this->domain_fs_path() . self::MYSQL_DATADIR)) {
                return false;
            }

            chown($this->domain_fs_path() . self::MYSQL_DATADIR, 'mysql');
            chgrp($this->domain_fs_path() . self::MYSQL_DATADIR, $this->group_id);

            return true;
        }

        public function delete_database_backend($db)
        {
            $db = \Opcenter\Database\MySQL::canonicalize($db);
            if (is_link(self::MYSQL_DATADIR . '/' . $db)) {
                unlink(self::MYSQL_DATADIR . '/' . $db);
            }

            return true;

        }

        /**
         * bool edit_mysql_user(string, string, array)
         * Note when calling through SOAP, all options must be given, otherwise
         * the will default to server preferences.
         *
         * @param string $user user
         * @param string $host hostname
         * @param array  $opts array of options, valid indexes:
         *                     host
         *                     password
         *                     max_user_connections
         *                     max_updates
         *                     max_questions
         *                     use_ssl
         *                     cipher_type
         *                     ssl_cipher
         *                     x509_subject
         *                     x509_issuer
         * @return bool query succeeded
         */
        public function edit_user(string $user, string $host, array $opts): bool
        {
            if (!IS_CLI) {
                return $this->query('mysql_edit_user', $user, $host, $opts);
            }
            $prefix = $this->get_prefix();
            if ($user !== $this->getServiceValue('mysql', 'dbaseadmin') && 0 !== strpos($user, $prefix)) {
                $user = $prefix . $user;
            }
            if (!is_array($opts)) {
                return error('Options must be an array');
            }
            if (isset($opts['cipher_type'])) {
                $opts['cipher_type'] = strtoupper($opts['cipher_type']);
                if ($opts['cipher_type'] != '' && $opts['cipher_type'] != 'ANY' &&
                    $opts['cipher_type'] != 'SPECIFIED' && $opts['cipher_type'] != 'X509'
                ) {
                    return error('Invalid cipher type');
                }
            }
            if (isset($opts['host']) && $opts['host'] != 'localhost') {

                if (!IpCommon::valid($opts['host']) && !preg_match(Regex::SQL_MYSQL_IP_WILDCARD, $opts['host'])) {
                    return error("rejected host `%s': only numeric IP addresses are permitted, not hostnames",
                        $opts['host']);
                }
            }

            $defaults = array(
                'host'                 => $host,
                'password'             => null,
                'max_user_connections' => self::DEFAULT_CONCURRENCY_LIMIT,
                'max_updates'          => 0,
                'max_questions'        => 0,
                'use_ssl'              => false,
                'cipher_type'          => '',
                'ssl_cipher'           => '',
                'x509_subject'         => '',
                'x509_issuer'          => ''
            );

            // make copy to check for max_user_connections change
            // later in event of password update
            $mergeopts = $opts;
            foreach ($defaults as $def_nam => $def_val) {
                if (!isset($mergeopts[$def_nam])) {
                    $mergeopts[$def_nam] = $def_val;
                }
            }
            /** if we're not using SSL, blank it out */
            if (!$mergeopts['use_ssl']) {
                $mergeopts['x509_subject'] = $mergeopts['x509_issuer'] = $mergeopts['ssl_cipher'] = $mergeopts['cipher_type'] = '';
            } else {
                $mergeopts['cipher_type'] = 'ANY';
            }

            if ($mergeopts['max_user_connections'] < 1) {
                $mergeopts['max_user_connections'] = self::DEFAULT_CONCURRENCY_LIMIT;
            }

            if ($mergeopts['max_questions'] < 0 || $mergeopts['max_updates'] < 0) {
                return error('Max queries and updates must be greater than 0');
            }
            if (isset($opts['max_user_connections']) && $opts['max_user_connections'] > static::MAX_CONCURRENCY_LIMIT) {
                return error('Max connection limit %d. Must file a ticket justifying need. ' .
                    'Check index placements first.', static::MAX_CONCURRENCY_LIMIT);
            }
            if (!is_null($mergeopts['password']) && strlen($mergeopts['password']) < self::MIN_PASSWORD_LENGTH) {
                return error('password must be at least %d characters long', self::MIN_PASSWORD_LENGTH);
            }

            $conn = $this->_connect_root();

            $stmt = $conn->prepare('SELECT user FROM user WHERE user = ? AND host = ?');
            $stmt->bind_param('ss', $user, $host);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows < 1) {
                $stmt->free_result();
                return error('invalid user@host specified: %s@%s', $user, $host);
            }
            $stmt->free_result();

            if ($host === 'localhost' &&
                $user === $this->getServiceValue('mysql','dbaseadmin') &&
                ($mergeopts['host'] ?: $host) !== $host)
            {
                return error("Cannot modify the hostname attribute for %(user)s on %(host)s", ['user' => $user, 'host' => $host]);
            }

            if (Opcenter\Database\MySQL::version() >= self::NEW_API_VERSION) {
                $params = [
                    $user,
                    $host,
                    [
                        'ssl'         => $mergeopts['use_ssl'] ?: null,
                        'subject'     => $mergeopts['x509_subject'] ?: null,
                        'issuer'      => $mergeopts['x509_issuer'] ?: null,
                        'ciper'       => $mergeopts['ssl_cipher'] ?: null,
                        'password'    => $mergeopts['password'] ?: null,
                        'connections' => (int)($mergeopts['max_user_connections'] ?: 0),
                        'updates'     => (int)($mergeopts['max_updates'] ?: 0),
                        'query'       => (int)($mergeopts['max_questions'] ?: 0),
                        'host'        => $mergeopts['host'] ?: null
                    ]
                ];
                if (!Opcenter\Database\MySQL::alterUser(...$params)) {
                    return false;
                }
            } else {
                $stmt = $conn->prepare('UPDATE user
                    SET
                        host            = ?,
                        ssl_type        = ?,
                        ssl_cipher      = ?,
                        x509_issuer     = ? ,
                        x509_subject    = ?,
                        max_questions   = ?,
                        max_updates     = ?,
                        max_user_connections = ?
                    WHERE
                            user = ?
                        AND
                            host = ?');

                $stmt->bind_param('sssssiiiss',
                    $mergeopts['host'],
                    $mergeopts['cipher_type'],
                    $mergeopts['ssl_cipher'],
                    $mergeopts['x509_issuer'],
                    $mergeopts['x509_subject'],
                    $mergeopts['max_questions'],
                    $mergeopts['max_updates'],
                    $mergeopts['max_user_connections'],
                    $user,
                    $host
                );
                $stmt->execute();
                if ($stmt->error) {
                    return new MySQLError('Invalid query, ' . $stmt->error);
                }

                if ($mergeopts['host'] !== $defaults['host']) {
                    $stmt = $conn->prepare('UPDATE db SET host = ? WHERE user = ? AND host = ?');
                    $stmt->bind_param('sss', $mergeopts['host'], $user, $defaults['host']);
                    $stmt->execute();
                    if ($stmt->error) {
                        return error('error while updating DB grants, %s', $stmt->error);
                    }
                }
                /** finally update the password if changed */
                if ($mergeopts['password']) {
                    $pwclause = 'password(?)';
                    $password = $mergeopts['password'];
                    // password is encrypted in new pw form or old
                    if ($password[0] == '*' && strlen($password) == 41
                        && ctype_xdigit(substr($password, 1)) ||
                        /** only accept old-style passwords on platforms <v6 */
                        strlen($password) == 16 && ctype_xdigit($password) && version_compare(platform_version(), '6',
                            '<')
                    ) {
                        $pwclause = '?';
                    }
                    $stmt2 = $conn->prepare('UPDATE user SET password = ' . $pwclause . ' WHERE user = ? AND host = ?;');

                    $stmt2->bind_param('sss', $password, $user, $mergeopts['host']);
                    $stmt2->execute();
                    if ($stmt2->error) {
                        return new MySQLError('Query error while updating password, ' . $stmt2->error);
                    }
                }
            }

            $conn->query('FLUSH PRIVILEGES');

            if ($user === $this->username && $mergeopts['password']) {
                $this->set_option('user', $this->username, 'client');
                $this->set_option('password',
                    str_replace(array('"'), array('\"'), $mergeopts['password']),
                    'client'
                );
            }

            return true;
        }

        /**
         * bool service_enabled (string)
         *
         * Checks to see if a service is enabled
         *
         * @deprecated
         * @see Mysql_Module::enabled()
         * @return bool
         */
        public function service_enabled()
        {
            deprecated('use enabled()');

            return $this->enabled();
        }

        /**
         * MySQL/PostgreSQL service enabled on account
         *
         * Checks to see if either MySQL or PostgreSQL is enabled on an account
         *
         * @return bool
         */
        public function enabled()
        {
            return parent::svc_enabled('mysql');
        }

        public function truncate_database($db)
        {

            return $this->_mysql_empty_truncate_wrapper($db, 'truncate');
        }

        private function _mysql_empty_truncate_wrapper($db, $mode)
        {
            if ($mode != 'truncate' && $mode != 'empty') {
                return error("unknown mode `%s'", $mode);
            }
            if ($mode == 'empty') {
                // semantically more correct
                $mode = 'drop';
            }

            $prefix = $this->getServiceValue('mysql', 'dbaseprefix');
            if (0 !== strpos($db, $prefix)) {
                $db = $prefix . $db;
            }

            if (!$this->database_exists($db)) {
                return error("unknown database, `%s'", $db);
            }

            $user = $this->_create_temp_user($db);
            if (!$user) {
                return error("failed to %s db `%s'", $mode, $db);
            }
            $conn = new mysqli('localhost', $user);
            $conn->set_charset('utf8mb4');
            if (!$conn->select_db($db)) {
                return error("unable to establish db connection for user `%s' on db `%s'", $user, $db);
            }

            $conn->query('SET FOREIGN_KEY_CHECKS=0');

            $q = "SELECT CONCAT('" . strtoupper($mode) . " TABLE ','`', table_schema,'`','.','`',TABLE_NAME,'`', ';') 
                      FROM INFORMATION_SCHEMA.TABLES where  table_schema in ('" . $conn->escape_string($db) . "');";
            $res = $conn->query($q);
            while (null !== ($rs = $res->fetch_row())) {
                if (!$conn->query($rs[0])) {
                    warn("failed to %s table `%s'", $mode, $rs[0]);
                }
            }

            $conn->query('SET @@FOREIGN_KEY_CHECKS=1;');
            if (!$res) {
                return error("%s failed on database `%s': `%s'", $mode, $db, $conn->error);
            }
            $this->_delete_temp_user($user);

            return true;
        }

        /**
         * Database is empty
         *
         * @param $db
         * @return bool
         */
        public function empty($db) {
            if (!$this->database_exists($db)) {
                return true;
            }

            return \count(\Opcenter\Database\MySQL::getTablesFromDatabase($db)) === 0;
        }

        public function empty_database($db)
        {
            return $this->_mysql_empty_truncate_wrapper($db, 'empty');
        }

        /**
         * Export a MySQL database
         *
         * @param string      $db
         * @param string|null $file optional filename
         * @return mixed path of export or false on failure
         */
        public function export($db, $file = null)
        {
            if (!IS_CLI) {
                return $this->query('mysql_export', $db, $file);
            }

            if (is_null($file)) {
                $file = $db . '.sql';
            }
            if (!in_array($db, $this->list_databases(), true)) {
                return error('Invalid database ' . $db);
            }
            if ($file[0] !== '/' && $file[0] !== '.' && $file[0] !== '~') {
                $file = '/tmp/' . $file;
            }
            $pdir = dirname($file);
            if (!$this->file_exists($pdir) && !$this->file_create_directory($pdir, 0755, true)) {
                return error("failed to create parent directory, `%s'", $pdir);
            }
            $path = $this->file_make_path($file);
            if (!$path) {
                return error("invalid file `%s'", $file);
            }

            if (file_exists($path) &&
                (filesize($path) > 0 || realpath($path) !== $path || fileowner($path) < USER_MIN_UID))
            {
                return error('%s: file exists, cannot overwrite', $file);
            }
            $user = $this->_create_temp_user($db);
            $cmd = 'umask 077 && ' . self::EXPORT_CMD . ' -u %s %s > %s';
            if (!$user) {
                $user = self::MASTER_USER;
                $rootpw = escapeshellarg($this->_get_elevated_password());
                $cmd = str_replace('-u %s', '-u %s -p' . $rootpw, $cmd);
            }

            $fsizelimit = Util_Ulimit::get('fsize');
            if ($this->get_database_size($db) > $fsizelimit / self::DB_BIN2TXT_MULT) {
                // make sure ulimit accommodates the db dump
                Util_Ulimit::set('fsize', 'unlimited');
            } else {
                // no need to change this then
                $fsizelimit = null;
            }
            $proc = new Util_Process_Safe();
            // gid must come first
            $proc->setSgid($this->group_id);
            $proc->setSuid($this->user_id);
            $proc->setPriority(19);

            $status = $proc->run($cmd,
                $user,
                $db,
                $path
            );

            if ($user != self::MASTER_USER) {
                $this->_delete_temp_user($user);
            }

            if (!is_null($fsizelimit)) {
                Util_Ulimit::set('fsize', $fsizelimit);
            }

            if (!$status['success'] || !file_exists($path)) {
                return error('export failed: %s', $status['stderr']);
            }

            if (!$status['success']) {
                return error('export failed: %s', $status['stderr']);
            }

            return $this->file_unmake_path($path);
        }

        /**
         * Clone a database
         *
         * @param string $from source database
         * @param string $to   target database
         * @return bool
         */
        public function clone(string $from, string $to): bool
        {
            if ($this->database_exists($to) && !$this->empty($to)) {
                return error("Database `%s' already exists", $to);
            }
            if (!$this->database_exists($from)) {
                return error("Database `%s' does not exist", $from);
            }
            if (!$this->database_exists($to) && !$this->create_database($to)) {
                return false;
            }
            $pipe = $this->export_pipe($from);
            defer($_, static function () use ($pipe) {
                if (file_exists($pipe)) {
                    unlink($pipe);
                }
            });
            return $this->import($to, $this->file_unmake_path($pipe));
        }

        // {{{ delete_mysql_backup()

        /**
         * Get disk space occupied by database
         *
         * @param string $db database name
         * @return int storage in bytes
         */
        public function get_database_size($db)
        {
            if (!IS_CLI) {
                $resp = $this->query('mysql_get_database_size', $db);

                return (int)$resp;
            }

            // mysql type
            $dir = self::MYSQL_DATADIR . '/' . \Opcenter\Database\MySQL::canonicalize($db);
            // database created as directory in /var/lib/mysql
            // instead of under fst
            if (($this->permission_level & (PRIVILEGE_SITE | PRIVILEGE_USER)) && !is_link($dir)) {
                $this->_move_db($db);
            }
            if (!file_exists($dir) || (is_link($dir) && !readlink($dir))) {
                warn($db . ': database does not exist');

                return 0;
            }

            $space = 0;
            $dh = opendir($dir);
            if (!$dh) {
                error("failed to open database directory `%s'", $dir);

                return 0;
            }
            while (($file = readdir($dh)) !== false) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                $space += filesize($dir . '/' . $file);
            }
            closedir($dh);

            return $space;
        }

        // }}}

        private function _move_db($db)
        {

            /**
             * make sure the DB is accessed by the correct user
             * otherwise the DB will be relocated under the caller's fs
             */
            $prefix = $this->getServiceValue('mysql', 'dbaseadmin');
            if (strncmp($db, $prefix, strlen($prefix))) {
                return true;
            }
            $dbfs = \Opcenter\Database\MySQL::canonicalize($db);
            $src = self::MYSQL_DATADIR . '/' . $dbfs;
            $dest = $this->domain_fs_path() . self::MYSQL_DATADIR . '/' . $dbfs;
            if (is_dir($dest)) {
                report('dest db exists - %s', $dest);

                return false;
            }
            \Opcenter\Filesystem::mkdir($dest, 'mysql', $this->group_id, 02750);
            /* a read lock should be used in this situation to ensure
             * absolutely no data is lost in the process
             * only a global flush tables would work, but this can
             * cause a 15+ second hang while tables are flushed
             * as a consequence, forgo the read lock and just move the files
             *
             * this process is also quicker than an export/import routine
             */

            $dh = opendir($src);
            if (!$dh) {
                return error("could not relocate database `%s'", $db);
            }

            while (false !== ($file = readdir($dh))) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                rename($src . '/' . $file, $dest . '/' . $file);
                chown($dest . '/' . $file, 'mysql');
                chgrp($dest . '/' . $file, $this->group_id);
            }

            rmdir($src);
            symlink($dest, $src);
            warn("database `%s' relocated under account filesystem root", $db);
            $db = $this->_connect_root();
            $db->query('FLUSH TABLES');

            return true;
        }
        // }}}

        // {{{ get_mysql_backup_config()

        /**
         * Export a db to a named pipe for immediate download
         *
         * @param $db
         * @return bool|void
         */
        public function export_pipe($db)
        {
            if (version_compare(platform_version(), '4.5', '<=')) {
                return error('platform version too old to support download feature');
            }

            $dbs = $this->list_databases();
            if (!\in_array($db, $dbs, true)) {
                $originalDb = $db;
                $db = $this->get_prefix() . $db;
                if (!\in_array($db, $dbs, true)) {
                    return error('Invalid database %s', $originalDb);
                }
            }

            $user = $this->_create_temp_user($db);

            return $this->query('mysql_export_pipe_real', $db, $user);
        }

        // }}}

        // {{{ get_mysql_backup_config()

        /**
         * Export a database to a named pipe
         *
         * Differs from export_pipe in that it may only be called internally
         * or from backend, no API access
         *
         * @param $db
         * @param $user if empty use superuser
         * @return bool|string|void
         */
        public function export_pipe_real($db, $user)
        {
            if (!IS_CLI) {
                return $this->query('mysql_export_pipe_real', $db, $user);
            }


            // automatically cleaned up on exit()/destruct

            $cmd = self::EXPORT_CMD . ' -u %s %s -r%s';
            if (!$user) {
                $user = self::MASTER_USER;
                $rootpw = escapeshellarg($this->_get_elevated_password());
                $cmd = str_replace('-u %s', '-u %s --password=' . $rootpw, $cmd);
            }

            // @XXX potential race condition
            $fifo = tempnam($this->domain_fs_path('/tmp'), 'id-' . $this->site);
            unlink($fifo);
            if (!posix_mkfifo($fifo, 0600)) {
                return error('failed to ready pipe for export');
            }
            chown($fifo, File_Module::UPLOAD_UID);
            $proc = new Util_Process_Fork();

            // lowest priority
            $proc->setPriority(19);
            $proc->setUser(APNSCP_SYSTEM_USER);

            $status = $proc->run($cmd,
                $user,
                $db,
                $fifo
            );

            if (!$status['success'] || !file_exists($fifo)) {
                return error('export failed: %s', $status['stderr']);
            }
            register_shutdown_function(static function () use ($fifo) {
                if (file_exists($fifo)) {
                    unlink($fifo);
                }

            });

            return $fifo;
        }

        // }}}

        /**
         * int get_mysql_uptime
         *
         * @return int time in seconds
         */
        public function get_uptime(): int
        {
            $db = MySQL::initialize();

            return $db->query("SHOW status LIKE 'uptime'")->fetch_object()->value;

        }

        // {{{ mysql_database_exists()

        public function add_backup($db, $extension = 'zip', $span = 5, $preserve = '0', $email = '')
        {
            return parent::add_backup_real('mysql', $db, $extension, $span, $preserve, $email);
        }

        public function edit_backup($db, $extension, $span = '0', $preserve = '0', $email = '')
        {
            return $this->edit_backup_real('mysql', $db, $extension, $span, $preserve, $email);
        }

        public function list_backups()
        {
            return parent::list_backups_real('mysql');
        }

        /**
         * Fetch MySQL backup task information
         *
         * span   => (integer) days between backups
         * hold   => (integer) number of backups to preserve
         * next   => (integer) unix timestamp of next backup
         * ext    => (string)  extension of backup
         * email  => (string)  notify address after backup
         *
         * @param string $db database name
         * @return array
         */
        public function get_backup_config($db)
        {
            return parent::get_backup_config_real('mysql', $db);
        }

        public function repair_database($db)
        {
            if (!IS_CLI) {
                return $this->query('mysql_repair_database', $db);
            }

            if (!$this->database_exists($db)) {
                return error("unknown database `%s'", $db);
            }

            $sqlroot = $this->domain_fs_path() . self::MYSQL_DATADIR;
            if (!file_exists($sqlroot . '/' . $db)) {
                // tut-tut. Resolve db with prefix in mind
                $prefix = $this->get_prefix();
                $db = $prefix . $db;
            }
            // make sure there are tables in this database to actually check...
            $files = glob($sqlroot . '/' . $db . '/*');
            if (count($files) < 2) {
                return true;
            }

            // negotiate to use mysqlcheck or myisamchk
            $quota = $this->site_get_account_quota();
            $conn = $this->_connect_root();
            $q = 'SELECT MAX(Data_length) AS max FROM ' .
                "information_schema.tables WHERE table_schema = '" .
                $conn->real_escape_string($db) . "'";
            $rs = $conn->query($q);
            $row = $rs->fetch_object();
            $tblsz = $row->max / 1024 * 1.25; //working room

            $qfree = $quota['qhard'] - $quota['qused'];
            $cmd = 'env HOME=/root mysqlcheck --auto-repair %s';
            if ($tblsz > $qfree) {
                warn('not enough storage to safely use mysqlcheck (need %d KB have %d KB free): reverting to direct IO',
                    $tblsz, $qfree
                );
                $cmd = 'myisamchk -r -c ' . $sqlroot . '/%s/*.MYI';
            }
            $fsizelimit = Util_Ulimit::get('fsize');
            Util_Ulimit::set('fsize', 'unlimited');
            $ret = Util_Process_Safe::exec($cmd, array($db), ['mute_stderr' => true]);
            Util_Ulimit::set('fsize', $fsizelimit);
            if (!$ret['success'] && false === strpos($ret['stderr'], "doesn't exist")) {
                return error("`%s' repair failed:\n%s", $db, $ret['stderr']);
            }

            return info("`%s' repair succeeded:\n%s", $db, $ret['output']);
        }

        /**
         * Kill a mysql connection
         *
         * @link mysql_processlist
         * @param integer $id
         * @return bool
         */
        public function kill($id)
        {
            $db = $this->_connect_root();
            $id = intval($id);
            $procs = $this->get_processlist();
            $found = 0;
            foreach ($procs as $p) {
                if ($p['id'] == $id) {
                    $found = 1;
                    break;
                }
            }
            if (!$found) {
                return error("`%d': invalid query id specified", $id);
            }
            $q = "KILL $id";
            $rs = $db->query($q);

            return (bool)$rs;
        }

        /**
         * Get active mysql connections
         *
         *  Array
         *   (
         *      [0] => Array
         *      (
         *          [id] => 11024
         *          [user] => debug
         *          [host] => localhost
         *          [db] => debug
         *          [command] => Query
         *          [state] => User sleep
         *          [info] => select sleep(1000)
         *      )
         *   )
         *
         * @return array
         */
        public function get_processlist()
        {
            $conns = array();
            $db = $this->_connect_root();
            $user = $this->username;
            $prefix = $this->get_prefix();
            $q = 'SELECT id, user, host, db, command, time, state, info FROM ' .
                "information_schema.processlist WHERE user = '" .
                $db->real_escape_string($user) . "' OR user LIKE '" . $db->real_escape_string($prefix) . "%'";
            $rs = $db->query($q);
            while (null != ($row = $rs->fetch_object())) {
                $conns[] = array(
                    'id'      => $row->id,
                    'user'    => $row->user,
                    'host'    => $row->host,
                    'db'      => $row->db,
                    'command' => $row->command,
                    'state'   => $row->state,
                    'info'    => $row->info
                );
            }

            return $conns;
        }

        /**
         * Get basic MySQL server statistics
         *
         * @return array
         */
        public function stats(): array {
            $conn = \MySQL::initialize();
            $vars = [
                'Queries',
                'Uptime',
                'Connections',
                'Questions',
                'TABLE_OPEN_CACHE_HITS',
                'MAX_USED_CONNECTIONS',
                'TABLE_OPEN_CACHE_MISSES',
                'OPENED_FILES',
                'OPENED_TABLES',
                'THREADS_RUNNING',
                'THREADS_CREATED'
            ];

            $fields = implode(',', array_map(static function ($var) use ($conn) {
                return "'$var'";
            }, $vars));
            $rs = $conn->query("SELECT LOWER(variable_name) AS name, variable_value AS val FROM information_schema.global_status WHERE variable_name IN($fields);");

            $items = array_build($rs->fetch_all(\MYSQLI_ASSOC), static function ($k, $v) {
                return [$v['name'], (int)$v['val']];
            });

            $items['observed_queries_per_second'] = null;
            $items['queries_per_second'] = round($items['queries']/$items['uptime'], 4);

            $key = 'mysql.qpslocf';
            $cache = \Cache_Global::spawn();
            if (false !== ($locf = $cache->get($key))) {
                if ($items['uptime'] > $locf[0]) {
                    // check if server reset
                    $items['observed_queries_per_second'] = round(($items['queries'] - $locf[1]) / ($items['uptime'] - $locf[0]), 4);
                    $cache->del($key);
                }
                return $items;
            } else {
                $cache->set($key, [$items['uptime'], $items['queries']]);
            }


            return $items;
        }

        public function _cron(Cronus $c)
        {
            if (!TELEMETRY_ENABLED) {
                return;
            }

            $collector = new Collector(PostgreSQL::pdo());
            $status = $this->stats();
            foreach (MysqlMetrics::getAttributeMap() as $attr => $metric) {
                if (!isset($status[$metric])) {
                    // MariaDB 10.3.20 lacks table cache hits
                    continue;
                }
                $val = $status[$metric];

                if ($val instanceof Closure) {
                    $val = $val($status);
                }
                $collector->add("mysql-${attr}", null, $val);
            }

        }

        /**
         * Get max length of a column in mysql schema
         *
         * @param string $field
         * @return int|null
         */
        public function schema_column_maxlen($field): ?int
        {
            if (!IS_CLI) {
                return $this->query('mysql_schema_column_maxlen', $field);
            }
            if ($field !== 'user' && $field !== 'db') {
                error("unsupported field `%s' requested", $field);
                return null;
            }
            return \Opcenter\Database\MySQL::fieldLength($field);
        }

        public function _delete()
        {
            if (!$this->enabled()) {
                return;
            }
            $conf = $this->getAuthContext()->getAccount()->new;
            if (!parent::uninstallDatabaseService('mysql')) {
                warn("failed to delete mysql service from `%s'", $conf['siteinfo']['domain']);
            }
        }

        public function _create()
        {
            if (version_compare(platform_version(), '7.5', '>=')) {
                return true;
            }
            $conf = $this->getAuthContext()->getAccount()->new;
            if ($conf['mysql']['enabled']) {
                parent::installDatabaseService('mysql');
            }
        }

        public function _edit()
        {
            if (platform_is('7.5')) {
                return true;
            }
            $conf = $this->getAuthContext()->getAccount();
            if ($conf->new['mysql']['enabled'] && !$conf->old['mysql']['enabled']) {
                $this->installDatabaseService('mysql');
            }
        }

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

        public function _create_user(string $user)
        {
        }

        public function _delete_user(string $user)
        {
        }

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