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: 
<?php

    /**
     * Copyright (C) Apis Networks, Inc - All Rights Reserved.
     *
     * Unauthorized copying of this file, via any medium, is
     * strictly prohibited without consent. Any dissemination of
     * material herein is prohibited.
     *
     * For licensing inquiries email <licensing@apisnetworks.com>
     *
     * Written by Matt Saladna <matt@apisnetworks.com>, May 2017
     */

    namespace Module\Support;

    use File_Module;
    use Module\Support\Webapps\App\Loader;
    use Module\Support\Webapps\App\Reconfigurator;
    use Module\Support\Webapps\App\Type\Adhoc\Manifest;
    use Module\Support\Webapps\App\Type\Unknown\Handler as Unknown;
    use Module\Support\Webapps\App\UIPanel;
    use Module\Support\Webapps\Contracts\Webapp;
    use Module\Support\Webapps\Git;
    use Module\Support\Webapps\MetaManager;
    use Module\Support\Webapps\MetaManager\Meta;
    use Opcenter\Blacklist;
    use Opcenter\Filesystem;
    use Opcenter\Versioning;
    use User_Module;
    use Web_Module;
    use Regex;

    /**
     * Class Webapps
     *
     * @todo
     *  - Improved handling of symlinked document roots
     *      Divided into getDocumentRoot/normalizeDocumentRoot()
     *      for web path + real path. Confusing & needs rework.
     *
     *      When installing to symlink'd docroots, metamanager uses referent
     *      path for meta storage. Streamline this.
     *
     * @package Module\Support
     */
    abstract class Webapps extends \Module_Skeleton implements Webapps\Contracts\Webapp
    {
        use \NamespaceUtilitiesTrait;

        const APPLICATION_PREF_KEY = 'webapps.paths';
        const APP_NAME = 'undefined';
        const DEFAULT_VERSION_LOCK = 'none';
        const BANNED_DIRECTIVES = [
            'FollowSymlinks',
            'Includes',
            'All'
        ];

        const LEARNING_DURATION = 60;

        /**
         * List of modes and files
         *
         * @var array
         */
        protected $aclList = [];

        protected static $registeredProviders = [];

        public $exportedFunctions = [
            '*'            => PRIVILEGE_SITE | PRIVILEGE_USER,
            'get_versions' => PRIVILEGE_ALL,
            'is_current'   => PRIVILEGE_ALL,
            'next_version' => PRIVILEGE_ALL
        ];

        public function __construct()
        {
            parent::__construct();
            if (static::blacklisted($this->getAppName())) {
                $this->exportedFunctions = [
                    '*' => PRIVILEGE_NONE
                ];
            }
        }

        /**
         * Merge interface methods
         *
         * @return array
         */
        public function getExportedFunctions(): array
        {
            $base = array_column((new \ReflectionClass(Webapp::class))->getMethods(\ReflectionMethod::IS_PUBLIC), 'name');
            return $this->exportedFunctions + array_fill_keys($base, PRIVILEGE_SITE|PRIVILEGE_USER);
        }


        /**
         * Get webapp name
         *
         * @return null|string
         */
        protected function getAppName(): ?string
        {
            if (static::class === self::class) {
                return null;
            }
            $name = strtolower(static::getBaseClassName());
            $rfxn = new \ReflectionClass($this);
            if ($rfxn->isAnonymous()) {
                // module has callback
                $name = strtolower(static::getBaseClassName($rfxn->getParentClass()->getName()));
            }
            return substr($name, 0, strpos($name, '_'));
        }

        /**
         * Vendor blocked app
         *
         * @param string $app app name
         * @return bool
         */
        public static function blacklisted(string $app): bool
        {
            static $blacklist;

            if (null === $blacklist) {
                $blacklist = (new Blacklist(WEBAPPS_BLACKLIST))->filter(static::allApps());
            }

            return !\in_array($app, $blacklist, true);
        }


        /**
         * All apps known to panel
         *
         * Excludes blacklisted apps. @see knownApps
         *
         * @return array
         */
        public static function allApps(): array
        {
            return array_filter(array_map(static function ($app) {
                return strtolower($app);

            }, Filesystem::readdir(__DIR__ . DIRECTORY_SEPARATOR . 'Webapps' . DIRECTORY_SEPARATOR . 'App' . DIRECTORY_SEPARATOR . 'Type')))
                + append_config(array_keys(self::$registeredProviders));
        }

        /**
         * List known apps, factoring in exclusions
         *
         * @return array
         */
        public static function knownApps(): array
        {
            /**
             * Localize apps per account per featureset in the future?
             */
            $key = 'webapps.applist';
            $cache = \Cache_Global::spawn();
            $apps = $cache->get($key);
            if (!is_debug() && false !== $apps) {
                return $apps;
            }
            $apps = array_filter(static::allApps(),
                static function ($app) {
                    if (static::blacklisted($app)) {
                        return false;
                    }

                    $appclass = self::handlerFromApplication($app);
                    $class = (new \ReflectionClass($appclass))->newInstanceWithoutConstructor();
                    return $class->display();
            });
            asort($apps);
            $cache->set($key, $apps, 300);

            return $apps;
        }

        /**
         * Restrict write-access by the app
         *
         * @param string $hostname
         * @param string $path
         * @param string $mode app-specific mode or magic mode: ['learn', 'write', 'reset']
         * @param array  $args
         * @return bool
         */
        public function fortify(string $hostname, string $path = '', string $mode = 'max', $args = []): bool
        {
            $app = Loader::fromHostname(null, $hostname, $path, $this->getAuthContext());
            if (\in_array($mode, ['learn', 'write', 'reset'], true)) {
                $ret = false;
                switch ($mode) {
                    case 'reset':
                        $ret = $this->file_reset_path($app->getDocumentMetaPath(),
                            array_get($app->getOptions(), 'user', ''), 644,
                            755);
                        break;
                    case 'learn':
                        $docroot = $app->getAppRoot();
                        $owner = array_get($app->getOptions(), 'user', $this->username);
                        if (!$this->file_set_acls($docroot, [
                            $app->getWebUser() => 'rwx',
                            $owner             => 'drwx',
                        ], [\File_Module::ACL_MODE_RECURSIVE])) {
                            return error('failed to open permissions');
                        }

                        $limit = (int)($args[0] ?? static::LEARNING_DURATION);
                        if ($limit < 1 || $limit > 60 * 48) {
                            $limit = 10;
                        }

                        $checkpoint = $this->watch_checkpoint($docroot);
                        if (!$checkpoint) {
                            return error('failed to enable learning mode');
                        }

                        info('Server in learning mode for the next %(duration)d minutes. Use the web site as you normally would. ' .
                            'A report will be sent to %(email)s once learning concludes.',
                            ['duration' => $limit, 'email' => $this->common_get_admin_email()]
                        );

                        $ret = $this->pman_schedule_api_cmd(
                            'watch_batch',
                            [$docroot, $checkpoint],
                            $limit . ' minutes'
                        );

                        break;
                    case 'write':
                        $approot = $app->getAppRoot();
                        $limit = (int)($args[0] ?? 10);
                        if ($limit < 1 || $limit > 60 * 48) {
                            $limit = 10;
                        }

                        if ($this->file_set_acls($approot, [$app->getWebUser() => 'rwx'],
                            [\File_Module::ACL_MODE_RECURSIVE])) {
                            info('web server may write to any files under %(approot)s for the next %(limit)d minutes',
                                compact('approot', 'limit')
                            );
                        }
                        // make sure everything gets chown'd
                        $cmdbatch = array(
                            array('file_chown', array($approot, $this->username, true)),
                        );

                        if ($app->hasFortification()) {
                            // we know how permissions should be setup for this app, change
                            // ownership to fix things
                            $module = $app->getClassMapping();
                            $instance = \apnscpFunctionInterceptor::get_class_from_module($module);
                            if (method_exists($instance, 'fortify')) {
                                $func = $module . '_fortify';
                                $root = $this->web_get_docroot($app->getHostname());
                                $path = (string)$app->getAppRoot();
                                if ($root === $path) {
                                    $pathcomponent = '';
                                } else {
                                    $pathcomponent = substr($approot, \strlen($path));
                                }
                                $cmdbatch[] = array(
                                    $func,
                                    array($hostname, $pathcomponent, $app::DEFAULT_FORTIFICATION)
                                );
                                info('Fortification %(mode)s will be enabled in %(time)d minutes',
                                    ['mode' => $app::DEFAULT_FORTIFICATION, 'time' => $limit]);
                            } else {
                                // this really shouldn't happen unless the web app class is misconfigured
                                warn('A known app without fortification support resides here - you will be ' .
                                    'responsible for opening up permissions to allow write-access ' .
                                    'to whatever folders are necessary in %d minutes once Write Mode is ' .
                                    'disabled', $limit);
                            }
                        } else {
                            $id1 = $this->watch_checkpoint($approot);
                            $cmdbatch[] = array(
                                'watch_batch',
                                array($approot, $id1, 'lock')
                            );
                            warn('an unknown app resides here - files that have changed within the next %d ' .
                                'minutes will be converted to your account. Double-check that all permissions are intact ' .
                                'after %d minutes have elapsed and Write Mode is disabled', $limit, $limit);

                        }

                        $ret = $this->pman_schedule_api_cmd($cmdbatch, $limit . ' minutes');

                        break;

                }

                if ($ret) {
                    $app->setOption('fortify', $mode);
                }

                return $ret;
            }
            $approot = $this->getAppRoot($hostname, $path);
            if (static::class !== \a23r::get_class_from_module('webapp') && (!$approot || !$this->valid($hostname, $path))) {
                return error("path `%(path)s' is not a valid %(app)s install", ['path' => $approot, 'app' => static::APP_NAME]);
            }

            if (null === $this->getACLFiles($mode, $app->getDocumentRoot())) {
                return error("unknown mode `%s'", $mode);
            }
            $username = $this->getDocrootUser($approot);
            // clear everything out
            $this->file_set_acls($approot, null, array(File_Module::ACL_MODE_RECURSIVE));
            $files = $this->mapFilesFromList($this->getACLFiles($mode, $app->getDocumentRoot()), $approot);
            $webuser = $this->web_get_user($hostname, $path);
            $users = array(
                array($webuser => 'drwx'),
                array($webuser => 'rwx'),
                array($username => 'rwx'),
                array($username => 'drwx'),
            );
            $flags = array(
                File_Module::ACL_MODE_RECURSIVE => true,
            );

            // @TODO clobber ownership?
            if (!$this->file_set_acls($files, $users, $flags)) {
                return warn("fortification failed on `%s/%s'", $hostname, $path);
            }

            $app->setOption('fortify', $mode);

            return true;
        }

        /**
         * Convert hostname/path into application root following symlinks
         *
         * @param string $hostname
         * @param string $path
         * @return bool|string
         */
        protected function getAppRoot(string $hostname, string $path = ''): ?string
        {
            if (!($approot = $this->normalizeDocumentRoot($hostname, $path))) {
                return null;
            }
            if (!$stat = $this->file_stat($approot)) {
                // directory doesn't exist yet
                return $approot;
            }

            if ($stat['link']) {
                $approot = $stat['referent'];
            }

            return $approot ?: null;
        }

        /**
         * Get module symbol
         *
         * @return string
         */
        protected function getInternalName(): string
        {
            return strtolower(static::APP_NAME);
        }

        /**
         * Get non-system user docroot ownership
         *
         * @param string $docroot
         * @return string user or active username if system user
         */
        protected function getDocrootUser(string $docroot): string
        {
            if (!($this->permission_level & PRIVILEGE_SITE)) {
                return $this->username;
            }
            $stat = $this->file_stat($docroot);
            if (!$stat) {
                return $this->username;
            }
            // don't change if system user
            if ($stat['uid'] < \apnscpFunctionInterceptor::get_autoload_class_from_module('user')::MIN_UID) {
                warn("docroot `%s' is owned by system user `%d'", $docroot, $stat['uid']);

                return $this->username;
            }
            if (!($username = $this->user_get_username_from_uid($stat['uid']))) {
                warn("failed to translate uid `%d' to user, defaulting ownership of `%s' to `%s'",
                    $stat['uid'], $docroot, $this->username);

                return $this->username;
            }

            return $username;
        }

        /**
         * Create docroot map of files
         *
         * @param array  $files
         * @param string $docroot
         * @return array
         */
        protected function mapFilesFromList(array $files, string $docroot): array
        {
            $prefix = $this->domain_fs_path();

            return array_filter(array_map(function ($f) use ($docroot, $prefix) {
                return $this->buildFileMapList($f, $docroot, $prefix);
            }, $files));
        }

        /**
         * Build map of physical files from glob-style list
         *
         * @param string $f       file name
         * @param string $docroot document root
         * @param string $prefix  path to prepend
         * @return null|string
         */
        protected function buildFileMapList(string $f, string $docroot, string $prefix = ''): ?string
        {
            if ($f[0] !== '/') {
                $f = $docroot . '/' . $f;
            }
            $path = $prefix . $f;
            /**
             * allow specifying additional files that may not
             * exist in the install
             */
            if (false === strpbrk($f, '[]*') && !file_exists($path)) {
                return null;
            }

            return $f;
        }

        /**
         * Get ACL files
         *
         * @param null|string $mode
         * @param string app root
         * @return array
         */
        protected function getACLFiles(?string $mode, string $docroot): ?array
        {
            $app = Loader::fromDocroot(null, $docroot, $this->getAuthContext());
            $manifest = Manifest::instantiateContexted($this->getAuthContext(), [$app]);
            $maps = $this->aclList;
            if ($manifest->exists() && $manifest->verifySignature()) {
                $maps = array_merge_recursive($this->aclList, array_get($manifest, 'fortification', []));
            }

            if (null === $mode) {
                return $maps;
            }

            return $maps[$mode] ?? null;
        }

        public function setOptions(string $docroot, ?array $options)
        {
            if (null === $options) {
                return $this->getMap($docroot)->setOption($options);
            }
            return $this->getMap($docroot)->getOptions()->replace($options);
        }

        protected function initializeMeta(string $docroot, array $opts = []): bool
        {
            $type = $this->getModule();
            if (isset($opts['type'])) {
                $type = $opts['type'];
            }
            $loader = Loader::fromDocroot($type, $docroot, $this->getAuthContext());
            $params = array(
                'version'    => $loader->getVersion(true),
                'hostname'   => $loader->getHostname(),
                'path'       => $loader->getPath(),
                'type'       => $type,
                'autoupdate' => (bool)($opts['autoupdate'] ?? false),
                'options'    => array_intersect_key(
                    $opts,
                    array_diff_key(
                        array_flip($this->reconfigurables($loader->getHostname(), $loader->getPath())),
                        array_flip($loader::TRANSIENT_RECONFIGURABLES)
                    )
                ),
            );

            return $this->map('add', $docroot, $params)
                && (Webapps\App\UIPanel::instantiateContexted(
                    $this->getAuthContext())->freshen($loader->getHostname(), $loader->getPath()
                ) || true);
        }

        /**
         * Set or replace single element of map
         *
         * @param string       $docroot
         * @param string|array $param
         * @param mixed         $val
         * @return bool
         */
        private function setMap(string $docroot, $param, $val = null): bool
        {
            $map = $this->getMap($docroot);

            if ($param === 'options') {
                $this->getMap($docroot)->setOption($param, $val);
                return true;
            }

            if ($param instanceof Meta) {
                $map = $param;
            } else if (!\is_array($param)) {
                if (null === $val) {
                    unset($map[$param]);
                } else {
                    $map[$param] = $val;
                }
            } else {
                $map = $param;
            }

            return $this->saveMap($docroot, $map);
        }

        /**
         * Get webapp metadata
         *
         * @param string $docroot
         * @return array
         */
        private function getMap(string $docroot): Meta
        {
            return MetaManager::factory($this->getAuthContext())->get($docroot);
        }

        /**
         * Save map
         *
         * @param string     $docroot
         * @param array|Meta $map
         * @return bool
         */
        private function saveMap(string $docroot, $map): bool
        {
            if ($map instanceof Meta) {
                // already synchronized
                return true;
            }
            $docroot = rtrim($docroot, '/');
            // can't use \Preferences::get('webapps.paths.foo.com') because foo.com -> foo['com']
            $prefs = MetaManager::factory($this->getAuthContext());
            if (null === $map) {
                $prefs->forget($docroot);
            } else {
                $prefs->set($docroot, $map);
            }

            return true;
        }

        /**
         * Get webapp options
         *
         * @param $docroot
         * @return MetaManager\Options
         */
        public function getOptions($docroot): MetaManager\Options
        {

            return $this->getMap($docroot)->getOptions();
        }

        /**
         * Parse general installer options
         *
         * Handles: version, ssl, autoupdate, email, user, and git attributes
         *
         * @param array  $options
         * @param string $hostname
         * @param string $path
         * @return bool
         */
        protected function parseInstallOptions(array &$options, string $hostname, string $path = ''): bool
        {
            $docroot = $this->getDocumentRoot($hostname, $path);

            if (!$this->checkDocroot($docroot, $options['user'] ?? null)) {
                return false;
            }

            if  (!empty($options['git'])) {
                defer($options['callbacks'], function () use ($hostname, $path) {
                    $approot = $this->getAppRoot($hostname, $path);
                    $docroot = $this->getDocumentRoot($hostname, $path);
                    $git = Git::instantiateContexted(
                        $this->getAuthContext(), [
                            $approot,
                            MetaManager::factory($this->getAuthContext())->get($docroot)
                        ]
                    );
                    $git->createRepository() && $git->snapshot(_('Initial install'));
                });
                // git requires a special callback not handled yet
                unset($options['git']);
            }

            $changes = array_intersect_key($options, array_flip($this->reconfigurables($hostname, $path)));
            $app = Loader::fromDocroot(null, $docroot, $this->getAuthContext());
            $reconfigurator = Reconfigurator::instantiateContexted($this->getAuthContext(), [$app]);

            foreach ($changes as $cname => $cval) {
                $reconfigurator->reconfigure($cname, $options[$cname]);
            }

            if ($this->prepareSquash($options)) {
                // squash requested, flip ownership to API owner, workout in unsquash later
                $this->file_chown($docroot, $this->user_id);
            }

            if (!\array_key_exists('verlock', $options)) {
                $options['verlock'] = static::DEFAULT_VERSION_LOCK;
            }

            if (!\array_key_exists('autoupdate', $options)) {
                $options['autoupdate'] = true;
            }

            if (!$this->checkEmail($options)) {
                return false;
            }

            if (!$this->checkVersion($options)) {
                return false;
            }

            $options['email'] = $options['email'] ?? $this->getConfig('siteinfo', 'email');

            if (!preg_match(Regex::EMAIL, $options['email'])) {
                return error("invalid email address `%s' specified", $options['email']);
            }

            if (!empty($options['user'])) {
                if (!$this->user_exists($options['user'])) {
                    return error("user `%s' does not exist", $options['user']);
                }

                if (!$this->file_chown($docroot, $options['user'])) {
                    return error("failed to prep docroot for ownership by `%s'", $options['user']);
                }
            } else {
                $options['user'] = $this->username;
            }

            // ensure the docroot is owned by the target uid to permit installation
            // correct it at the end
            if ($options['squash']) {
                $this->file_chown($docroot, $this->user_id);
                defer($options['callbacks'], function () use ($docroot) {
                    // hook into xxx:install() last when fn returns
                    return $this->unsquash($docroot);
                });
            }


            return true;
        }

        /**
         * Notify application installed
         *
         * @param string $hostname
         * @param string $path
         * @param array  $args
         * @return bool
         */
        protected function notifyInstalled(string $hostname, string $path = '', array $args = []): bool
        {
            if (!array_get($args, 'notify', true)) {
                return true;
            }

            $args['email'] = $args['email'] ?? $this->common_get_email();

            if (empty($args['email'])) {
                return warn("Notification requested but no 'email' parameter found for %(app)s install on %(hostname)s/%(path)s", [
                    'app' => $this->getAppName(), $hostname, $path
                ]);
            }

            \Lararia\Bootstrapper::minstrap();

            $fqdn = $this->web_normalize_hostname($hostname);
            $opts['url'] = rtrim($fqdn . '/' . $path, '/');
            $app = Loader::fromHostname(null, $hostname, $path, $this->getAuthContext());
            if ('webapp' === ($type = $app->getModuleName())) {
                $type = $this->getModule();
            }

            \Illuminate\Support\Facades\Mail::to($args['email'])->
                send((new \Module\Support\Webapps\Mailer('@webapp(' . $type . ')::job-installed', $args + [
                    'login'    => $args['user'] ?? null,
                    'password' => $args['password'] ?? null,
                    'uri'      => rtrim($fqdn . '/' . $path, '/'),
                    'proto'    => empty($opts['ssl']) ? 'http://' : 'https://',
                    'appname'  => static::APP_NAME,
                    'approot'  => $app->getAppRoot(),
                    'app'      => $app
                ]))->setAppName(static::APP_NAME));

            return true;
        }

        /**
         * Get or set failed status
         *
         * @param string $docroot
         * @param null|bool $failedFlag
         * @return bool
         */
        public function failed(string $docroot, bool $failedFlag = null): bool
        {
            $prefs = $this->getMap($docroot);
            if ($failedFlag === null) {
                return (bool)array_get($prefs, 'failed', false);
            }
            $prefs['failed'] = (bool)$failedFlag;

            return $this->setMap($docroot, $prefs);
        }

        /**
         * Get application version lock
         *
         * @param string $docroot
         * @return null|string
         */
        public function getVersionLock(string $docroot): ?string
        {
            $options = $this->getOptions($docroot);
            $lock = array_get($options, 'verlock', static::DEFAULT_VERSION_LOCK);
            return $lock === 'none' ? null : $lock;
        }

        /**
         * Web application supports fortification
         *
         * @param string      $hostname
         * @param string      $path
         * @param string|null $mode optional mode (min, max)
         * @return bool
         */
        public function has_fortification(string $hostname, string $path = '', string $mode = null): bool
        {
            $docroot = $this->getDocumentRoot($hostname, $path);
            if ($mode) {
                return null !== $this->getACLFiles($mode, $docroot);
            }

            return !empty($this->aclList);
        }

        /**
         * Supported Fortification modes
         *
         * @param string $hostname
         * @param string $path
         * @return array
         */
        public function fortification_modes(string $hostname, string $path = ''): array
        {
            $docroot = $this->getDocumentRoot($hostname, $path);
            return array_keys($this->getACLFiles(null, $docroot));
        }


        /**
         * Relax permissions to allow write-access
         *
         * @param string $hostname
         * @param string $path
         * @return bool
         */
        public function unfortify(string $hostname, string $path = ''): bool
        {
            $docroot = $this->getAppRoot($hostname, $path);
            if (!$docroot) {
                return error("docroot for `%s' is unknown ", $hostname);
            }
            $webuser = $this->web_get_user($hostname, $path);

            $users = array(
                array($webuser => 'rxw'),
                array($webuser => 'drwx'),
                $this->username => 'drwx'
            );
            if (!$this->file_set_acls($docroot, $users, array(File_Module::ACL_MODE_RECURSIVE => true))) {
                return warn("unfortification failed on `%s/%s'", $hostname, $path);
            }
            $app = Loader::fromHostname(null, $hostname, $path, $this->getAuthContext());
            $app->setOption('fortify', false);
            return true;
        }

        /**
         * Remove an installed web application
         *
         * @param string $hostname
         * @param string $path
         * @param string $delete "all", "db", or "files"
         * @return bool
         */
        public function uninstall(string $hostname, string $path = '', string $delete = 'all'): bool
        {
            $docroot = $this->getDocumentRoot($hostname, $path);

            if (!$docroot) {
                return error('failed to determine path');
            }

            if (!$this->valid($hostname, $path)) {
                return error("`%(path)s' does not contain a valid %(app)s install", ['path' => $docroot, 'app' => static::APP_NAME]);
            }

            $delete = strtolower($delete);
            if ($delete && !\in_array($delete, array('all', 'db', 'files'), true)) {
                return error("unknown delete option `%s'", $delete);
            }
            $config = $this->db_config($hostname, $path);
            $dbtype = $config['type'] ?? 'mysql';
            if (($delete === 'all' || $delete === 'db') && $config !== []) {
                if (!$config) {
                    warn('cannot remove database, config missing?');
                } else if ($this->{$dbtype . '_database_exists'}($config['db']) && !$this->{$dbtype . '_delete_database'}($config['db'])) {
                    warn("failed to delete mysql database `%s'", $config['db']);
                } else if ($config['user'] !== $this->getServiceValue($dbtype, 'dbaseadmin')) {
                    if ($this->{$dbtype . '_user_exists'}($config['user'],
                            $config['host']) && !$this->{$dbtype . '_delete_user'}($config['user'], $config['host'])
                    ) {
                        warn("failed to delete mysql user `%s' on localhost", $config['user']);
                    }
                }
            } else if ($config) {
                warn("database kept, delete user: `%s'@`%s', db: `%s' manually",
                    $config['user'],
                    $config['host'],
                    $config['db']
                );
            }
            $options = $this->getOptions($docroot);
            $this->map('delete', $docroot);
            $saved = array_intersect_key(
                $options->toArray(),
                array_flip($this->webapp_reconfigurables($hostname, $path))
            );
            $prefs = [
                'type' => null,
                'failed' => false,
                'options' => $saved
            ];
            // reapply generic settings
            if (!$delete || $delete === 'db') {
                return info("removed configuration, manually delete files under `%s'", $docroot);
            }
            $approot = $this->getAppRoot($hostname, $path);
            if (($oldroot = $this->getDocumentRoot($hostname, $path)) !== $this->getAppRoot($hostname, $path)) {
                $oldroot = $this->web_normalize_path($hostname, $path);
                $docroot = $this->remapPublic($hostname, $path, '') ?? $docroot;
                // rename normalized root, can't do before it's remapped as symlinks are always resolved
                MetaManager::instantiateContexted($this->getAuthContext())->rename($oldroot, $docroot);
            }

            $this->map('add', $docroot, $prefs);

            $this->file_delete($approot, true);
            if ($approot !== $docroot && 0 !== strpos("${docroot}/", "${approot}/")) {
                // remapping /var/www/html to /var/www/ghost/public
                $this->file_delete($docroot, true);
            }
            $url = rtrim(join('/', array($hostname, $path)), '/');
            $this->file_purge();
            $this->file_create_directory($docroot, 0755, true);
            if (!array_get($options, 'squash', true)) {
                $this->unsquash($docroot);
            }

            UIPanel::instantiateContexted($this->getAuthContext())->freshen($hostname, $path);

            return info("deleted %s `%s' located under `%s'", static::APP_NAME, $url, $docroot);
        }

        /**
         * Get document root from hostname
         *
         * @param string $hostname subdomain or domain
         * @param string $path     optional path under hostname
         * @return bool|string
         */
        protected function getDocumentRoot(string $hostname, string $path = ''): ?string
        {
            return $this->web_get_docroot($hostname, $path);
        }

        /**
         * Retrieve document root realpath for given host
         *
         * @param string $hostname
         * @param string $path
         * @return string|null
         */
        protected function normalizeDocumentRoot(string $hostname, string $path = ''): ?string
        {
            return $this->web_normalize_path($hostname, $path);
        }

        /**
         * Map management
         *
         * @param string $mode    add or delete
         * @param string $docroot document root
         * @param array|null $params map parameters
         * @return bool
         */
        protected function map(string $mode, string $docroot, array $params = null): bool
        {
            if ($mode !== 'add' && $mode !== 'delete') {
                return error("failed to set map for `%(docroot)s', unknown mode `%(mode)s'",
                    ['docroot' => $docroot, 'mode' => $mode]);
            }

            $stat = $this->file_stat($docroot);
            if (!empty($stat['referent']) && $mode !== 'delete') {
                debug('Symlink encountered %(docroot)s -> %(referent)s, changing to %(referent)s',
                    ['docroot' => $docroot, 'referent' => $stat['referent']]
                );
                $docroot = $stat['referent'];
            }

            unset($params['options']['callbacks']);

            if ($mode === 'delete') {
                return $this->saveMap($docroot, null);
            }

            if (!\array_key_exists('type', $params)) {
                $params['type'] = $this->getModule();
            }

            return $this->saveMap($docroot, $params);
        }

        /**
         * Get Web App module name
         *
         * @return string
         * @throws \ReflectionException
         */
        protected function getModule(): string
        {
            $rfxn = new \ReflectionClass($this);
            $class = static::getBaseClassName($rfxn->isAnonymous() ? $rfxn->getParentClass()->getName() :  $rfxn->getName());
            return strtolower(substr($class, 0, strpos($class, '_')) ?? 'skeleton');
        }

        /**
         * Migrate a document root to public/
         *
         * @param string $hostname hostname
         * @param string $path     subdomain path
         * @param string $public   optional public folder, leave empty to restore docroot
         * @return null|string
         */
        protected function remapPublic(string $hostname, string $path = '', string $public = 'public'): ?string
        {
            if (!$public && !$path && $hostname === $this->domain) {
                // can't relocate primary docroot, short-circuit it
                $this->file_delete(Web_Module::MAIN_DOC_ROOT, true);
                $this->file_create_directory(Web_Module::MAIN_DOC_ROOT);
                return Web_Module::MAIN_DOC_ROOT;
            }
            $rootsave = $this->getDocumentRoot($hostname, $path);
            if (false === ($docroot = $this->movePrimaryDocumentRoot($rootsave))) {
                warn('failed to relocate docroot for %s - installation incomplete', static::APP_NAME);

                return null;
            }
            if (!$public) {
                $public = $this->getAppRoot($hostname, $path);
                $stat = $this->file_stat($public);
                if (!$stat || $stat['link']) {
                    warn("Cannot remap public, public `%s' does not exist or is a symlink", $public);

                    return null;
                }
            }

            if ($rootsave !== $docroot) {
                $stat = $this->file_stat($rootsave);
                // remove dangling symlink
                if ($stat && $stat['link']) {
                    $this->file_delete($rootsave, false);
                }
            }
            if ($public[0] !== '/') {
                if (!$this->file_exists("${docroot}/${public}")) {
                    if (!$stat = $this->file_stat($docroot)) {
                        error("document root `%s' missing - unable to stat", $docroot);

                        return null;
                    }
                    $this->file_create_directory("${docroot}/${public}");
                    $this->file_chown("${docroot}/${public}", $stat['owner']);
                }
                if ($rootsave !== $docroot) {
                    // docroot was moved, bad fringe case
                    $stat = $this->file_stat($docroot);
                    if (!$stat) {
                        error("emerg! failed to stat path `%s'", $docroot);

                        return null;
                    }
                    if ($public) {
                        // otherwise restoring docroot
                        $this->file_symlink($docroot . '/' . $public, $rootsave);
                    }
                    $this->file_chown_symlink($rootsave, $stat['owner']);
                    $this->web_purge();

                    return $rootsave;
                }
            }

            $normalized = $this->web_normalize_hostname($hostname);
            [$subdomain, $domain] = array_values($this->web_split_host($normalized));
            // restoring or moving;
            $newpath = strncmp($public, '/', 1) === 0 ? $public : "${docroot}/${public}";
            $ret = true;
            if ($docroot !== rtrim("${docroot}/${public}", '/')) {
                // in case of /var/www/html no modification is performed
                if ($subdomain) {
                    $ret = $this->web_rename_subdomain($hostname, $hostname, $newpath)
                        && info("Moved document root for `%s' from `%s' to `%s'", $normalized, $docroot, $newpath);
                } else {
                    $ret = $this->aliases_modify_domain($domain, ['path' => $newpath])
                        && info("Moved document root for `%s' from `%s' to `%s'", $normalized, $docroot, $newpath);
                }
            }
            $this->web_purge();

            return !$ret ? null : $newpath;
        }

        /**
         * Migrate document root elsewhere
         *
         * @param string $docroot
         * @return mixed string new root on relocation, false on error
         */
        protected function movePrimaryDocumentRoot(string $docroot)
        {
            if ($docroot !== \Web_Module::MAIN_DOC_ROOT) {
                return $docroot;
            }
            $app = $this->getInternalName();
            // @todo objects make more sense now...
            $suffix = '';
            $i = 0;
            do {
                $newroot = \dirname($docroot) . DIRECTORY_SEPARATOR . 'html-' . $app . $suffix;
                if (!$this->file_exists($newroot)) {
                    break;
                }
                $newroot = null;
                $i++;
                $suffix = '-' . date('Ymd-' . $i);
            } while ($i < 100);

            if (null === $newroot) {
                return error("failed to rename docroot `%s' - cannot find a suitable location", $docroot);
            }

            if ($this->file_exists($newroot)) {
                return error("attempted to install %(app)s in `%(location)s', but directory exists - remove first before proceeding",
                    ['app' => ucwords($app), 'location' => $newroot]);
            }
            if (!$this->file_rename($docroot, $newroot)) {
                return error("failed to rename docroot from `%(old)s' to `%(new)s'", ['old' => $docroot, 'new' => $newroot]);
            }
            info("Relocated primary document root from `%(old)s' to `%(new)s'", ['old' => $docroot, 'new' => $newroot]);
            MetaManager::instantiateContexted($this->getAuthContext())->rename(Web_Module::MAIN_DOC_ROOT, $newroot);
            $this->web_purge();

            return $newroot;
        }

        /**
         * Change ownership from active uid to parent directory uid
         *
         * @param string $docroot document root
         * @return bool
         */
        protected function unsquash(string $docroot): bool
        {
            $stat = $this->file_stat(\dirname($docroot));
            $newuid = array_first([$stat['uid'], $this->user_id], static function ($uid) {
                return $uid >= User_Module::MIN_UID;
            });
            if ($newuid === $this->user_id) {
                return true;
            }
            $ret = $this->file_chown($docroot, $newuid, true);
            if (!$ret) {
                warn("failed to unsquash `%(docroot)s', ownership will remain as `%(owner)s'", ['docroot' => $docroot, 'owner' => $this->username]);
            }
            // @todo this is a kludge to allow updates by site admin without sudo to user
            // adjust update routines to sudo?
            $this->file_set_acls(
                $docroot,
                $this->username,
                'rwx',
                [File_Module::ACL_MODE_RECURSIVE]
            );
            foreach ($this->web_list_subdomains('path', $docroot) as $subdomain => $path) {
                // update ownership on subdomain link
                $this->web_rename_subdomain($subdomain, $subdomain, $path);
            }
            return true;
        }

        /**
         * Get next version in hierarchy
         *
         * @param string $version
         * @param string $maximalbranch
         * @return null|string
         */
        public function next_version(string $version, string $maximalbranch = '99999999.99999999.99999999'): ?string
        {
            $versions = $this->get_versions();

            return Versioning::nextVersion($versions, $version, $maximalbranch);
        }

        /**
         * Check if version is latest or get latest version
         *
         * @param null|string $version
         * @param string|null $branchcomp branch to compare against
         * @return int|string
         */
        public function is_current(string $version = null, string $branchcomp = null)
        {
            $versions = $this->get_versions();
            if (!$version) {
                return array_pop($versions);
            }

            return Versioning::current($versions, $version, $branchcomp);
        }

        /**
         * Create an afi instance based on directory ownership
         *
         * @param string               $docroot
         * @param \Auth_Info_User|null $context context reference
         * @return \apnscpFunctionInterceptor
         */
        protected function getApnscpFunctionInterceptorFromDocroot(
            string $docroot,
            ?\Auth_Info_User &$context = null
        ): \apnscpFunctionInterceptor {
            $user = $this->getDocrootUser($docroot);
            if ($user === $this->username) {
                $context = $this->getAuthContext();

                return $this->getApnscpFunctionInterceptor();
            }
            $context = \Auth::context($user, $this->site);

            return \apnscpFunctionInterceptor::factory($context);
        }

        /**
         * Account has sufficient memory in MB
         *
         * @param int $memory    memory in MB
         * @param int $available detected memory available
         * @return bool
         */
        protected function hasMemoryAllowance(int $memory, int &$available = null): bool
        {
            return ($available = $this->getMaximalMemory()) >= $memory;
        }

        /**
         * Maximum memory permitted in MB
         *
         * @return int
         */
        protected function getMaximalMemory(): int
        {
            return $this->cgroup_enabled() ? $this->getConfig('cgroup', 'memory') :
                \Opcenter\System\Memory::stats()['memtotal']/1024;
        }

        /**
         * Account has sufficient storage in MB
         *
         * @param int $storage   storage in MB
         * @param int $available detected storage in MB
         * @return bool
         */
        protected function hasStorageAllowance(int $storage, int &$available = null): bool
        {
            $quota = $this->site_get_account_quota();
            if (!$this->getConfig('diskquota', 'enabled')) {
                return true;
            }

            $available = (int)(($quota['qhard'] - $quota['qused']) / 1024);

            return $available >= $storage;
        }

        /**
         * Check email option
         *
         * @param array $options
         * @return bool
         */
        protected function checkEmail(array &$options): bool
        {
            if (isset($options['email']) && !preg_match(Regex::EMAIL, $options['email'])) {
                return error("invalid email address `%s' specified", $options['email']);
            }
            $options['email'] = $options['email'] ?? $this->common_get_email();

            return true;
        }

        /**
         * Convert ownership to match parent directory of docroot
         *
         * In relocatable docroots (moving /var/www/html to /var/www/foo-bar/public)
         * this always runs as the same user as "user" option
         *
         * @param array $options
         * @return bool
         */
        protected function prepareSquash(array &$options): bool
        {
            $squash = array_get($options, 'squash', false);
            if ($squash && $this->permission_level & PRIVILEGE_USER) {
                warn('cannot squash privileges as secondary user');
                $squash = false;
            }
            $options['squash'] = $squash;

            return (bool)$squash;
        }

        /**
         * Check and prepare version information
         *
         * @param array $options
         * @return bool
         */
        protected function checkVersion(array &$options): bool
        {
            $version = array_get($options, 'version');
            if (null === $version) {
                $version = $this->get_versions();
                $version = array_pop($version);
            } else if (null !== $version && strcspn($version, '.0123456789')) {
                return error('invalid version number, %s', $version);
            }
            $options['version'] = $version;

            return true;
        }

        /**
         * Verify docroot is writeable before beginning installation
         *
         * @param string      $docroot docroot to check
         * @param string|null $user    optional docroot owner
         * @return bool
         */
        protected function checkDocroot(string $docroot, string $user = null): bool
        {
            if (!$user) {
                $user = $this->username;
            }
            if (!$this->user_exists($user)) {
                return error("target user for install `%s' does not exist", $user);
            }
            $this->file_purge();

            if (!$this->file_exists($docroot) && !$this->file_create_directory($docroot, 0755, true)) {
                return error("failed to create installation directory `%s'", $docroot);
            }

            $publicpath = $this->domain_fs_path() . DIRECTORY_SEPARATOR . $docroot;
            $files = glob($publicpath . DIRECTORY_SEPARATOR . '{.,}*', GLOB_BRACE|GLOB_NOSORT);

            $placeholder = $docroot . '/index.html';

            if (\count($files) === 3 /* . + .. links */ && $this->file_exists($placeholder)) {
                $this->file_delete($placeholder);
                info('removed placeholder file');
            } else if (\count($files) > 2 /* . + .. */) {
                return error("target path `%s' must be empty, %d files located in `%s'", $docroot, \count($files)-2,
                    $docroot);
            }

            $this->file_chown($docroot, $user);
            $this->file_purge();

            return true;
        }

        /**
         * Kill processes running under location
         *
         * @param string $hostname
         * @param string $path
         * @return int
         */
        protected function kill(string $hostname, string $path = ''): int
        {
            $approot = $this->getAppRoot($hostname, $path);
            $procs = $this->pman_get_processes();
            $count = 0;
            if ($this->permission_level & PRIVILEGE_SITE | PRIVILEGE_USER) {
                // cwd is /home/virtual/siteXX/fst
                $approot = $this->domain_fs_path() . $approot;
            }
            $oldex = \Error_Reporter::exception_upgrade(\Error_Reporter::E_ERROR);
            foreach ($procs as $pid => $data) {
                if (0 !== strpos($data['cwd'], $approot)) {
                    continue;
                }
                try {
                    $this->pman_kill($pid);
                    $count++;
                } catch (\apnscpException $e) {
                    warn($e->getMessage());
                }
            }
            \Error_Reporter::exception_upgrade($oldex);

            return $count;
        }

        /**
         * Get latest release
         *
         * @param string $branch branch to discover latest version
         * @return null|string
         */
        protected function getLatestVersion(string $branch = null): ?string
        {
            $versions = $this->get_versions();
            if (!$versions) {
                return null;
            }
            if (!$branch) {
                return array_pop($versions);
            }

            $latest = null;
            $search = $branch . '.0';

            foreach ($versions as $version) {
                if (0 === strpos($version, $branch) && version_compare($version, $search, '>=')) {
                    $latest = $version;
                }
            }

            return $latest;
        }

        /**
         * Add RewriteBase to htaccess
         *
         * @param        $docroot
         * @param string $path
         * @return bool
         * @throws \FileError
         */
        protected function fixRewriteBase(string $docroot, string $path = ''): bool
        {
            $file = $docroot . $path . '/.htaccess';
            if (!$this->file_exists($file)) {
                return true;
            }
            $htaccess = $this->file_get_file_contents($file);
            $replacement = '$1RewriteEngine On' . "\n" .
                '$1RewriteBase ' . '/' . ltrim($path, '/');

            $newhtaccess = preg_replace('/^(\s*)RewriteEngine On(?!\s+RewriteBase)/mi', $replacement, $htaccess);
            return $this->file_put_file_contents($file, $newhtaccess);
        }

        /**
         * Remove invalid directives from .htaccess
         *
         * @param string $docroot document root
         * @param string $path subpath
         * @return bool
         * @throws \FileError
         */
        protected function removeInvalidDirectives(string $docroot, string $path = ''): bool
        {
            $file = $docroot . '/' . ltrim($path, '/') . '/.htaccess';
            if (!$this->file_exists($file)) {
                return true;
            }
            $htaccess = $this->file_get_file_contents($file);
            foreach (static::BANNED_DIRECTIVES as $directive) {
                $htaccess = preg_replace(
                    [
                        '/^(\s*Options\s+.*?(?=[+-]?' . $directive . '))(?:[+-]?' . $directive . '(?=\s+|$))/m',
                        '/^\s*Options\s*$/m'
                    ],
                    '\1',
                    $htaccess
                );
            }
            return $this->file_put_file_contents($file, $htaccess);
        }

        /**
         * Download specified file
         *
         * @param string $url
         * @param string $dest
         * @param bool   $extract
         * @throws HTTP_Request2_Exception
         * @return string|bool
         */
        protected function download(string $url, string $dest, bool $extract = true)
        {
            // @todo refactor into helper, cf. filemanager
            $prefix = $this->domain_fs_path();
            // necessary because sometimes file_extract can be dumb
            $basename = basename($url);
            if (false !== ($pos = strpos($basename, '?'))) {
                $basename = substr($basename, 0, $pos);
            }
            // $dest specified as filename.ext
            if (false !== strpos(basename($dest), '.')) {
                $basename = basename($dest);
                $dest = dirname($dest);
            }

            if (false !== ($pos = strpos($basename, '.tar.'))) {
                $suffix = substr($basename, $pos);
            } else {
                $suffix = substr($basename, strrpos($basename, '.'));
            }

            $tmp = tempnam($prefix . '/' . TEMP_DIR, 'wget') . $suffix;
            if (file_exists($tmp)) {
                return error("cannot download, dest file/suffix `%s' exists", $tmp);
            }
            if (\extension_loaded('curl')) {
                $adapter = new \HTTP_Request2_Adapter_Curl();
            } else {
                $adapter = new \HTTP_Request2_Adapter_Socket();
            }

            $http = new \HTTP_Request2(
                $url,
                \HTTP_Request2::METHOD_GET,
                array(
                    'adapter'    => $adapter,
                    'store_body' => false
                )
            );

            $observer = new \HTTP_Request2_Observer_SaveDisk($tmp);
            $http->attach($observer);
            try {
                $response = $http->send();
                $code = $response->getStatus();
                switch ($code) {
                    case 200:
                        break;
                    case 403:
                        return error("URL `%s' request forbidden by server", $url);
                    case 404:
                        return error("URL `%s' not found on server", $url);
                    case 301:
                    case 302:
                        $newLocation = $response->getHeader('location');

                        return self::download($newLocation, "$dest/$basename", $extract);
                    default:
                        return error("URL request failed, code `%d': %s",
                            $code, $response->getReasonPhrase());
                }
                $content = $response->getHeader('content-type');
                $okcontent = array('application/octet-stream', 'application/zip', 'application/x-bzip2');
                if (!\in_array($content, $okcontent, true)) {
                    \Error_Reporter::report($content);
                }
                // this returns nothing as xfer is saved directly to disk
                $http->getBody();
            } catch (\HTTP_Request2_Exception $e) {
                return error("fatal error retrieving URL: `%s'", $e->getMessage());
            }
            if (!posix_getuid()) {
                chown($tmp, WS_USER);
            }
            // write file
            $jailtmp = $this->file_unmake_path($tmp);
            $this->file_endow_upload(basename($jailtmp));
            if (version_compare(platform_version(), '6.5', '>=')) {
                // Luna+ platforms use OverlayFS
                $this->file_purge();
            }

            if ($extract && $this->file_is_compressed($jailtmp)) {
                if (!$this->file_extract($jailtmp, $dest)) {
                    error("failed to extract downloaded file to `%s'", $dest);
                    $dest = null;
                }
            }
            $this->file_delete($jailtmp);

            return $dest;
        }

        /**
         * Set webapp meta
         *
         * @param string     $docroot document root
         * @param array|null $info
         * @return Meta
         */
        protected function setInfo(string $docroot, ?array $info): void
        {
            $fn = null === $info ? 'set' : 'replace';
            MetaManager::factory($this->getAuthContext())->get($docroot)->{$fn}($info);
        }

        /**
         * Get all hostnamers on site
         *
         * @param \Auth_Info_User $ctx
         * @return array
         */
        public static function getAllHostnames(\Auth_Info_User $ctx): array
        {
            $afi = \apnscpFunctionInterceptor::factory($ctx);
            $domainfill = array_merge([$ctx->domain], $afi->aliases_list_aliases());
            $hosts = array_combine($domainfill, $domainfill);
            $subdomains = array_keys($afi->web_list_subdomains());

            foreach ($subdomains as $subdomain) {
                if (false === strpos($subdomain, '.')) {
                    $hosts[$subdomain] = $subdomain . '.' . $ctx->domain;
                    continue;
                }
                $tmp = $afi->web_split_host($subdomain);
                if (!isset($hosts[$tmp['domain']])) {
                    // @XXX
                    // detached domain, subdomain no longer applicable
                    // this should be removed automatically by removal
                    // of domain
                    continue;
                }
                $hosts[$subdomain] = $subdomain;
            }

            return array_values($hosts);
        }

        /**
         * Get hostnames grouped by subdomain and domain
         *
         * @param \Auth_Info_User $ctx
         * @param bool            $showWWW
         * @param bool            $sort
         * @return array|array[]
         */
        public static function getAllPartitionedHostnames(\Auth_Info_User $ctx, bool $showWWW = true, bool $sort = false): array
        {
            $afi = \apnscpFunctionInterceptor::factory($ctx);
            $ret = ['domain' => [], 'subdomain' => []];
            $domainfill = array_merge([$ctx->domain], $afi->aliases_list_aliases());
            $subdomains = array_keys($afi->web_list_subdomains());
            if ($sort) {
                asort($subdomains);
                asort($domainfill);
            }

            $domains = array_fill_keys($domainfill, array());
            array_unshift($subdomains, '');
            if ($showWWW) {
                array_unshift($subdomains, 'www');
            }
            foreach ($subdomains as $subdomain) {
                if (false === strpos($subdomain, '.')) {
                    foreach (array_keys($domains) as $d) {
                        $ret['domain'][$d][] = $subdomain;
                    }
                    $ret['subdomain'][$subdomain] = $domainfill;
                    continue;
                }
                $tmp = $afi->web_split_host($subdomain);
                if (!isset($domains[$tmp['domain']])) {
                    // @XXX
                    // detached domain, subdomain no longer applicable
                    // this should be removed automatically by removal
                    // of domain
                    continue;
                }
                $ret['subdomain'][$tmp['subdomain']][] = $tmp['domain'];
                $ret['domain'][$tmp['domain']][] = $tmp['subdomain'];
            }

            return $ret;
        }

        /**
         * Document root contains expected app type
         *
         * @param string $hostname
         * @param string $path
         * @return bool
         */
        abstract public function valid(string $hostname, string $path = ''): bool;

        /**
         * @inheritDoc
         */
        public function theme_status(string $hostname, string $path = '', string $theme = null)
        {
            return [];
        }

        /**
         * @inheritDoc
         */
        public function install_theme(string $hostname, string $path, string $theme, string $version = null): bool
        {
            return error('not implemented');
        }

        /**
         * @inheritDoc
         */
        public function uninstall_theme(string $hostname, string $path, string $theme, bool $force = false): bool
        {
            return error('not implemented');
        }

        /**
         * @inheritDoc
         */
        public function plugin_status(string $hostname, string $path = '', string $plugin = null)
        {
            return [];
        }

        /**
         * @inheritDoc
         */
        public function install_plugin(string $hostname, string $path, string $plugin, string $version = ''): bool
        {
            return error("not implemented");
        }

        /**
         * @inheritDoc
         */
        public function uninstall_plugin(string $hostname, string $path, string $plugin, bool $force = false): bool
        {
            return error("not implemented");
        }

        /**
         * @inheritDoc
         */
        public function disable_all_plugins(string $hostname, string $path = ''): bool
        {
            return error("not implemented");
        }

        /**
         * @inheritDoc
         */
        public function db_config(string $hostname, string $path = '')
        {
            return [];
        }

        /**
         * @inheritDoc
         */
        public function change_admin(string $hostname, string $path, array $fields): bool
        {
            return error("not implemented");
        }

        /**
         * @inheritDoc
         */
        public function get_admin(string $hostname, string $path = ''): ?string
        {
            return null;
        }

        /**
         * @inheritDoc
         */
        public function update_all(string $hostname, string $path = '', string $version = null): bool
        {
            return error("not implemented");
        }

        /**
         * @inheritDoc
         */
        public function update(string $hostname, string $path = '', string $version = null): bool
        {
            return error("not implemented");
        }

        /**
         * @inheritDoc
         */
        public function update_plugins(string $hostname, string $path = '', array $plugins = array()): bool
        {
            return error("not implemented");
        }

        /**
         * @inheritDoc
         */
        public function update_themes(string $hostname, string $path = '', array $themes = array()): bool
        {
            return error("not implemented");
        }

        /**
         * Asset skipped for update
         *
         * @param string      $hostname hostname
         * @param string      $path     path
         * @param string      $name     asset name
         * @param string|null $type     asset subtype
         * @return bool
         */
        public function asset_skipped(string $hostname, string $path, string $name, ?string $type): bool
        {
            return false;
        }

        /**
         * Reconfigure a webapp
         *
         * @param string       $hostname hostname
         * @param string       $path     optional path
         * @param string|array $param    array of reconfigurables or single value
         * @param mixed        $value    value to set in single-value mode
         * @return bool
         */
        public function reconfigure(string $hostname, string $path, $param, $value = null): bool
        {
            if (static::class !== \a23r::get_class_from_module('webapp') && !$this->valid($hostname, $path)) {
                // switch back to webapp module
                return $this->webapp_reconfigure($hostname, $path, $param, $value);
            }

            if (\is_array($param) && $value) {
                return error('Invalid parameter format');
            }

            if (!\is_array($param)) {
                $param = [$param => $value];
            }

            $bad = array_diff(array_keys($param), $this->reconfigurables($hostname, $path));
            if ($bad) {
                return error('Unknown reconfigurable directives: %s', implode(', ', $bad));
            }
            $original = $this->getOptions($docroot = $this->getDocumentRoot($hostname, $path));
            $app = Loader::fromDocroot($this->getAppName(), $docroot, $this->getAuthContext());
            $changes = $original->diff($param) + array_intersect_key($param, array_flip($app::TRANSIENT_RECONFIGURABLES));
            $reconfigurator = Reconfigurator::instantiateContexted($this->getAuthContext(), [$app]);
            foreach ($changes as $cname => $cval) {
                $reconfigurator->reconfigure($cname, $cval);
            }

            return true;
        }

        /**
         * List of reconfigurable elements
         *
         * @param string $hostname
         * @param string $path
         * @return array
         */
        public function reconfigurables(string $hostname, string $path = ''): array
        {
            $transients = Loader::fromHostname($this->getAppName(), $hostname, $path, $this->getAuthContext());
            return array_merge(
                ['user', 'http10', 'ssl', 'verlock', 'autoupdate', 'git', 'affixed'],
                $transients::TRANSIENT_RECONFIGURABLES
            );
        }

        /**
         * Get reconfigurable setting
         *
         * @param string $hostname
         * @param string $path
         * @param string|string[] $setting
         * @return mixed
         */
        public function get_reconfigurable(string $hostname, string $path, $setting)
        {
            if (static::class !== \a23r::get_class_from_module('webapp') && !$this->valid($hostname, $path)) {
                return error("%(hostname)s/%(path)s does not contain a valid %(app)s install", [
                    'hostname' => $hostname, 'path' => $path, 'app' => $this->getAppName()
                ]);
            }
            $wantArray = is_array($setting);
            $setting = array_flip((array)$setting);

            $bad = array_diff(array_keys($setting), $this->reconfigurables($hostname, $path));
            if ($bad) {
                return error('Unknown reconfigurable directives: %s', implode(', ', $bad));
            }
            $app = Loader::fromHostname($this->getAppName(), $hostname, $path, $this->getAuthContext());
            $reconfigurator = Reconfigurator::instantiateContexted($this->getAuthContext(), [$app]);
            foreach ($setting as $cname => $cval) {
                $setting[$cname] = $reconfigurator->handler($cname)->getValue();

            }

            return $wantArray ? $setting : current($setting);
        }

        /**
         * Register new web application
         *
         * @param string $app
         * @param string $handler
         * @return bool
         */
        public static function registerApplication(string $app, string $handler): bool
        {
            if (isset(self::$registeredProviders[$app])) {
                return error("Web App provider `%s' is already registered", $app);
            }
            try {
                if (!(new \ReflectionClass($handler))->isSubclassOf(Unknown::class)) {
                    fatal("Cannot register %s: %s", $handler, Unknown::class . ' is not implemented');
                }
            } catch (\ReflectionException $e) {
                fatal("Cannot register %s: %s", $handler, $e->getMessage());
            }
            self::$registeredProviders[$app] = $handler;

            return true;
        }

        /**
         * Snapshot a web application
         *
         * @param string $hostname
         * @param string $path
         * @param string $comment
         * @return bool
         */
        public function snapshot(string $hostname, string $path = '', string $comment = 'snapshot'): bool
        {
            $approot = $this->getAppRoot($hostname, $path);
            $docroot = $this->getDocumentRoot($hostname, $path);
            $git = Git::instantiateContexted(
                $this->getAuthContext(), [
                    $approot,
                    MetaManager::factory($this->getAuthContext())->get($docroot)
                ]
            );
            if (!$git->enabled()) {
                return error("Snapshots are not enabled for `%s%s'", $hostname, $path);
            }

            return $git->snapshot($comment) !== null;
        }

        /**
         * Rollback specified snapshot
         *
         * @param string      $hostname
         * @param string      $path
         * @param string|null $commit   optional commit
         * @return bool
         */
        public function rollback(string $hostname, string $path = '', string $commit = null): bool
        {
            $approot = $this->getAppRoot($hostname, $path);
            $docroot = $this->getDocumentRoot($hostname, $path);
            $meta = MetaManager::factory($this->getAuthContext())->get($docroot);
            $git = Git::instantiateContexted(
                $this->getAuthContext(), [
                    $approot,
                    $meta
                ]
            );
            if (!$git->enabled()) {
                return error("Snapshots are not enabled for `%s%s'", $hostname, $path);
            }

            $prune = null === $commit;
            if (!$commit && null === ($commit = $git->lastSnapshot())) {
                return error("No snapshots found for `%s%s'", $hostname, $path);
            }

            $handler = static::handlerFromApplication($this->getAppName());
            return $git->restore($commit, $prune) &&
                $this->fortify($hostname, $path, data_get($meta, 'fortify', $handler::DEFAULT_FORTIFICATION));
        }

        /**
         * Get handler from application
         *
         * @param string $app
         * @return string
         */
        public static function handlerFromApplication(string $app): string
        {
            static $map = [];
            if (isset($map[$app])) {
                return $map[$app];          }
            return $map[$app] = self::$registeredProviders[$app] ?? (self::class . '\\App\\Type\\' . ucwords($app ?: 'unknown') . '\\Handler');
        }
    }