function validate_server_hostname($vars)
{
    lg_debug("Validating this: " . $vars["hostname"]);
    if (!validate_dns_domainname($vars["hostname"])) {
        return "Error: Invalid hostname - Hostname must be like: <b>(yourserver).yourdomain.tld ( example: supserserver.com </b>or<b> server666.superserver.com )</b>";
    }
    lg_debug("validated: " . validate_dns_domainname($vars["hostname"]));
}
function unix_ssh_local_redirect($local_port, $ssh_target, $remote_host, $remote_port, $duration = 1800)
{
    $ssh_key_file = "/var/www/.ssh/id_citrix_vminfo";
    lg_debug("SSH-Connection to {$ssh_target} for port forwarding from port {$local_port} to {$remote_host}:{$remote_port}");
    $ssh_options = "-p 59172 -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no";
    $forward = "-L {$local_port}:{$remote_host}:{$remote_port}";
    $ssh_command = "/usr/bin/ssh >/tmp/ssh_forward.log 2>&1 {$ssh_options} {$forward} -i {$ssh_key_file} -l citrix_info {$ssh_target} sleep {$duration} &";
    lg_debug("SSH-Command: {$ssh_command}");
    $ssh = `{$ssh_command}`;
}
function websocket_proxy_start($listen_port, $vnc_host, $vnc_port, $duration = 60, $client_ip)
{
    lg_debug("Starting Console Proxy");
    lg_debug("Proxy-Start-Command: /var/www/novnc/start_proxy {$listen_port} {$vnc_host} {$vnc_port} {$duration}");
    system("/var/www/novnc/init/start_proxy {$listen_port} {$vnc_host} {$vnc_port} {$duration} {$client_ip}");
}
/**
 * Show server provisioning page
 */
