<?php
function clean($str) { 
  $search  = array('&'    , '"'     , "'"    , '<'   , '>'    ); 
  $replace = array('&amp;', '&quot;', '&#39;', '&lt;', '&gt;' ); 
  $str = str_replace($search, $replace, $str);
  $strf = htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
  return $strf; 
}

if(isset($_REQUEST['logout'])){
    session_start();
    session_unset(); 
    session_destroy();
} else {
    session_start();
}

$mode="";

function checkvm($vmname) {
    $shellout = shell_exec("/usr/bin/nlvmi checkvm $vmname bla");//){
    if (preg_match_all('/not running/', $shellout)){
        return 1;
    }
    return 0;
}

function serverdepropdown($server, $val, $what){
    if ($what == "cdrom"){
        $dir = "isodirectory";
        $enddiv = "</div>";
    } elseif (preg_match('/drive/', $what)) {
        $dir = "vmdirectory";
        $enddiv="";
    }
    echo "<div class=row><div class=col-md-1 style=text-align:right>$what</div><div class=col-md-2><div class=dropdown><button class=\"btn btn-secondary dropdown-toggle\" type=button id=".$what."button data-toggle=dropdown aria-haspopup=true aria-expanded=false>$val</button>";
    echo "<div class=dropdown-menu aria-labelledby=".$what."button>";
    echo "<a class=dropdown-item href=\"javascript:dropdown('".$what."button','')\">no $what</a><div class=dropdown-divider></div>";
    $shellout=shell_exec("/usr/bin/nlvmi listdirs $server $dir");
    $files = explode("\n", $shellout);
    for ($f=0; $f<count($files); $f++){
        $file = explode(" ", $files[$f]);
        $lastpart = count($file) -1;
        if((preg_match('/\//', $file[$lastpart]))&&(!preg_match('/^d/', $file[0]))){
            echo "<a class=dropdown-item href=\"javascript:dropdown('".$what."button','$file[$lastpart]')\">$file[$lastpart]</a>";
        }
    }
    echo "$enddiv</div></div></div><input type=hidden id=".$what."buttonh name=$what value=\"$val\">";
}

function formatbuttons($label, $val){
    echo "<div class=row><div class=col>$label</div><div class=col><div class=dropdown><button class=\"btn btn-secondary dropdown-toggle\" type=button id=".$label."button$label data-toggle=dropdown aria-haspopup=true aria-expanded=false>$val</button>";
    echo "<div class=dropdown-menu aria-labelledby=formatbutton$label>";
    echo "<a class=dropdown-item href=\"javascript:dropdown('".$label."button$label','')\">&nbsp</a>";
    echo "<div class=dropdown-divider></div>";
    echo "<a class=dropdown-item href=\"javascript:dropdown('".$label."button$label','raw')\">raw</a>";
    echo "<a class=dropdown-item href=\"javascript:dropdown('".$label."button$label','qcow2')\">qcow2</a>";
    echo "</div></div></div></div></div><input type=hidden id=".$label."button".$label."h name=$label value=\"$val\">";
}

function listimg($server,$dir){
    $shellout=shell_exec("/usr/bin/nlvmi listdirs $server $dir");
    $files = explode("\n", $shellout);
    echo "<div id=listimgd class=form-group><label for=ld><select class=form-control id=ld>";
    for ($f=0; $f<count($files); $f++){
        $file = explode(" ", $files[$f]);
        $lastpart = count($file) -1;
        $filenames = explode('/', $file[$lastpart]);
        $filenamep = count($filenames) -1;
        $filename = $filenames[$filenamep];
        if((preg_match('/\//', $file[$lastpart]))&&(!preg_match('/^d/', $file[0]))){
            echo "<option>$filename</option>";
        }
    }
    echo "</select></label></div>";
}

//read config file
$configfile = new SplFileObject("/etc/nlvmi/nlvmi.conf");
while (!$configfile->eof()) {
    $line = $configfile->fgets();
    if (!preg_match('/^#/', $line)){
        if (!preg_match('/^$/', $line)){
            if (preg_match('/=/', $line)){
                $configparam = explode('=', $line);
                $p = rtrim($configparam[1]);
                //echo "B$p";
                $config[$configparam[0]]=str_replace('"', '', $p);
            }
        }
    }
}
$file = null;

//check db connection
if ($config['DATABASETYPE']=="sqlite"){
    $db_handle = new SQLite3($config['SQLITEFILE']);
    $query = "SELECT name FROM sqlite_master WHERE type='table' AND name='vms';";
    $db_handle->exec($query);
    $result = $db_handle->query($query);
    $row = $result->fetchArray();
    if (!$row['name']=="vms"){
        echo "DB connection failed!";
        exit;
    }
}

//check login
$usersfound = "no";
$sql="SELECT * FROM users LIMIT 1";
$res = $db_handle->query($sql);
while ($row = $res->fetchArray(SQLITE3_ASSOC)){
    $usersfound="yes";
    if ($_SESSION['username']=="inituser"){
        session_unset(); 
        session_destroy();
        session_start();
        echo "killed inituser!";
    }
}

