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

    use Module\Support\Aliases;
    use Module\Support\Webapps\MetaManager;
    use Opcenter\License;
    use Opcenter\Map;
    use Opcenter\Service\ConfigurationContext;

    /**
     * Aliases and shared domains
     *
     * @package core
     */
    class Aliases_Module extends Aliases
    {
        const DEPENDENCY_MAP = [
            'siteinfo',
            'apache',
            'users'
        ];

        /** addon domain dns verification record */
        const DNS_VERIFICATION_RECORD = 'newacct';

        /**
         * void __construct(void)
         *
         * @ignore
         */
        public function __construct()
        {
            $this->exportedFunctions = array(
                '*'                  => PRIVILEGE_SITE,
                'add_domain_backend' => PRIVILEGE_SERVER_EXEC | PRIVILEGE_SITE,
                'map_domain'         => PRIVILEGE_SERVER_EXEC,
            );
            parent::__construct();
        }

        /**
         * Post-verification add_domain()
         *
         * @param string $domain
         * @param string $path
         * @return bool
         */
        public function add_domain_backend(string $domain, string $path): bool
        {
            $parent = dirname($path);

            if (!file_exists($this->domain_fs_path() . $parent)) {
                warn('%s: parent directory does not exist', $parent);
                if (!$this->file_create_directory($parent, 0755, true)) {
                    return error('failed to create parent directory');
                }
            }
            if (!$this->createDocumentRoot($path)) {
                return error("failed to create document root `%s'", $path);
            }
            $stat = $this->file_stat($path);
            $user = null;
            if (isset($stat['owner'])) {
                $user = $stat['owner'];
                if (ctype_digit($user)) {
                    warn("no such user found for domain `%s' uid `%d'", $domain, $user);
                    $user = null;
                }
            } else {
                Error_Reporter::report('Bad stat response: ' . var_export($stat, true));
            }

            if (!$user && $stat['uid'] < \User_Module::MIN_UID) {
                return error("unable to determine ownership of docroot `%s' for `%s'",
                    $path, $domain);
            } else if (!$user) {
                warn("invalid uid `%d' detected on `%s', squashed to account uid `%d'",
                    $stat['uid'],
                    $domain,
                    $this->user_id
                );
                $this->file_chown($path, $this->user_id, true);
                $user = $this->username;
            }

            $ret = $this->add_alias($domain);
            if (!$ret) {
                file_exists($path) && unlink($path);

                return error("failed to add domain alias configuration `%s'", $domain);
            }

            $this->notify_admin($domain, $path);

            if (!$this->map_domain('add', $domain, $path, $user)) {
                return error("failed to map domain `%s' in http configuration", $domain);
            }
            $this->removeBypass($domain);

            return true;
        }

        /**
         * Add hostname to account configuration
         *
         * add_alias() implies that prereq checks have been made,
         * including duplication checks
         *
         * @param string $alias
         * @return bool
         */
        protected function add_alias(string $alias): bool
        {
            if (!IS_CLI) {
                return error('%s should be called from backend', __METHOD__);
            }

            $alias = strtolower($alias);
            if (!preg_match(Regex::DOMAIN, $alias)) {
                return error('%s: invalid domain', $alias);
            }

            $license = License::get();

            if ($license->isDevelopment() && substr($alias, -5) !== '.test') {
                return error("License permits only .test TLDs. `%s' provided.", $alias);
            }

            $aliases = (array)$this->getServiceValue('aliases', 'aliases');
            $aliases[] = $alias;
            $limit = $this->getServiceValue('aliases', 'max', null);
            if (null !== $limit && count($aliases) > $limit) {
                return error("account has reached max amount of addon domains, `%d'", $limit);
            }

            $count = \count(Map::load(Map::home() . '/' . Map::DOMAIN_MAP, 'r-')->fetchAll());
            if ($license->hasDomainCountRestriction() && ++$count > $license->getDomainLimit()) {
                return error('License limit reached for domain count: %(limit)d',
                    ['limit' => $license->getDomainLimit()]);
            }

            return $this->setConfigJournal('aliases', 'enabled', 1) &&
                $this->setConfigJournal('aliases', 'aliases', $aliases);
        }

        /**
         * Notify appliance admin domain has been added
         *
         * @param string $domain
         * @param string $path
         * @return bool
         */
        protected function notify_admin(string $domain, string $path): bool
        {
            if (!DOMAINS_NOTIFY) {
                return false;
            }

            $template = \BladeLite::factory('views/email');
            $html = $template->make('aliases.domain-add',
                [
                    'domain'     => $domain,
                    'path'       => $path,
                    'authdomain' => $this->domain,
                    'authuser'   => $this->username,
                    'siteid'     => $this->site_id,
                ]
            )->render();

            $opts = array(
                'html_charset' => 'utf-8',
                'text_charset' => 'utf-8'
            );
            $from = \Crm_Module::FROM_NAME . ' <' . \Crm_Module::FROM_ADDRESS . '>';
            $headers = array(
                'Sender' => $from,
                'From'   => $from
            );
            $mime = new Mail_Mime($opts);

            $mime->setHTMLBody($html);
            $mime->setTXTBody(strip_tags($html));
            $headers = $mime->txtHeaders($headers);
            $msg = $mime->get();

            return Mail::send(
                \Crm_Module::COPY_ADMIN,
                'Domain Added',
                $msg,
                $headers
            );

        }

        /**
         * Manage domain symlink mapping
         *
         * @todo   merge into web module
         *
         * @param  string $mode   add/delete
         * @param  string $domain domain to add/remove
         * @param  string $path   domain path
         * @param  string $user   user to assign mapping
         * @return bool
         */
        public function map_domain(string $mode, string $domain, string $path = null, string $user = null): bool
        {
            if (!IS_CLI) {
                return $this->query('aliases_map_domain',
                    $mode,
                    $domain,
                    $path,
                    $user);
            }

            $mode = substr($mode, 0, 3);
            if (!preg_match(Regex::DOMAIN, $domain)) {
                return error($domain . ': invalid domain');
            }
            if ($mode != 'add' && $mode != 'del') {
                return error($mode . ': invalid map operation');
            }
            if ($mode == 'del') {
                return $this->removeMap($domain) &&
                    $this->file_delete('/home/*/all_domains/' . $domain);
            } else if ($mode == 'add') {
                if (!$user) {
                    $stat = $this->file_stat($path);
                    if ($stat instanceof Exception) {
                        return error($stat->getMessage());
                    }

                    $user = $this->user_get_username_from_uid($stat['uid']);
                }
                if ($user) {
                    if ($user == $this->tomcat_system_user()) {
                        $user = $this->username;
                        $uid = $this->user_get_uid_from_username($user);
                    } else {
                        $uid = $this->user_get_uid_from_username($user);
                        if ($uid < User_Module::MIN_UID) {
                            $user = $this->username;
                        }
                    }

                    $user_home = '/home/' . $user;
                    $user_home_abs = $this->domain_fs_path() . $user_home;

                    if (!file_exists($this->domain_fs_path() . $path)) {
                        warn($path . ': path does not exist, creating link');
                    }
                    if (!file_exists($user_home_abs . '/all_domains')) {
                        $this->file_create_directory($user_home . '/all_domains');
                        $this->file_chown($user_home . '/all_domains', $user);
                    }
                    // remove symlink if domain previously added
                    $fullpath = $this->domain_fs_path() . $user_home . '/all_domains/' . $domain;
                    // sometimes clients do dumb things, like remove the symlink and recreate
                    // as an empty directory
                    clearstatcache(true, $fullpath);
                    if (is_link($fullpath)) {
                        unlink($fullpath);
                    } else if (is_dir($fullpath)) {
                        Error_Reporter::mute_warning(true);
                        if (!rmdir($fullpath)) {
                            warn('not creating symlink all_domains/%s; a directory was found within ' .
                                'that contains files', $domain);
                        }
                        Error_Reporter::unmute_warning();
                    }
                    // and sometimes clients can do really dumb things like
                    // assign a doc root under all_domains/
                    $localpath = $user_home . '/all_domains/' . $domain;
                    if (!file_exists($fullpath)) {
                        $this->file_symlink($path, $localpath);
                    } else {
                        warn('cannot make symlink %s - file exists, possibly misplaced docroot?',
                            $localpath
                        );
                    }
                } else {
                    warn($domain . ': cannot determine user for domain mapping');
                }
            }
            if ($mode == 'add') {
                return $this->addMap($domain, $path);
            }

            return $this->removeMap($domain);
        }

        /**
         * Domain is exempt from DNS verification requirements
         *
         * @param $domain
         * @return bool
         */
        public function bypass_exists(string $domain): bool
        {
            return $this->isBypass($domain);
        }

        /**
         * Modify shared domain settings
         *
         * @param  string $domain
         * @param  array  $newparams
         * @return bool
         */
        public function modify_domain(string $domain, array $newparams): bool
        {
            if (!IS_CLI) {
                $ret = $this->query('aliases_modify_domain', $domain, $newparams);
                if (!$this->inContext()) {
                    \Preferences::reload();
                }
                $this->web_purge();

                return $ret;
            }
            if (!$this->domain_exists($domain)) {
                return error("domain `$domain' is not attached to account");
            }
            if ($this->shared_domain_hosted($domain)) {
                return error("domain `$domain' is hosted by another account");
            }
            if ($domain === $this->getConfig('siteinfo', 'domain')) {
                return error('cannot modify primary domain');
            }

            if (isset($newparams['owner'])) {
                $newowner = $newparams['owner'];
                if (!$this->_change_owner($domain, $newowner)) {
                    return false;
                }
            }

            if (isset($newparams['path'])) {
                $path = $newparams['path'];
                if (!$this->_change_path($domain, $path)) {
                    return false;
                }
            }

            if (isset($newparams['domain'])) {
                if (License::get()->isDevelopment() && substr($newparams['domain'], -5) !== '.test') {
                    return error("License permits only .test TLDs. `%s' provided.", $newparams['domain']);
                }

                $newdomain = $newparams['domain'];
                if (!$this->_change_domain($domain, $newdomain)) {
                    return false;
                }
            }
            $this->web_purge();

            return true;
        }

        /**
         * Verify domain hosted on account
         *
         * @param string $domain
         * @return bool
         */
        public function domain_exists(string $domain): bool
        {
            return $domain === $this->getConfig('siteinfo', 'domain') ||
                array_key_exists($domain, $this->list_shared_domains());
        }

        /**
         * List shared domains attached to account
         *
         * @return array
         */
        public function list_shared_domains(): array
        {
            if (!IS_CLI) {
                $cache = \Cache_Account::spawn($this->getAuthContext());
                if (false !== ($aliases = $cache->get(static::CACHE_KEY))) {
                    return $aliases;
                }

                return $this->query('aliases_list_shared_domains');
            }

            return $this->transformMap();
        }

        /**
         * Shared domain is hosted by another account
         *
         * @param string $domain
         * @return bool
         */
        public function shared_domain_hosted(string $domain): bool
        {
            $domain = strtolower($domain);
            if ($this->dns_domain_hosted($domain, true)) {
                return true;
            }
            $id = Auth::get_site_id_from_domain($domain);
            if ($id && $id != $this->site_id) {
                return true;
            }

            return false;
        }

        private function _change_owner(string $domain, string $user): bool
        {
            $users = $this->user_get_users();
            if (!isset($users[$user])) {
                return error("user `$user' not found");
            }
            $map = $this->list_shared_domains();
            if (!array_key_exists($domain, $map)) {
                return error("domain `$domain' not found in domain map");
            }

            $path = $map[$domain];
            return $this->file_chown($path, $user, true);
        }

        private function _change_path(string $domain, string $newpath): bool
        {
            $map = $this->list_shared_domains();
            if (!array_key_exists($domain, $map)) {
                return error("domain `%s' not found in domain map", $domain);
            }

            if (!preg_match(Regex::ADDON_DOMAIN_PATH, $newpath)) {
                return error($newpath . ': invalid path');
            }
            $oldpath = $map[$domain];
            if (!$this->removeMap($domain)) {
                return false;
            }
            if (!file_exists($this->domain_fs_path() . $newpath)) {
                $this->createDocumentRoot($newpath);
            }
            if (!$this->addMap($domain, $newpath)) {
                // domain addition failed - revert
                $this->addMap($domain, $oldpath);

                return error("domain `$domain' path change failure - reverting");
            }

            if ($oldpath === $newpath) {
                return true;
            }

            return true;
        }

        private function _change_domain(string $domain, string $newdomain): bool
        {
            $map = $this->list_shared_domains();
            if (!array_key_exists($domain, $map)) {
                return error("domain `$domain' not found in domain map");
            }
            $path = $map[$domain];
            MetaManager::instantiateContexted($this->getAuthContext())
                ->merge($path, ['host' => $newdomain])->sync();
            $ret = $this->remove_domain($domain)
                && $this->_synchronize_changes() &&
                $this->add_domain($newdomain, $path);
            if ($ret) {
                warn('activate configuration changes for new domain to take effect');
            }

            return $ret;
        }

        /**
         * bool remove_domain(string)
         *
         * @param string $domain domain name to remove
         * @return bool
         */
        public function remove_domain(string $domain): bool
        {
            if (!IS_CLI) {
                $docroot = $this->web_get_docroot($domain);
                $status = $this->query('aliases_remove_domain', $domain);
                if ($status && $docroot) {
                    MetaManager::factory($this->getAuthContext())
                        ->forget($docroot)->sync();
                }

                return $status;
            }
            $domain = strtolower($domain);
            if (!preg_match(Regex::DOMAIN, $domain)) {
                return error("Invalid domain `$domain'");
            }
            $this->map_domain('delete', $domain);
            if (!$this->remove_alias($domain)) {
                return false;
            }

            /**
             * NB: don't call dns_remove_zone, the domain may be added back at a later date,
             * in which case the DNS will get clobbered
             */
            return true;
        }

        public function remove_alias(string $alias): bool
        {
            if (!IS_CLI) {
                return $this->query('aliases_remove_alias', $alias);
            }
            $alias = strtolower(trim($alias));
            if (!preg_match(Regex::DOMAIN, $alias)) {
                return error('Invalid domain');
            }

            $aliases = (array)array_get($this->getNewServices('aliases'), 'aliases', $this->getServiceValue('aliases', 'aliases'));

            $key = array_search($alias, $aliases, true);
            if ($key === false) {
                return error("domain `$alias' not found");
            }

            unset($aliases[$key]);
            if (!$aliases && !platform_is('7.5')) {
                $this->setConfigJournal('aliases', 'enabled', 0);
            }

            return $this->setConfigJournal('aliases', 'aliases', $aliases) instanceof Auth_Info_Account;
        }

        private function _synchronize_changes(): bool
        {
            if ($this->auth_is_inactive()) {
                return error('account is suspended, will not resync');
            }
            $cmd = new Util_Account_Editor($this->getAuthContext()->getAccount(), $this->getAuthContext());
            // pull in latest, unsynchronized config from new/
            $cmd->importConfig();
            $status = $cmd->edit();
            if (!$status) {
                return error('failed to activate domain changes');
            }
            info('Hang tight! Domain changes will be active within a few minutes, but may take up to 24 hours to work properly.');
            return true;
        }

        public function add_domain(string $domain, string $path): bool
        {
            $domain = preg_replace('/^www./', '', strtolower($domain));
            $path = rtrim(str_replace('..', '.', $path), '/') . '/';

            if (!preg_match(Regex::DOMAIN, $domain)) {
                return error($domain . ': invalid domain');
            } else if (!preg_match(Regex::ADDON_DOMAIN_PATH, $path)) {
                return error($path . ': invalid path');
            } else if ($domain === $this->getServiceValue('siteinfo', 'domain')) {
                return error('Primary domain may not be replicated as a shared domain');
            } else if ($domain === SERVER_NAME) {
                return error('Domain may not duplicate system hostname');
            }

            if (!$this->_verify($domain)) {
                return false;
            }

            return $this->query('aliases_add_domain_backend', $domain, $path);
        }

        protected function _verify(string $domain): bool
        {
            if ($this->domain_exists($domain)) {
                return error("domain `$domain' exists");
            }
            if (!$this->dns_verified($domain)) {
                return error("Domain must be verified through the DNS service first");
            }
            if (\in_array($domain, (array)$this->getServiceValue('aliases', 'aliases'), true)) {
                // allow domains attached via aliases,aliases to be added to account
                return true;
            }
            if ($this->shared_domain_hosted($domain)) {
                return error("`%s': domain is already hosted by another account", $domain);
            }

            if (!DOMAINS_DNS_CHECK) {
                return true;
            }

            if (!$this->dns_domain_on_account($domain) /** domain under same invoice */ &&
                !$this->_verify_dns($domain) && !$this->_verify_url($domain)
            ) {
                $nameservers = $this->dns_get_authns_from_host($domain);
                $cpnameservers = $this->dns_get_hosting_nameservers($domain);
                $hash = $this->challenge_token($domain);
                $script = $hash . '.html';

                return error("`%s': domain has DNS records delegated to nameservers %s. " .
                    'Domain cannot be added to this account for security. Complete one of the following options to ' .
                    'verify ownership:' . "\r\n\r\n" .
                    '(1) Change nameservers to %s within the domain registrar' . "\r\n" .
                    "(2) Upload a html file to your old hosting provider accessible via http://%s/%s with the content:\r\n\t%s" . "\r\n" .
                    "(3) Create a temporary DNS record named %s.%s with an `A' resource record that points to %s" . "\r\n\r\n" .
                    'Please contact your previous hosting provider for assistance with performing any of ' .
                    'these verification options.',
                    $domain,
                    join(', ', $nameservers),
                    join(', ', $cpnameservers),
                    $domain,
                    $script,
                    $hash,
                    self::DNS_VERIFICATION_RECORD,
                    $domain,
                    $this->dns_get_public_ip()
                );
            }

            return true;
        }

        /**
         * Ensure a domain is not already hosted through Apis
         *
         * @param $domain
         * @return bool domain can be hosted
         */
        protected function _verify_dns(string $domain): bool
        {
            /*
             * workaround for account migrations which
             * duplicate domains across multiple servers
             * that no longer have DNS properly delegated
             *
             * @XXX DNS checks can be bypassed via API: BAD
             */
            if ($this->isBypass($domain)) {
                return true;
            }
            // domain not hosted, 5 second timeout
            $ip = silence(function () use ($domain) {
                return parent::__call('dns_gethostbyname_t', [$domain, 5000]);
            });
            if (!$ip) {
                return true;
            }

            $myip = (array)$this->dns_get_public_ip();
            foreach ($myip as $testip) {
                if ($ip === $testip) {
                    // domain is on this server and would appear in db lookup check
                    return true;
                }
            }
            if ($this->domain_is_delegated($domain)) {
                return true;
            }
            $record = self::DNS_VERIFICATION_RECORD . '.' . $domain;
            $tmp = $this->dns_gethostbyname_t($record, 1500);
            if ($tmp && \in_array($tmp, $myip, true)) {
                return true;
            }

            return false;
        }

        /**
         * Verify that a domain is delegated to hosting nameservers
         *
         * @param $domain
         * @return int
         */
        protected function domain_is_delegated(string $domain): int
        {
            if ($this->dns_domain_uses_nameservers($domain)) {
                return 1;
            }
            $ns = $this->dns_get_authns_from_host($domain);
            // no nameservers set, treat this as addable
            // some nameservers return records, some fail if the
            // target domain is not registered... may need workaround in future
            // query WHOIS?
            if (is_null($ns)) {
                return -1;
            }
            $hostingns = $this->dns_get_hosting_nameservers($domain);
            // uses at least 1 of the required nameservers, we're good

            foreach ($ns as $n) {
                if (in_array($n, $hostingns)) {
                    return 1;
                }
            }

            return 0;
        }

        protected function _verify_url(string $domain): bool
        {
            $hash = $this->challenge_token($domain);
            $url = 'http://' . $domain . '/' . $hash . '.html';
            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,
                    'follow_redirects' => true
                )
            );

            try {
                $response = $http->send();
                $code = $response->getStatus();
                switch ($code) {
                    case 303:
                    case 302:
                    case 301:
                    case 200:
                        break;
                    case 403:
                        return error('Verification URL request forbidden by server');
                    case 404:
                        return false;
                    default:
                        return error("Verification URL request failed, code `%d': %s",
                            $code, $response->getReasonPhrase());
                }
                $content = $response->getBody();
            } catch (HTTP_Request2_Exception $e) {
                return error("Fatal error retrieving verification URL: `%s'", $e->getMessage());
            }

            if (!preg_match("!^https?://$domain/$hash.html!", $response->getEffectiveUrl())) {
                return error(
                    'Verification URL request moved to different location other than accepted: %s',
                    $response->getEffectiveUrl()
                );
            }
            return trim(strip_tags($content)) === $hash;
        }

        /**
         * Get challenge token to verify ownership of domain
         *
         * @return string
         */
        public function challenge_token(): string
        {
            if (!IS_CLI) {
                return $this->query('aliases_challenge_token');
            }
            $str = (string)fileinode($this->domain_info_path('users'));

            return sha1($str);
        }

        public function remove_shared_domain(string $domain): bool
        {
            deprecated_func('Use remove_domain');

            return $this->remove_domain($domain);
        }

        public function add_shared_domain(string $domain, string $path): bool
        {
            deprecated_func('Use add_domain');

            return $this->add_domain($domain, $path);
        }

        public function shared_domain_exists($domain): bool
        {
            deprecated_func('use domain_exists');

            return $this->domain_exists($domain);
        }

        /**
         * Compare domain configuration journal
         *
         * @return array
         */
        public function list_unsynchronized_domains(): array
        {
            $active = parent::getActiveServices('aliases');
            $active = $active['aliases'];
            $pending = parent::getNewServices('aliases');
            if ($pending === null) {
                return ['add' => [], 'remove' => []];

            }
            if ($pending) {
                $pending = $pending['aliases'];
            }
            $domains = array_keys($this->list_shared_domains());
            $changes = array(
                'add'    => array_diff($pending, $active),
                'remove' => array_diff($active, $domains)
            );

            return $changes;
        }

        /**
         * Account has unjournaled domain configuration
         *
         * @return bool
         */
        public function changes_pending(): bool
        {
            if (!IS_CLI) {
                // info/ is 0700 root:root
                return $this->query('aliases_changes_pending');
            }
            return file_exists($this->domain_info_path('new/aliases'));
        }

        public function synchronize_changes(): bool
        {
            if (!IS_CLI) {
                $ret = $this->query('aliases_synchronize_changes');
                $this->freshenAuthContext();
                return $ret;
            }
            $aliases = array_keys($this->list_shared_domains());
            if (!platform_is('7.5')) {
                $this->setConfigJournal('aliases', 'enabled', (int)(count($aliases) > 0));
            }
            $this->setConfigJournal('aliases', 'aliases', $aliases);

            return $this->_synchronize_changes();
        }

        /**
         * array list_aliases()
         *
         * @return array aliases associated to the domain
         */
        public function list_aliases(): array
        {
            $values = $this->getServiceValue('aliases', 'aliases');

            return (array)$values;
        }

        public function _reset(Util_Account_Editor &$editor = null)
        {
            $module = 'aliases';
            $params = array('aliases' => array());
            if (!platform_is('7.5')) {
                $params['enabled'] = 0;
            }
            if ($editor) {
                foreach ($params as $k => $v) {
                    $editor->setConfig($module, $k, $v);
                }
            }

            return array($module => $params);
        }

        public function _edit()
        {
            $conf_old = $this->getAuthContext()->conf('siteinfo', 'old');
            $conf_new = $this->getAuthContext()->conf('siteinfo', 'new');
            $domainold = $conf_old['domain'];
            $domainnew = $conf_new['domain'];

            // domain name change via auth_change_domain()
            if ($domainold !== $domainnew && $this->isBypass($domainnew)) {
                $this->removeBypass($domainnew);
            }
            $aliasesnew = array_get($this->getAuthContext()->conf('aliases', 'new'), 'aliases', []);
            $aliasesold = array_get($this->getAuthContext()->conf('aliases', 'old'), 'aliases', []);

            $add = array_diff($aliasesnew, $aliasesold);
            $rem = array_diff($aliasesold, $aliasesnew);
            $db = Map::load(Map::DOMAIN_MAP, 'wd');

            foreach ($add as $a) {
                $db->insert($a, $this->site);
            }

            foreach ($rem as $r) {
                if ($r === $this->domain) {
                    // domain promoted from alias to primary
                    continue;
                }
                $db->delete($r);
            }
            $db->close();

            return;
        }

        public function _create()
        {
            $db = Map::write(Map::DOMAIN_MAP);
            $conf = array_get($this->getAuthContext()->conf('aliases'), 'aliases', []);
            foreach ($conf as $domain) {
                $db->insert($domain, $this->site);
            }
            $db->close();
        }

        public function _delete()
        {
            if (platform_is('7.5')) {
                return;
            }
            $db = Map::write(Map::DOMAIN_MAP);
            $conf = array_get($this->getAuthContext()->conf('aliases'), 'aliases', []);
            foreach ($conf as $domain) {
                $db->delete($domain);
            }
            $db->close();
        }

        public function _edit_user(string $user, string $usernew, array $oldpwd)
        {
            if ($user === $usernew) {
                return;
            }

            $domains = $this->list_shared_domains();
            $home = $oldpwd['home'];
            $newhome = preg_replace('!' . DIRECTORY_SEPARATOR . $user . '!', DIRECTORY_SEPARATOR . $usernew, $home, 1);
            foreach ($domains as $domain => $path) {
                if (0 !== strpos($path, $home)) {
                    continue;
                }
                $newpath = preg_replace('!^' . $home . '!', $newhome, $path);
                if (!$this->_change_path($domain, $newpath)) {
                    warn("failed to update domain `%s'", $domain);
                }
            }
            $this->web_purge();

            return true;
        }

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

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

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


    }