function nocprovisioning_provision($params)
{
    try {
        /* against XSS attacks */
        if ($_SERVER['REQUEST_METHOD'] == "POST" && $_POST['nps_nonce'] != $_SESSION['nps_nonce']) {
            throw new Exception('Nonce value does not match');
        }
        if ($params[NOCPS_CONFIG_ENABLE_PROVISIONING] != 'on') {
            throw new Exception('Not allowed');
        }
        $api = nocprovisioning_api($params);
        $ip = nocprovisioning_getServerIP($params["serviceid"]);
        $mac = nocprovisioning_getServerMAC($params["serviceid"]);
        $error = "";
        if (!empty($_POST['profile'])) {
            /* Never trust user input. Double check if profile is not blacklisted */
            $whitelist = array_filter(explode(' ', $params[NOCPS_CONFIG_WHITELIST]));
            $blacklist = array_filter(explode(' ', $params[NOCPS_CONFIG_BLACKLIST]));
            $profile = $api->getProfile(intval($_POST['profile']));
            $profileid = intval($_POST['profile']);
            $tags = explode(' ', $profile['data']['tags']);
            if (count($whitelist) && !in_array($profileid, $whitelist) && count(array_intersect($tags, $whitelist)) == 0) {
                throw new Exception("Profile is not on whitelist");
            } else {
                if (count($blacklist) && (in_array($profileid, $blacklist) || count(array_intersect($tags, $blacklist)))) {
                    throw new Exception("Profile is on blacklist");
                }
            }
            /* --- */
            if (empty($params[NOCPS_CONFIG_REQUIRE_IPMIPASSWORD])) {
                $rebootmethod = 'auto';
                $ipmipassword = '';
                /* use password stored in db */
            } else {
                if (empty($_POST['ipmipassword'])) {
                    throw new Exception("Enter your server's IPMI password");
                }
                $rebootmethod = 'ipmi';
                $ipmipassword = $_POST['ipmipassword'];
            }
            /* Provision server */
            lg_debug("password : "******"rootpassword"]);
            lg_debug("password2: " . $_POST["rootpassword2"]);
            $result = $api->provisionHost(array("mac" => $mac, "hostname" => $_POST["hostname"], "profile" => $profileid, "rootpassword" => $_POST["rootpassword"], "rootpassword2" => $_POST["rootpassword2"], "adminuser" => $_POST["adminuser"], "userpassword" => $_POST["userpassword"], "userpassword2" => $_POST["userpassword2"], "disk_addon" => $_POST["disklayout"], "packages_addon" => $_POST["packageselection"], "extra_addon1" => $_POST["extra1"], "extra_addon2" => $_POST["extra2"], "rebootmethod" => $rebootmethod, "ipmipassword" => $ipmipassword));
            if ($result['success']) {
                $n = $profile['data']['name'];
                if ($_POST['disklayout']) {
                    $n .= '+' . $_POST['disklayout'];
                }
                if ($_POST['packages_addon']) {
                    $n .= '+' . $_POST['packages_addon'];
                }
                if ($_POST['extra1']) {
                    $n .= '+' . $_POST['extra1'];
                }
                if ($_POST['extra2']) {
                    $n .= '+' . $_POST['extra2'];
                }
                nocprovisioning_log("Provisioning server - Profile '{$n}' - MAC {$mac}", $params);
            } else {
                /* input validation error */
                foreach ($result['errors'] as $field => $msg) {
                    $error .= $field . ': ' . htmlentities($msg) . '<br>';
                }
                lg_err("Error trying to provision - " . str_replace("<br>", " - ", $error));
                // nocprovisioning_log("Error trying to provision - ".str_replace("<br>", " - ", $error), $params);
            }
        } else {
            if (!empty($_POST['cancelprovisioning'])) {
                /* Cancel provisioning */
                $api->cancelProvisioning($mac);
                nocprovisioning_log("Cancelled provisioning - MAC {$mac}", $params);
            }
        }
        $status = $api->getProvisioningStatusByServer($mac);
        if ($status) {
            /* Host is already being provisioned */
            return array('templatefile' => 'provision-status', 'vars' => array('ip' => $ip, 'mac' => $mac, 'serviceid' => $params["serviceid"], 'nonce' => $_SESSION['nps_nonce'], 'status' => $status));
        } else {
            $profiles = $api->getProfileNames(0, 1000);
            $addons = $api->getProfileAddonNames(0, 1000);
            /* Check profile against white- and blacklist */
            $whitelist = array_filter(explode(' ', $params[NOCPS_CONFIG_WHITELIST]));
            $blacklist = array_filter(explode(' ', $params[NOCPS_CONFIG_BLACKLIST]));
            foreach ($profiles['data'] as $k => $profile) {
                $tags = explode(' ', $profile['tags']);
                /* Check wheter the profile ID or any of its tags are on the whitelist */
                if (count($whitelist) && !in_array($profile['id'], $whitelist) && count(array_intersect($tags, $whitelist)) == 0) {
                    /* not on whitelist, remove */
                    unset($profiles['data'][$k]);
                } else {
                    if (count($blacklist) && (in_array($profile['id'], $blacklist) || count(array_intersect($tags, $blacklist)))) {
                        /* on blacklist, remove */
                        unset($profiles['data'][$k]);
                    }
                }
            }
            /* --- */
            require_once 'Zend/Json.php';
            return array('templatefile' => 'provision', 'vars' => array('ip' => $ip, 'mac' => $mac, 'serviceid' => $params["serviceid"], 'nonce' => $_SESSION['nps_nonce'], 'profiles' => $profiles['data'], 'addons_json' => Zend_Json::encode($addons['data']), 'profiles_json' => Zend_Json::encode(array_values($profiles['data'])), 'error' => $error, 'ask_ipmi_password' => !empty($params[NOCPS_CONFIG_REQUIRE_IPMIPASSWORD])));
        }
    } catch (Exception $e) {
        nocprovisioning_log("Provisioning error - " . $e->getMessage(), $params);
        die('<b>Error: </b>' . $e->getMessage());
    }
}
function citrix_set_vcore_count($xen_server, $vm_name, $vcore_count)
{
    $ssh_key_file = "/var/www/.ssh/id_citrix_vminfo";
    lg_debug("SSH-Connection to {$xen_server} to set vcores of {$vm_name} to {$vcore_count}");
    $ssh_options = "-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no";
    $ssh_command = "/usr/bin/ssh 2>&1 {$ssh_options} -i {$ssh_key_file} -l citrix_info {$xen_server}  /usr/bin/sudo /usr/local/bin/citrix_set_vcores {$vm_name} {$vcore_count}";
    lg_debug("{$ssh_command}");
    $ssh_output = popen("{$ssh_command}", "r");
    do {
        $line = fgets($ssh_output);
        lg_debug2($line);
    } while ($line);
    pclose($ssh_output);
    return $vnc_port;
}
function get_host_name_from_service_id($serviceid)
{
    $q = mysql_query("SELECT domain FROM tblhosting WHERE id='{$serviceid}';");
    lg_debug("Servername for service ID {$serviceid} is " . mysql_result($q, 0));
    return mysql_result($q, 0);
}