if ($usersfound=="no"){
    $_SESSION['username']="inituser";
    $_SESSION['isadmin']="1";
    if (!isset($_POST['newusername'])){
        echo "<h1>You have no users in the datbase!</h1></br>";
        $mode="usermgmt";
    }
} elseif ((isset($_POST['login']))&&(isset($_POST['username']))&&(isset($_POST['password']))){
    $user = clean($_POST['username']);
    $pass = clean($_POST['password']);
    if ($pass == ""){
        echo "$user is not allowed to login without a password.";
    } else {
        $sql="SELECT password,admin FROM users WHERE username='$user'";
        $res = $db_handle->query($sql);
        while ($row = $res->fetchArray(SQLITE3_ASSOC)){
            if (password_verify($pass, $row['password'])){
                $_SESSION['username']=$user;
                $_SESSION['isadmin']=$row['admin'];
            } else {
                echo "Password not correct!";
            }
        }
    }
}

function checkmacfree($vmname,$mac,$db_handle){
    $sql="SELECT vmname FROM vms WHERE (macaddr1='$mac' OR macaddr2='$mac' OR macaddr3='$mac') AND NOT vmname='$vmname'";
    //echo "na";
    $res = $db_handle->query($sql);
    while ($row = $res->fetchArray(SQLITE3_ASSOC)){
        return "$row[vmname] uses the mac $mac already!";
    }
    return 0;
}

if (isset($_POST['checkmac'])){
    $mac = clean($_POST['checkmac']);
    $mf = checkmacfree('novm', $mac, $db_handle);
    if ($mf == 0){
        echo "mac is free";
    } else {
        echo "mac not free";
    }
    exit;

//delete vms
} elseif (isset($_SESSION['username'])){
    if ((isset($_POST['deleteid']))&&(isset($_POST['deletename']))&&($_POST['delwhat']=="vm")){
        if($_SESSION['isadmin']!=1){
            echo "you are not allowed to delete vms!";
        } else {
            $vmname = clean($_POST['deletename']);
            $vmid = clean($_POST['deleteid']);
            $sql="SELECT vms.id AS vid,prio,hostname,connectstring,autostart FROM vms LEFT JOIN servers ON vms.server = servers.hostname WHERE vmname='$vmname' AND vid='$vmid'";
            $res = $db_handle->query($sql);
            while ($row = $res->fetchArray(SQLITE3_ASSOC)){
                $prio = $row['prio'];
                $nextprio = $prio + 1;
                $lastprio = "no";
                while ($lastprio == "no"){
                    $sqln="SELECT id FROM vms WHERE prio='$nextprio'";
                    $nid = $db_handle->query($sqln)->fetchArray(SQLITE3_ASSOC)['id'];
                    if($nid == ""){
                        $lastprio = "yes";
                    } else {
                        $sqlu="UPDATE vms SET prio='$prio' WHERE id='$nid'";
                        if (!$db_handle->query($sqlu)){
                            echo "SQL $sqlu failed!";
                            exit;
                        } else {
                            $nextprio = $nextprio + 1;
                            $prio = $prio + 1;
                        }
                    }
                }
                if ($row['autostart'] == "1"){
                    if ($row['connectstring'] == ""){
                        $shellout = shell_exec("/usr/bin/nlvmi delautostart local $vmname");
                    } else {
                        $shellout = shell_exec("/usr/bin/nlvmi delautostart $row[connectstring] $vmname");
                    }
                }
                if (isset($config['NGINXCONFIGPATH'])){
                    $shellout = shell_exec("/usr/bin/nlvmi delnginx local $vmname");
                }
                $sqld="DELETE FROM vms WHERE id='$vmid'";
                if ($db_handle->query($sqld)){
                    echo "VM $vmname deleted!";
                }
            }
        }
    } elseif
//delete user    
    ((isset($_POST['deleteid']))&&(isset($_POST['deletename']))&&($_POST['delwhat']=="user")){
        if($_SESSION['isadmin']!=1){
            echo "you are not allowed to delete users!";
        } else {
            $uname = clean($_POST['deletename']);
            $uid = clean($_POST['deleteid']);
            $sql="SELECT id FROM users WHERE username='$uname' AND id='$uid'";
            $res = $db_handle->query($sql);
            while ($row = $res->fetchArray(SQLITE3_ASSOC)){
                $sqld="DELETE FROM users WHERE id='$uid'";
                if ($db_handle->query($sqld)){
                    echo "User $uname deleted!";
                }
            }
        }
    } elseif 
//delete server    
    ((isset($_POST['deleteid']))&&(isset($_POST['deletename']))&&($_POST['delwhat']=="server")){
        if($_SESSION['isadmin']!=1){
            echo "you are not allowed to delete vms!";
        } else {
            $sname = clean($_POST['deletename']);
            $sid = clean($_POST['deleteid']);
            $sql="SELECT id FROM servers WHERE hostname='$sname' AND id='$sid'";
            $res = $db_handle->query($sql);
            while ($row = $res->fetchArray(SQLITE3_ASSOC)){
                $sqld="DELETE FROM servers WHERE id='$sid'";
                if ($db_handle->query($sqld)){
                    echo "Server $sname deleted!";
                }
            }
        }
    } elseif
//delete image
    ((isset($_POST['deleteid']))&&(isset($_POST['deletename']))&&($_POST['delwhat']=="image")){
        if($_SESSION['isadmin']!=1){
            echo "you are not allowed to delete images!";
        } else {
            $server = clean($_POST['deletename']);
            $filec = explode(';', clean($_POST['deleteid']));
            
            $sql="SELECT id FROM servers WHERE hostname='$server' AND (vmdirectory LIKE '%$filec[0]%' OR isodirectory LIKE '%$filec[0]%')";
            $res = $db_handle->query($sql);
            while ($row = $res->fetchArray(SQLITE3_ASSOC)){
                $shellout = shell_exec("/usr/bin/nlvmi delimg $server $filec[0]/$filec[1]");
                echo $shellout;
            }
        }
    } elseif
//create new image
    (isset($_POST['createimg'])){
            $img = clean($_POST['createimg']);
            $server = clean($_POST['createimgs']);
            $dir = clean($_POST['createimgd']);
            $size = clean($_POST['createimgsize']);
            $sql="SELECT id FROM servers WHERE hostname='$server' AND (vmdirectory LIKE '%$dir%')";
            $res = $db_handle->query($sql);
            while ($row = $res->fetchArray(SQLITE3_ASSOC)){
                $shellout = shell_exec("/usr/bin/nlvmi createimg \"$server;$dir/$img\" $size");
                echo $shellout;
                exit;
            }
    }
//insert new user in db
    elseif(isset($_POST['newusername'])){
        if($_SESSION['isadmin']!=1){
            echo "you are not allowed to add usernames!";
        } else {
            $newusername = clean($_POST['newusername']);
            $newpassword = password_hash(clean($_POST['newpassword']), PASSWORD_DEFAULT);
            if ($_POST['isadmin']=="on"){
                $isadmin = "1";
            } else {
                $isadmin = "0";
            }
            $sqlu="SELECT id FROM users WHERE username='$newusername'";
            $res = $db_handle->query($sqlu);
            while ($row = $res->fetchArray(SQLITE3_ASSOC)){
                echo "username already exist!";
                exit;
            }
            $sql="INSERT INTO users (username,password,admin) VALUES('$newusername', '$newpassword', '$isadmin')";
            $res=$db_handle->query($sql);
            $res=$db_handle->query($sqlu);
            while ($row = $res->fetchArray(SQLITE3_ASSOC)){
                echo "success";
                exit;
            }
            echo "Failed to insert into DB!";
            exit;
        }
    }
//update user in db
    if(isset($_POST['changeusername'])){
        if($_SESSION['isadmin']!=1){
            echo "you are not allowed to change usernames!";
        } else {
            $userchange=clean($_POST['userchange']);
            $username=clean($_POST['changeusername']);
            if($_POST['passwordchange']==""){
                $passwd ="";
            } else {
                $pass=password_hash(clean($_POST['passwordchange']), PASSWORD_DEFAULT);
                $passwd="password='$pass',";
            }
            if ($_POST['isadmin']=="on"){
                $isadmin = "1";
            } else {
                $isadmin = "0";
            }
            $sql="UPDATE users SET username='$username', $passwd admin='$isadmin' where id='$userchange'";
            if($db_handle->query($sql)){
                echo "success";
                exit;
            }
        }
    }
//insert new server in db
    if(isset($_POST['newhostname'])){
        if($_SESSION['isadmin']!=1){
            echo "you are not allowed to add servers!";
        } else {
            $newservername = clean($_POST['newhostname']);
            $connectstring = clean($_POST['connectstring']);
            $vmdirectory = clean($_POST['vmdirectory']);
            $isodirectory = clean($_POST['isodirectory']);
            $sqlu="INSERT INTO servers ('hostname','connectstring','vmdirectory','isodirectory') VALUES('$newservername','$connectstring','$vmdirectory','$isodirectory')";
            //echo $sqlu;
            $res = $db_handle->query($sqlu);
                echo "success";
                exit;
        }
    }
//update server in db
    if(isset($_POST['changehostname'])){
        if($_SESSION['isadmin']!=1){
            echo "you are not allowed to change servers!";
        } else {
            $newservername = clean($_POST['changehostname']);
            $connectstring = clean($_POST['connectstring']);
            $vmdirectory = clean($_POST['vmdirectory']);
            $isodirectory = clean($_POST['isodirectory']);
            $changeid = clean($_POST['changeid']);
            $sql="UPDATE servers SET hostname='$newservername', connectstring='$connectstring', vmdirectory='$vmdirectory', isodirectory='$isodirectory' where id='$changeid'";
            if($db_handle->query($sql)){
                echo "success";
                exit;
            } else {
                echo "$sql";
                exit;
                }
        }
    }    
//insert or update vm in db
    if(isset($_REQUEST['mode'])){
        if($_REQUEST['mode']=="newvm"){
            $psql = "SELECT MAX(prio) AS prio FROM vms";
            $pres = $db_handle->query($psql);
            $prioa = $pres->fetchArray(SQLITE3_ASSOC);
            $prio = $prioa['prio'] + 1;
            $mode="newvm";
            $sqls="INSERT INTO vms ";
            $sqlc="(";
            $sqlv=" VALUES (";
            foreach(array_keys($_REQUEST) as $rkey){
                if (($rkey!="mode")&&($rkey!="rand")){
                    $rvalue = clean($_REQUEST[$rkey]);
                    if ((preg_match('/macaddr/', $rkey))&&($rvalue!="")){
                        $cm = checkmacfree(clean($_REQUEST['vmname']), $rvalue, $db_handle);
                        if ($cm != "0") {
                            echo $cm;
                            exit;
                        }
                    }
                    if ($rkey == "autostart"){
                        if ($rvalue == "on"){
                            $rvalue = "1";
                        } else {
                            $rvalue = "0";
                        }
                    }
                    if ($rvalue == "x86_64"){
                        $rvalue = "qemu-system-x86_64";
                    } elseif ((preg_match('/no drive/', $rvalue))||($rvalue == "no cdrom")){
                        $rvalue = "";
                    }
                    $sqlc .= "$rkey,";
                    $sqlv .= "'$rvalue',";    
                }
            }
            $sqlc.=" 'prio')";
            $sqlv.=" '$prio')";
            $sql = "$sqls$sqlc$sqlv";
            $res = $db_handle->exec($sql);
            echo "success";
            exit;
        } elseif ($_REQUEST['mode']=="editvm"){
            $sql="UPDATE vms SET ";
            $autostartfound = "0";
            foreach(array_keys($_REQUEST) as $rkey){
                if (($rkey!="mode")&&($rkey!="editid")&&($rkey!="rand")){
                    $rvalue = clean($_REQUEST[$rkey]);
                    if ((preg_match('/macaddr/', $rkey))&&($rvalue!="")){
                        $cm = checkmacfree(clean($_REQUEST['vmname']), $rvalue, $db_handle);
                        if ($cm != "0") {
                            echo $cm;
                            exit;
                        }
                    }
                    if ($rkey == "autostart"){
                        $autostartfound = "1";
                        if ($rvalue == "on"){
                            $rvalue = "1";
                        } else {
                            $rvalue = "0";
                        }
                    }
                    if ($rvalue == "x86_64"){
                        $rvalue = "qemu-system-x86_64";
                    } elseif ((preg_match('/no drive/', $rvalue))||($rvalue == "no cdrom")){
                        $rvalue = "";
                    }
                    $sql .= " $rkey='$rvalue',";
                }
            }
            if ($autostartfound == "0"){
                $sql .= " autostart='0'";
            } else {
                $sql = rtrim($sql, ',');
            }
            $eid=clean($_REQUEST['editid']);
            $sql .= " WHERE id='$eid'";
            $res = $db_handle->exec($sql);
            echo "success";
            exit;
        }
    }
    if (isset($_REQUEST['neworder'])){
        if (isset($_REQUEST['vid'])){
            $vid = clean($_REQUEST['vid']);
            $sql="SELECT prio FROM vms WHERE id='$vid'";
            $oldprio = $db_handle->query($sql)->fetchArray(SQLITE3_ASSOC)['prio'];
            if ($_REQUEST['neworder']=="up"){
                $newprio = $oldprio - 1;
                $sqlu="SELECT id FROM vms WHERE prio='$newprio'";
                $oldid = $db_handle->query($sqlu)->fetchArray(SQLITE3_ASSOC)['id'];
                $sqlm="UPDATE vms SET prio='$newprio' WHERE id='$vid'";
                $sqln="UPDATE vms SET prio='$oldprio' WHERE id='$oldid'";
                if(($db_handle->exec($sqlm))&&($db_handle->exec($sqln))){
                    echo "success";
                    exit;
                }
            } elseif ($_REQUEST['neworder']=="down"){
                $newprio = $oldprio + 1;
                $sqlu="SELECT id FROM vms WHERE prio='$newprio'";
                $oldid = $db_handle->query($sqlu)->fetchArray(SQLITE3_ASSOC)['id'];
                $sqlm="UPDATE vms SET prio='$newprio' WHERE id='$vid'";
                $sqln="UPDATE vms SET prio='$oldprio' WHERE id='$oldid'";
                if(($db_handle->exec($sqlm))&&($db_handle->exec($sqln))){
                    echo "success";
                    exit;
                }
            }
            
        }
    }
    if (isset($_POST['serverbuttoni'])){
        serverdepropdown($_POST['serverbuttoni'], "no drive1", 'drive1');
        formatbuttons('format1', '');
        serverdepropdown($_POST['serverbuttoni'], "no drive2", 'drive2');
        formatbuttons('format2', '');
        serverdepropdown($_POST['serverbuttoni'], "no drive3", 'drive3');
        formatbuttons('format3', '');
        serverdepropdown($_POST['serverbuttoni'], "no cdrom", 'cdrom');
        exit;
    }

    if (isset($_REQUEST['imagemgmt'])){
        $server = clean($_REQUEST['imagemgmt']);
        if ($server == "undefined"){
            $serverq = "";
        } else {
            $serverq = $server;
        }
        function imgdropdowns($db_handle, $server, $serverq, $dmode){
            $sqli="SELECT vmdirectory,isodirectory,hostname FROM servers";
            $resi = $db_handle->query($sqli);
            $sdropdown = "";
            $firstserver = "";
            while ($rowi = $resi->fetchArray(SQLITE3_ASSOC)){
                $hostname = $rowi['hostname'];
                if ($firstserver == ""){
                    $firstserver = $hostname;
                }
                $vmdirs = explode(';', $rowi['vmdirectory']);
                $isodirs = explode(';', $rowi['isodirectory']);
                $imgdirs[$hostname] = array_merge($vmdirs, $isodirs);
                $sdropdown .= "<a class=dropdown-item href=\"javascript:imgdropdown('server','$hostname', '$vmdirs[0]', '$dmode')\">$hostname</a>";
            }
            if ($serverq == ""){
                $serverq = $firstserver;
            }
            $dropdowns = "<div class=row><div class=col-sm><div class=dropdown><button class=\"btn btn-secondary dropdown-toggle\" type=button id=imageserverbutton$dmode data-toggle=dropdown aria-haspopup=true aria-expanded=false>$serverq</button>";
            $dropdowns .= "<div class=dropdown-menu aria-labelledby=imageserverbutton>$sdropdown</div></div></div>";
            foreach(array_keys($imgdirs) as $iserver){
                $firstdir = $imgdirs[$iserver][0];
                $hiddend = "d-none";
                if(($server == "undefined")&&($imgdirs[$firstserver][0] == $firstdir)&&($firstserver == $iserver)){
                    $hiddend = "";
                }
                $dropdowns .= "<div class=\"col-sm $hiddend\" id=imagedirdropd$iserver$dmode><div class=dropdown ><button class=\"btn btn-secondary dropdown-toggle\" type=button id=imagedirbutton$iserver$dmode data-toggle=dropdown aria-haspopup=true aria-expanded=false>$firstdir</button>";
                $dropdowns .= "<div class=dropdown-menu aria-labelledby=imagedirbutton$iserver>";
                for ($di=0; $di<count($imgdirs[$iserver]); $di++){
                    $dir = $imgdirs[$iserver][$di];
                    $dropdowns .= "<a class=dropdown-item href=\"javascript:imgdropdown('dir','$iserver','$dir', '$dmode')\">$dir</a>";
                }
                $dropdowns .= "</div></div></div>";
            }
            $dropdowns .= "</div><br/>";
            echo $dropdowns;
            if ($dmode == "source"){
                listimg($firstserver, $firstdir);
            }
        }
        imgdropdowns($db_handle, $server, $serverq, 'source');
        echo "<div class=d-none id=copytargetd>Target";
        imgdropdowns($db_handle, $server, $serverq, 'target');
        echo "<div class=row><div class=col-sm><input id=targetfilename name=targetfilenme type=text class=form-control placeholder=\"new filename\"></div></div><br/></div>";
        echo "<div class=row><div class=col-sm><a class=\"btn btn-primary\" id=copybtn onclick=imgcopy();>copy</a></div><div class=col-sm id=delimgbutton><button class=\"btn btn-danger\" data-delete-text=\"Delete image \" data-delete-what=image data-delete-id=\"\" data-delete-name=\"\" data-toggle=\"modal\" data-target=\"#confirm-delete\">Delete</button></div></div>";
        echo "<div id=newimgdiv><hr><div class=row ><div class=col-sm><input type=text class=form-control id=newimg placeholder=\"new image name\"></div><div class=col-md-3><input type=text class=form-control id=newimgsize placeholder=\"size in GB\"></div><div class=col-md-3><a class=\"btn btn-primary\" onclick=createimg();>create</a></div></div></div>";
        exit;
    }
    
    if ((isset($_REQUEST['listdir']))&&(isset($_REQUEST['server']))){
        $listdir = clean($_REQUEST['listdir']);
        $server = clean($_REQUEST['server']);
        $sqld="SELECT id FROM servers WHERE hostname = '$server' AND (vmdirectory LIKE '%$listdir%' OR isodirectory LIKE '%$listdir%')";
        $resd = $db_handle->query($sqld);
        while ($rowd = $resd->fetchArray(SQLITE3_ASSOC)){
            listimg($server, $listdir);
            exit;
        }
    }
    
    if (isset($_REQUEST['copyss'])){
        $sserver = clean($_REQUEST['copyss']);
        $sfile = clean($_REQUEST['copysf']);
        $tserver = clean($_REQUEST['copyts']);
        $tfile = clean($_REQUEST['copytf']);
        $shellout = shell_exec("export FID=\$\$; printf \"\$FID\"; /usr/bin/nlvmi copyimg \"$sserver;$sfile\" \"$tserver;$tfile\" 2&>/dev/null &");
        if (preg_match_all('/completed/', $shellout)){
            echo "success";
        } else {
            echo $shellout;
        }
        exit;
    }
    if (isset($_REQUEST['progress'])){
        $txt_file = file_get_contents("/tmp/$_REQUEST[progress]");
        if (preg_match('/noprogressavailable/', $txt_file)){
            echo "sorry, no progress available";
        } elseif(preg_match('/fail/', $txt_file)){
            echo "fail";
        } elseif(!preg_match('/^done/', $txt_file)){
            $row = explode(" ", $txt_file);
            $c = count($row) - 1;
            $pfound="no";
            while ($pfound == "no"){
                $field = $row[$c];
                if (preg_match('/%/', $field)){
                    $perc = explode('%', $field);
                    echo $perc[0];
                    $pfound="yes";
                }
                $c = $c -1;
            }
        } else {
            echo "done";
        }
        exit;
    }

    
    
//ajax queries are all done, time for the header    
    include('header.php');



//usermanagement
    if ((isset($_POST['usermgmt']))||($mode=="usermgmt")){
        $mode="usermgmt";
        if (($_SESSION['username']=="inituser")||($_SESSION['isadmin']=="1")){
            $sql="SELECT * FROM users";
            $res = $db_handle->query($sql);
            echo "</br>"; 
            if ($_SESSION['username']!="inituser"){
                echo "<h2>Existing users</h2>";
            }
            while ($row = $res->fetchArray(SQLITE3_ASSOC)){
                echo "<div class=row><div class=col style=text-align:right><form id=uform$row[id] action=? method=post><input class=form-control name=changeusername value=$row[username]></div>";
                if ($row['admin']=="1"){
                    $checked="checked";
                } else {
                    $checked="";
                }
                echo "<div class=col-ms><input data-onstyle=\"danger\" data-offstyle=success name=isadmin id=\"isadmin$row[id]\" type=\"checkbox\" data-toggle=\"toggle\" data-on=\"user is Admin\" data-off=\"user is no Admin\" $checked></div>";
                echo "<input type=hidden name=userchange value=$row[id]>";
                echo "<div class=col><input class=form-control type=password name=passwordchange placeholder=newpassword></div><div class=col><a href=# class=\"btn btn-success\" onclick=\"javascript:submitbutton('uform$row[id]');\">save user</a></form> ";
                echo "<button class=\"btn btn-danger\" data-delete-text=\"Delete user $row[username]!\" data-delete-what=user data-delete-id=\"$row[id]\" data-delete-name=\"$row[username]\" data-toggle=\"modal\" data-target=\"#confirm-delete\">Delete user</button></div></div>";
            }
//newuserform
            echo "<h2>Create a new user</h2><form id=newuserform action=? method=post><div class=row><div class=col><input type=text class=form-control name=newusername placeholder=Username></div>";
            if ($_SESSION['username']!="inituser"){
                echo "<div class=col-ms><input data-onstyle=\"danger\" data-offstyle=success name=isadmin id=\"isadmin\" type=\"checkbox\" data-toggle=\"toggle\" data-on=\"user is Admin\" data-off=\"user is no Admin\" checked></div>";
            } else {
                echo "<input type=hidden name=isadmin value=on>";
            }
            echo "<div class=col><input class=form-control type=password name=newpassword placeholder=newpassword></div><div class=col><a href=# class=\"btn btn-success\" onclick=\"javascript:submitbutton('newuserform');\">Create user</a></div></div></form>";
        }
    }


//servermanagement
    if (isset($_POST['servermgmt'])){
        $mode="servermgmt";
        if ($_SESSION['isadmin']=="1"){
            $sql="SELECT * FROM servers";
            $res = $db_handle->query($sql);
            echo "</br>";
                echo "<h2>Existing servers</h2>";
                echo "<div class=row><div class=col>hostname</div><div class=col>connectstring</div><div class=col>VM directory</div><div class=col>ISO directory</div><div class=col></div></div>";
            while ($row = $res->fetchArray(SQLITE3_ASSOC)){
                echo "<div class=row><div class=col style=text-align:right><form id=sform$row[id] action=? method=post><input class=form-control name=changehostname value=$row[hostname]></div>";
                echo "<div class=col><input name=connectstring id=\"connectstring\" type=\"text\" value=$row[connectstring]></div>";
                echo "<div class=col><input name=vmdirectory id=\"connectstring\" type=\"text\" value=$row[vmdirectory]></div>";
                echo "<div class=col><input name=isodirectory id=\"connectstring\" type=\"text\" value=$row[isodirectory]></div>";
                echo "<div class=col><input type=hidden name=changeid value=$row[id]><a href=# class=\"btn btn-success\" onclick=\"javascript:submitbutton('sform$row[id]');\">save server</a></form> ";
                echo "<button class=\"btn btn-danger\" data-delete-text=\"Delete server $row[hostname]!\" data-delete-what=server data-delete-id=\"$row[id]\" data-delete-name=\"$row[hostname]\" data-toggle=\"modal\" data-target=\"#confirm-delete\">Delete server</button></div></div>";
            }
//newserverform
            echo "<h2>Create a new server</h2><form id=newserverform action=? method=post><div class=row><div class=col><input type=text class=form-control name=newhostname placeholder=hostname></div>";
            echo "<div class=col><input class=form-control name=connectstring type=\"text\" placeholder=\"nlvmi@192.168.0.X\"></div>";
            echo "<div class=col><input class=form-control type=test name=vmdirectory placeholder=\"multiple directories like /directorya;/directoryb\"></div>";
            echo "<div class=col><input class=form-control type=test name=isodirectory placeholder=\"multiple directories like /directorya;/directoryb\"></div>";
            echo "<div class=col><a href=# class=\"btn btn-success\" onclick=\"javascript:submitbutton('newserverform');\">Create server</a></div></div></form>";
        }
    }


//start vm
    if (isset($_REQUEST['start'])){
        $vmname = clean($_REQUEST['start']);
        $sqllimit="";
        if($_SESSION['isadmin']!="1"){
            $sqllimit="WHERE username='$_SESSION[username]'";
        }
        $sql="SELECT * FROM vms WHERE vmname='$vmname' $sqllimit";
        $res = $db_handle->query($sql);
        while ($row = $res->fetchArray(SQLITE3_ASSOC)){
            $shellout = shell_exec("/usr/bin/nlvmi start $vmname bla");
            echo $shellout;
        }
    }
//stop vm
    if (isset($_REQUEST['stop'])){
        $vmname = clean($_REQUEST['stop']);
        if($_SESSION['isadmin']!="1"){
            $sqllimit="WHERE username='$_SESSION[username]'";
        }
        $sql="SELECT * FROM vms WHERE vmname='$vmname' $sqllimit";
        $res = $db_handle->query($sql);
        while ($row = $res->fetchArray(SQLITE3_ASSOC)){
            if(!checkvm($vmname)){
                $shellout = shell_exec("/usr/bin/nlvmi stop $vmname bla");
                echo $shellout;
            }
        }
    }

//form for edit and new vms
    if (isset($_REQUEST['edit'])){
        $mode="editvm";
        $formname="editvm";
        $eid=clean($_REQUEST['edit']);
        $sql="SELECT * FROM vms WHERE id='$eid'";
        $res = $db_handle->query($sql);
        $editid = "<input type=hidden name=editid value=$eid>";
        while ($row = $res->fetchArray(SQLITE3_ASSOC)){
            $e = $row;
        }
    } elseif(isset($_REQUEST['newvm'])) {
        $formname="newvm";
        $editid="";
        $mode="newvm";
    }

    if (isset($formname)){
        $placehold['vmname']="Name of the VM";
        $placehold['server']="ip or name of host server";
        $placehold['cputype']="normally just 'host'";
        $placehold['cpus']="Number of core for the VM";
        $placehold['memory']="Amount of RAM for the VM im Mb";
        $placehold['usbdev']="Normally just 'tablet' to get a mouse";
        $placehold['kblang']="Qemu keyboard layout. Like 'de-ch'";
        $placehold['custom']="Customstring to add to the qemu command";
        $placehold['tapdev1']="tapname of first netinterface";
        $placehold['tapdev2']="tapname of second netinterface";
        $placehold['tapdev3']="tapname of third netinterface";
        $placehold['macaddr1']="macaddress of first netinterface";
        $placehold['macaddr2']="macaddress of second netinterface";
        $placehold['macaddr3']="macaddress of third netinterface";
        $placehold['brdev1']="bridge on host to add first netinterface";
        $placehold['brdev2']="bridge on host to add second netinterface";
        $placehold['brdev3']="bridge on host to add third netinterface";
        $placehold['vncport']="VNC displaynumber like '1'";
        $placehold['websocket']="port to bind the VNC websocket";
        $placehold['vncpasswort']="the password for VNC";

        echo "<h2>$formname</h2></br>";
        echo "<form id=$formname name=$formname action=? method=post>";
        $res = $db_handle->query('PRAGMA table_info(vms)');
        while ($col = $res->fetchArray(SQLITE3_ASSOC)) {
            $arrColnames[]=$col['name'];
        }
        $server = $e['server'];
        for ($col=0; $col <count($arrColnames); $col++){
            if (($arrColnames[$col]!="id")&&($arrColnames[$col]!="prio")){
                if (isset($e[$arrColnames[$col]])){
                    $val = $e[$arrColnames[$col]];
                } else {
                    $val = "";
                }
                $colname=$arrColnames[$col];
                if ($arrColnames[$col] == "bootoption"){
                    if($val=="") {
                        $val="c";
                    }
                    echo "<div class=row><div class=col-md-1 style=text-align:right>bootoption</div><div class=col-md-2><div class=dropdown><button class=\"btn btn-secondary dropdown-toggle\" type=button id=bootoptionbutton data-toggle=dropdown aria-haspopup=true aria-expanded=false>$val</button>";
                    echo "<div class=dropdown-menu aria-labelledby=bootoptionbutton>";
                    echo "<a class=dropdown-item href=\"javascript:dropdown('bootoptionbutton','c')\">c</a>";
                    echo "<a class=dropdown-item href=\"javascript:dropdown('bootoptionbutton','d')\">d</a>";
                    echo "</div></div></div></div><input type=hidden id=bootoptionbuttonh name=bootoption value=$val>";
                } elseif ($arrColnames[$col] == "user"){
                    if ($val=="") {
                        $val=$_SESSION['username'];
                    }
                    echo "<div class=row><div class=col-md-1 style=text-align:right>user</div><div class=col-md-2><div class=dropdown><button class=\"btn btn-secondary dropdown-toggle\" type=button id=userbutton data-toggle=dropdown aria-haspopup=true aria-expanded=false>$val</button>";
                    echo "<div class=dropdown-menu aria-labelledby=userbutton>";
                    $sqlusers="SELECT username FROM users";
                    $resusers=$db_handle->query($sqlusers);
                    while ($rowusers = $resusers->fetchArray(SQLITE3_ASSOC)){
                       echo "<a class=dropdown-item href=\"javascript:dropdown('userbutton','$rowusers[username]')\">$rowusers[username]</a>";
                    }   
                    echo "</div></div></div><input type=hidden id=userbuttonh name=user value=$val></div>";
                } elseif ($arrColnames[$col] == "arch"){
                    echo "<div class=row><div class=col-md-1 style=text-align:right>arch</div><div class=col-md-2><div class=dropdown><button class=\"btn btn-secondary dropdown-toggle\" type=button id=archbutton data-toggle=dropdown aria-haspopup=true aria-expanded=false>x86_64</button>";
                    echo "<div class=dropdown-menu aria-labelledby=archbutton>";
                    echo "<a class=dropdown-item href=\"javascript:dropdown('archbutton','x86_64')\">x86_64</a>";
                    echo "</div></div></div></div><input type=hidden id=archbuttonh name=arch value=x86_64>";
                } elseif (preg_match('/format/', $arrColnames[$col])){
                    formatbuttons($arrColnames[$col], $val);
                } elseif ($arrColnames[$col] == "autostart"){
                    $checked="";
                    if ($val=="1"){
                        $checked="checked";
                    }
                    echo "<div class=row><div class=col-md-1 style=text-align:right>autostart</div><div class=col-md-2><input data-onstyle=\"success\" data-offstyle=danger name=autostart id=\"autostart\" type=\"checkbox\" data-toggle=\"toggle\" data-on=\"boot with host\" data-off=\"no autostart\" $checked></div></div>";
                } elseif ($arrColnames[$col] == "cdrom"){
                    serverdepropdown($server, $val, "cdrom");
                    echo "</div>";
                } elseif (preg_match('/tapdev/', $arrColnames[$col])) {
                    echo "<div class=row><div class=col-md-1 style=text-align:right>$arrColnames[$col]</div><div class=col-md-2><input class=form-control type=text name=$arrColnames[$col] value=\"$val\" placeholder=\"$placehold[$colname]\"></div>";
                } elseif (preg_match('/macaddr/', $arrColnames[$col])) {
                    echo "<div class=col-md-1 style=text-align:right>$arrColnames[$col]</div><div class=col-md-2><input class=form-control type=text name=$arrColnames[$col] id=$arrColnames[$col] value=\"$val\" placeholder=\"$placehold[$colname]\"></div><div onclick=genmac('$arrColnames[$col]') class=\"btn btn-primary\">gen</div>";
                } elseif (preg_match('/brdev/', $arrColnames[$col])) {
                    echo "<div class=col-md-1 style=text-align:right>$arrColnames[$col]</div><div class=col-md-2><input class=form-control type=text name=$arrColnames[$col] value=\"$val\" placeholder=\"$placehold[$colname]\"></div></div>";
                } elseif (preg_match('/drive/', $arrColnames[$col])){
                    if ($arrColnames[$col]=="drive1"){
                        echo "<div id=drivesdiv>";
                    }
                    serverdepropdown($server, $val, $arrColnames[$col]);
                } elseif ($arrColnames[$col] == "server"){
                    echo "<div class=row><div class=col-md-1 style=text-align:right>$arrColnames[$col]</div><div class=col-md-2><div class=dropdown><button class=\"btn btn-secondary dropdown-toggle\" type=button id=$arrColnames[$col]button data-toggle=dropdown aria-haspopup=true aria-expanded=false>$val</button>";
                    echo "<div class=dropdown-menu aria-labelledby=$arrColnames[$col]button>";
                    $sqls="SELECT hostname FROM servers";
                    $ress = $db_handle->query($sqls);
                    while ($rows = $ress->fetchArray(SQLITE3_ASSOC)){
                        
                    echo "<a class=dropdown-item href=\"javascript:dropdown('$arrColnames[$col]button','$rows[hostname]')\">$rows[hostname]</a>";
                    }
                    echo "</div></div></div></div><input type=hidden id=$arrColnames[$col]buttonh name=$arrColnames[$col] value=$val>";
                } else {
                    
                    echo "<div class=row><div class=col-md-1 style=text-align:right>$arrColnames[$col]</div><div class=col-md-2><input class=form-control type=text name=$arrColnames[$col] value=\"$val\" placeholder=\"$placehold[$colname]\"></div></div>";
                }
            }
        }
        echo "$editid<input type=hidden name=mode value=$formname><a href=# onclick=\"submitbutton('$formname')\" class=\"btn btn-primary\">save vm</a></form>";
    }


    if(($mode!="newvm")&&($mode!="editvm")&&($mode!='usermgmt')){
        if ($_SESSION['isadmin']=="1"){
            $sqllimit="";
            echo "</br><a class=\"btn btn-primary\" href=# onclick=\"post('?', {newvm: 'newvm'});\">Create a new VM</a></br></br>";
        } else {
            $sqllimit="WHERE user='$_SESSION[username]'";
        }

//getting vms from DB
        $sql="SELECT * FROM vms $sqllimit ORDER BY prio";
        $res = $db_handle->query($sql);
        
        while ($row = $res->fetchArray(SQLITE3_ASSOC)){
            echo "<div class=row>";
            if (checkvm($row['vmname'])){
                $button = "start";
                $buttonc = "btn-success";
            } else {
                $button = "stop";
                $buttonc = "btn-warning";
            }
            $vncport = sprintf("%02d", $row['vncport']);
            echo "<div><button type=button onclick=\"arrow('up', '$row[id]');\" class=\"btn btn-default\" aria-label=\"Left Align\"><span><img src=arrowup.png width=6px ></span></button><br/>";
            echo "<button type=button onclick=\"arrow('down', '$row[id]');\" class=\"btn btn-default\" aria-label=\"Left Align\"><span><img src=arrowdown.png width=6px></span></button></div>";
            echo "<div class=col-sm><b>$row[vmname]</b></div><div class=col-sm>$row[server]</div><div class=col-sm>$row[cpus] CPUs, $row[memory] MB RAM</div><div class=col-sm>$row[drive1]</div>";
            echo "<div class=col-sm>VNC port: 59$vncport</div><div class-col-sm><a class=\"btn btn-primary\" href=# onclick=\"post('?', {edit: '$row[id]'});\">edit</a> ";
            echo "<a href=# onclick=\"post('?', {'$button': '$row[vmname]'});\"class=\"btn $buttonc\">$button</a> ";
            echo "<button class=\"btn btn-danger\" data-delete-text=\"Delete VM $row[vmname]!\" data-delete-id=\"$row[id]\" data-delete-name=\"$row[vmname]\" data-toggle=\"modal\" data-target=\"#confirm-delete\" data-delete-what=vm>Delete VM</button> ";
            if ($row['websocket']!=""){
                $server = $row['server'];
                $websocketport = $row['websocket'] + 5700;
                $wpath="";
                if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])){
                    if($_SERVER['HTTP_X_FORWARDED_PROTO']=="https"){
                        $wpath="$row[vmname]/";
                        $websocketport="443";
                    }
                } elseif (isset($_SERVER['REQUEST_SCHEME'])){
                    if ($_SERVER['REQUEST_SCHEME']=="https"){
                        $wpath="$row[vmname]/";
                        $websocketport="443";
                    }
                }
                if (preg_match('/stop/', $button)) {
                    echo "<a target=_blank href=novnc/vnc.html?host=$server&port=$websocketport&path=$wpath class=\"btn btn-success\">VNC</a>";
                }
            }
            echo "</div></div><hr>";
        }
    }
    echo "</div></body></html>";
} elseif (!isset($_SESSION['username'])){
    echo "<h1>Welcome to nlvmi!</h1><h2>You need to log in</h2></br>";
    echo "<form action=? method=post>Username: <input type=text name=username> Password: <input type=password name=password> <input name=login type=submit></form>";
    exit;
}

?>
