function AJacceptBlockAllocationSubmit()
{
    global $mysql_link_vcl, $user;
    $blockid = getContinuationVar('blockid');
    $comments = getContinuationVar('comments');
    $validemail = getContinuationVar('validemail');
    $emailuser = getContinuationVar('emailuser');
    $imageid = getContinuationVar('imageid');
    $setusergroup = getContinuationVar('setusergroup');
    if ($setusergroup) {
        $usergroupid = processInputVar('groupid', ARG_NUMERIC);
    }
    $name = processInputVar('brname', ARG_STRING);
    $emailtext = processInputVar('emailtext', ARG_STRING);
    $override = getContinuationVar('override', 0);
    $err = 0;
    if (!preg_match('/^([-a-zA-Z0-9\\. ]){3,80}$/', $name)) {
        $errmsg = i("The name can only contain letters, numbers, spaces, dashes(-), and periods(.) and can be from 3 to 80 characters long");
        $err = 1;
    }
    if ($validemail) {
        if (get_magic_quotes_gpc()) {
            $emailtext = stripslashes($emailtext);
        }
        if (!$err && preg_match('/[<>|]/', $emailtext)) {
            $errmsg = i("<>\\'s and pipes (|) are not allowed in the email text.");
            $err = 1;
        }
        if (!$err && !preg_match('/[A-Za-z]{2,}/', $emailtext)) {
            $errmsg = i("Something must be filled in for the email text.");
            $err = 1;
        }
    }
    $groups = getUserGroups(0, $user['affiliationid']);
    if (!$err && $setusergroup && !array_key_exists($usergroupid, $groups)) {
        $errmsg = i("Invalid user group submitted.");
        $err = 1;
    }
    $managementnodes = getManagementNodes('future');
    if (!$err && empty($managementnodes)) {
        $errmsg = i("Error encountered while trying to create block allocation:") . "\\n\\n";
        $errmsg .= i("No active management nodes were found. Please try accepting the block allocation at a later time.");
        $err = 1;
    }
    $dooverride = 0;
    if (!$err && !$override && $setusergroup) {
        $groupresources = getUserResources(array("imageAdmin", "imageCheckOut"), array("available"), 0, 0, 0, $usergroupid);
        if (!array_key_exists($imageid, $groupresources['image'])) {
            $errmsg = i("Warning: The selected user group does not currently have access to the requested image. You can accept the Block Allocation again to ignore this warning.");
            $err = 1;
            $dooverride = 1;
        }
    }
    $mnid = array_rand($managementnodes);
    if (!$err) {
        # update values for block allocation
        if ($validemail) {
            $esccomments = mysql_real_escape_string("COMMENTS: {$comments}|EMAIL: {$emailtext}");
        } else {
            $esccomments = mysql_real_escape_string("COMMENTS: {$comments}|USER NOT EMAILED");
        }
        $query = "UPDATE blockRequest " . "SET name = '{$name}', ";
        if ($setusergroup) {
            $query .= "groupid = {$usergroupid}, ";
        }
        $query .= "status = 'accepted', " . "comments = '{$esccomments}', " . "managementnodeid = '{$mnid}' " . "WHERE id = {$blockid}";
        doQuery($query, 101);
        if (!mysql_affected_rows($mysql_link_vcl)) {
            $errmsg = i("Error encountered while updating status of block allocation.");
            $err = 1;
        } else {
            $repeating = getContinuationVar('repeating');
            if ($repeating == 'weekly') {
                $startts = getContinuationVar('startts');
                $endts = getContinuationVar('endts');
                $daymask = getContinuationVar('daymask');
                $times = getContinuationVar('times');
                createWeeklyBlockTimes($blockid, $startts, $endts, $daymask, $times);
            } elseif ($repeating == 'monthly') {
                $startts = getContinuationVar('startts');
                $endts = getContinuationVar('endts');
                $day = getContinuationVar('day');
                $weeknum = getContinuationVar('weeknum');
                $times = getContinuationVar('times');
                createMonthlyBlockTimes($blockid, $startts, $endts, $day, $weeknum, $times);
            } elseif ($repeating == 'list') {
                $slots = getContinuationVar('slots');
                createListBlockData($blockid, $slots, 'accept');
            }
        }
    }
    if ($err) {
        print "alert('{$errmsg}');";
        $cdata = getContinuationVar();
        $cont = addContinuationsEntry('AJacceptBlockAllocationSubmit', $cdata, SECINDAY, 1, 0);
        print "dojo.byId('submitacceptcont').value = '{$cont}';";
        if ($dooverride) {
            $cdata['override'] = 1;
            $cont = addContinuationsEntry('AJacceptBlockAllocationSubmit', $cdata, SECINDAY, 1, 0);
            print "dojo.byId('submitacceptcont2').value = '{$cont}';";
        } else {
            print "dojo.byId('submitacceptcont2').value = '';";
        }
        print "document.body.style.cursor = 'default';";
        return;
    }
    # send accept email to requestor
    $message = $emailtext . "\n\nVCL Admins";
    $mailParams = "-f" . ENVELOPESENDER;
    mail($emailuser, i("VCL Block Allocation Accepted"), $message, '', $mailParams);
    print "clearHideConfirmAccept();";
    $html = getPendingBlockHTML(1);
    $html = str_replace("\n", '', $html);
    $html = str_replace("'", "\\'", $html);
    $html = preg_replace("/>\\s*</", "><", $html);
    print setAttribute('pendinglist', 'innerHTML', $html);
    print "AJdojoCreate('pendinglist');";
    $html = getCurrentBlockHTML(1);
    $html = str_replace("\n", '', $html);
    $html = str_replace("'", "\\'", $html);
    $html = preg_replace("/>\\s*</", "><", $html);
    print setAttribute('blocklist', 'innerHTML', $html);
    print "AJdojoCreate('blocklist');";
}
Beispiel #2
0
function processMgmtnodeInput($checks = 1)
{
    global $submitErr, $submitErrMsg, $user, $mode;
    $return = array();
    $mgmtnodes = getManagementNodes();
    $return["mgmtnodeid"] = getContinuationVar("mgmtnodeid");
    $return["hostname"] = getContinuationVar("hostname", processInputVar("hostname", ARG_STRING));
    $return["IPaddress"] = getContinuationVar("IPaddress", processInputVar("IPaddress", ARG_STRING));
    $return["owner"] = getContinuationVar("owner", processInputVar("owner", ARG_STRING, $user["unityid"]));
    $return["stateid"] = getContinuationVar("stateid", processInputVar("stateid", ARG_STRING));
    $return["premoduleid"] = getContinuationVar("premoduleid", processInputVar("premoduleid", ARG_NUMERIC));
    $return["checkininterval"] = getContinuationVar("checkininterval", processInputVar("checkininterval", ARG_NUMERIC));
    $return["installpath"] = getContinuationVar("installpath", processInputVar("installpath", ARG_STRING));
    $return["keys"] = getContinuationVar("keys", processInputVar("keys", ARG_STRING));
    $return["sshport"] = getContinuationVar("sshport", processInputVar("sshport", ARG_NUMERIC));
    $return["imagelibenable"] = getContinuationVar("imagelibenable", processInputVar("imagelibenable", ARG_NUMERIC));
    $return["imagelibgroupid"] = getContinuationVar("imagelibgroupid", processInputVar("imagelibgroupid", ARG_NUMERIC));
    $return["imagelibuser"] = getContinuationVar("imagelibuser", processInputVar("imagelibuser", ARG_STRING));
    $return["imagelibkey"] = getContinuationVar("imagelibkey", processInputVar("imagelibkey", ARG_STRING));
    if ($return['checkininterval'] < 5) {
        $return['checkininterval'] = 5;
    }
    if ($return['checkininterval'] > 30) {
        $return['checkininterval'] = 30;
    }
    if ($return['sshport'] < 1 || $return['sshport'] > 65535) {
        $return['sshport'] = 22;
    }
    if ($return['imagelibenable'] != '' && $return['imagelibenable'] != 1) {
        $return['imagelibenable'] = '';
    }
    if ($return['imagelibenable'] != 1) {
        $return["imagelibgroupid"] = 'NULL';
        $return["imagelibuser"] = '******';
        $return["imagelibkey"] = 'NULL';
    }
    if (!$checks) {
        return $return;
    }
    if (!ereg('^[a-zA-Z0-9_][-a-zA-Z0-9_\\.]{1,49}$', $return["hostname"])) {
        $submitErr |= MNHOSTNAMEERR;
        $submitErrMsg[MNHOSTNAMEERR] = "Hostname can only contain letters, numbers, dashes(-), periods(.), and underscores(_). It can be from 1 to 50 characters long";
    }
    if (!($submitErr & MNHOSTNAMEERR) && $mode != "confirmEditMgmtnode" && checkForMgmtnodeHostname($return["hostname"])) {
        $submitErr |= MNHOSTNAMEERR;
        $submitErrMsg[MNHOSTNAMEERR] = "A node already exists with this hostname.";
    }
    $ipaddrArr = explode('.', $return["IPaddress"]);
    if (!ereg('^(([0-9]){1,3}\\.){3}([0-9]){1,3}$', $return["IPaddress"]) || $ipaddrArr[0] < 1 || $ipaddrArr[0] > 255 || $ipaddrArr[1] < 0 || $ipaddrArr[1] > 255 || $ipaddrArr[2] < 0 || $ipaddrArr[2] > 255 || $ipaddrArr[3] < 1 || $ipaddrArr[3] > 255) {
        $submitErr |= IPADDRESSERR;
        $submitErrMsg[IPADDRESSERR] = "Invalid IP address. Must be w.x.y.z with each of " . "w, x, y, and z being between 1 and 255 (inclusive)";
    }
    if ($mode != "confirmEditMgmtnode" && !($submitErr & IPADDRESSERR) && checkForMgmtnodeIPaddress($return["IPaddress"])) {
        $submitErr |= IPADDRESSERR;
        $submitErrMsg[IPADDRESSERR] = "A node already exists with this IP address.";
    }
    if (!validateUserid($return["owner"])) {
        $submitErr |= MNOWNERERR;
        $submitErrMsg[MNOWNERERR] = "Submitted ID is not valid";
    }
    if (!preg_match('/^([-a-zA-Z0-9_\\.\\/]){2,100}$/', $return["installpath"])) {
        $submitErr |= MNINSTPATHERR;
        $submitErrMsg[MNINSTPATHERR] = "This can only contain letters, numbers, dashes(-), periods(.), underscores(_), and forward slashes(/). It can be from 2 to 100 characters long";
    }
    if (!empty($return['keys']) && !preg_match('/^([-a-zA-Z0-9_\\.\\/,]){2,1024}$/', $return["keys"])) {
        $submitErr |= MNSSHIDKEYSERR;
        $submitErrMsg[MNSSHIDKEYSERR] = "This can only contain letters, numbers, dashes(-), periods(.), underscores(_), forward slashes(/), and commas(,). It can be from 2 to 1024 characters long";
    }
    if ($return['imagelibenable'] == 1) {
        $validgroups = getUserResources(array('mgmtNodeAdmin'), array("manageGroup"), 1);
        if (!in_array($return['imagelibgroupid'], array_keys($validgroups['managementnode']))) {
            $submitErr |= MNIMGLIBGRPIDERR;
            $submitErrMsg[MNIMGLIBGRPIDERR] = "The selected group was invalid";
        }
        if (!preg_match('/^([-a-zA-Z0-9_\\.\\/,]){2,20}$/', $return["imagelibuser"])) {
            $submitErr |= MNIMGLIBUSERERR;
            $submitErrMsg[MNIMGLIBUSERERR] = "This can only contain letters, numbers, and dashes(-) and can be from 2 to 20 characters long";
        }
        if (!preg_match('/^([-a-zA-Z0-9_\\.\\/,]){2,100}$/', $return["imagelibkey"])) {
            $submitErr |= MNIMGLIBKEYERR;
            $submitErrMsg[MNIMGLIBKEYERR] = "This can only contain letters, numbers, dashes(-), periods(.), underscores(_), and forward slashes(/). It can be from 2 to 100 characters long";
        }
    } else {
        $return["imagelibgroupid"] = 'NULL';
        $return["imagelibuser"] = '******';
        $return["imagelibkey"] = 'NULL';
    }
    return $return;
}
Beispiel #3
0
 function getMapSubName($maptype, $subid)
 {
     switch ($maptype) {
         case "Image":
             $data = getImages(0, $subid);
             return $data[$subid]['prettyname'];
         case "OS Type":
             $ostypes = getOStypes();
             return $ostypes[$subid];
         case "OS":
             $oses = getOSList();
             return $oses[$subid]['prettyname'];
         case "Config":
         case "Cluster":
             $data = $this->_getData($subid);
             return $data[$subid]['name'];
         case "Management Node":
             $managementnodes = getManagementNodes('neither', 0, $subid);
             return $managementnodes[$subid]['hostname'];
             break;
     }
 }
Beispiel #4
0
function viewRequests()
{
    global $user, $inContinuation, $mode, $skin;
    if ($inContinuation) {
        $lengthchanged = getContinuationVar('lengthchanged', 0);
    } else {
        $lengthchanged = processInputVar('lengthchanged', ARG_NUMERIC, 0);
    }
    $incPaneDetails = processInputVar('incdetails', ARG_NUMERIC, 0);
    $refreqid = processInputVar('reqid', ARG_NUMERIC, 0);
    $requests = getUserRequests("all");
    $images = getImages();
    $computers = getComputers();
    $resources = getUserResources(array("imageAdmin"));
    $text = '';
    $newbtnh = '';
    if (in_array("imageCheckOut", $user["privileges"]) || in_array("imageAdmin", $user["privileges"])) {
        $newbtnh .= "<button id=\"newrequestbtn\" dojoType=\"dijit.form.Button\">\n";
        $newbtnh .= "  " . i("New Reservation") . "\n";
        $newbtnh .= "  <script type=\"dojo/method\" event=\"onClick\">\n";
        $newbtnh .= "    showNewResDlg();\n";
        $newbtnh .= "  </script>\n";
        $newbtnh .= "</button><br><br>\n";
    }
    if ($mode != 'AJviewRequests') {
        print "<H2>" . i("Current Reservations") . "</H2>\n";
        if (count($requests) == 0) {
            print "<span id=\"noresspan\">\n";
        } else {
            print "<span id=\"noresspan\" class=\"hidden\">\n";
        }
        if ($newbtnh == '') {
            print i("You have no current reservations and do not have access to create new ones.") . "<br><br>\n";
        } else {
            print i("You have no current reservations.") . "<br><br>\n";
        }
        print "</span>\n";
        print $newbtnh;
    }
    if ($newbtnh == '' && count($requests) == 0) {
        return;
    }
    if ($mode != 'AJviewRequests') {
        print "<div id=subcontent>\n";
    }
    $refresh = 0;
    $connect = 0;
    $failed = 0;
    $normal = '';
    $imaging = '';
    $long = '';
    $server = '';
    $pendingcnt = 0;
    $reqids = array();
    if (checkUserHasPerm('View Debug Information')) {
        $nodes = getManagementNodes();
    }
    if ($count = count($requests)) {
        $now = time();
        for ($i = 0, $failed = 0, $timedout = 0, $text = '', $showcreateimage = 0, $cluster = 0; $i < $count; $i++, $failed = 0, $timedout = 0, $text = '', $cluster = 0) {
            if ($requests[$i]['forcheckout'] == 0 && $requests[$i]['forimaging'] == 0) {
                continue;
            }
            if (count($requests[$i]['reservations'])) {
                $cluster = 1;
            }
            $cdata = array('requestid' => $requests[$i]['id']);
            $reqids[] = $requests[$i]['id'];
            $imageid = $requests[$i]["imageid"];
            $text .= "  <TR valign=top id=reqrow{$requests[$i]['id']}>\n";
            if (requestIsReady($requests[$i]) && $requests[$i]['useraccountready']) {
                $connect = 1;
                # request is ready, print Connect! and End buttons
                $cont = addContinuationsEntry('AJconnectRequest', $cdata, SECINDAY);
                $text .= getViewRequestHTMLitem('connectbtn', $cont);
                if ($requests[$i]['serveradmin']) {
                    $cdata2 = $cdata;
                    $cdata2['notbyowner'] = 0;
                    if ($user['id'] != $requests[$i]['userid']) {
                        $cdata2['notbyowner'] = 1;
                    }
                    $cont = addContinuationsEntry('AJconfirmDeleteRequest', $cdata2, SECINDAY);
                    $text .= getViewRequestHTMLitem('deletebtn', $cont);
                } else {
                    $text .= "    <TD></TD>\n";
                }
            } elseif ($requests[$i]["currstateid"] == 5) {
                # request has failed
                $text .= getViewRequestHTMLitem('failedblock', $requests[$i]['id']);
                if ($requests[$i]['serveradmin']) {
                    $cont = addContinuationsEntry('AJconfirmRemoveRequest', $cdata, SECINDAY);
                    $text .= getViewRequestHTMLitem('removebtn', $cont);
                } else {
                    $text .= "    <TD></TD>\n";
                }
                $failed = 1;
            } elseif (datetimeToUnix($requests[$i]["start"]) < $now) {
                # other cases where the reservation start time has been reached
                if ($requests[$i]["currstateid"] == 12 && $requests[$i]['laststateid'] == 11 || $requests[$i]["currstateid"] == 11 || $requests[$i]["currstateid"] == 14 && $requests[$i]["laststateid"] == 11) {
                    # request has timed out
                    $text .= getViewRequestHTMLitem('timeoutblock');
                    $timedout = 1;
                    if ($requests[$i]['serveradmin']) {
                        $cont = addContinuationsEntry('AJconfirmRemoveRequest', $cdata, SECINDAY);
                        $text .= getViewRequestHTMLitem('removebtn', $cont);
                    } else {
                        $text .= "    <TD></TD>\n";
                    }
                } else {
                    # computer is loading, print Pending... and Delete button
                    # TODO figure out a different way to estimate for reboot and reinstall states
                    # TODO if user account not ready, print accurate information in details
                    $pendingcnt++;
                    $remaining = 1;
                    if (isComputerLoading($requests[$i], $computers)) {
                        if (datetimeToUnix($requests[$i]["daterequested"]) >= datetimeToUnix($requests[$i]["start"])) {
                            $startload = datetimeToUnix($requests[$i]["daterequested"]);
                        } else {
                            $startload = datetimeToUnix($requests[$i]["start"]);
                        }
                        $imgLoadTime = getImageLoadEstimate($imageid);
                        if ($imgLoadTime == 0) {
                            $imgLoadTime = $images[$imageid]['reloadtime'] * 60;
                        }
                        $tmp = ($imgLoadTime - ($now - $startload)) / 60;
                        $remaining = sprintf("%d", $tmp) + 1;
                        if ($remaining < 1) {
                            $remaining = 1;
                        }
                    }
                    $data = array('text' => '');
                    if ($requests[$i]['currstateid'] != 26 && $requests[$i]['currstateid'] != 27 && $requests[$i]['currstateid'] != 28 && $requests[$i]['currstateid'] != 24 && ($requests[$i]["currstateid"] != 14 || $requests[$i]['laststateid'] != 26 && $requests[$i]['laststateid'] != 27 && $requests[$i]['laststateid'] != 28 && $requests[$i]['laststateid'] != 24)) {
                        $data['text'] = i("<br>Est:&nbsp;") . $remaining . i("&nbsp;min remaining\n");
                    }
                    $text .= getViewRequestHTMLitem('pendingblock', $requests[$i]['id'], $data);
                    $refresh = 1;
                    if ($requests[$i]['serveradmin'] && $requests[$i]['laststateid'] != 24) {
                        $cdata2 = $cdata;
                        $cdata2['notbyowner'] = 0;
                        if ($user['id'] != $requests[$i]['userid']) {
                            $cdata2['notbyowner'] = 1;
                        }
                        $cont = addContinuationsEntry('AJconfirmDeleteRequest', $cdata2, SECINDAY);
                        $text .= getViewRequestHTMLitem('deletebtn', $cont);
                    } else {
                        $text .= "    <TD></TD>\n";
                    }
                }
            } else {
                # reservation is in the future
                $text .= "    <TD></TD>\n";
                if ($requests[$i]['serveradmin']) {
                    $cdata2 = $cdata;
                    $cdata2['notbyowner'] = 0;
                    if ($user['id'] != $requests[$i]['userid']) {
                        $cdata2['notbyowner'] = 1;
                    }
                    $cont = addContinuationsEntry('AJconfirmDeleteRequest', $cdata2, SECINDAY);
                    $text .= getViewRequestHTMLitem('deletebtn', $cont);
                } else {
                    $text .= "    <TD></TD>\n";
                }
            }
            if (!$failed && !$timedout) {
                # print edit button
                $editcont = addContinuationsEntry('AJeditRequest', $cdata, SECINDAY);
                $imgcont = addContinuationsEntry('AJstartImage', $cdata, SECINDAY);
                if ($requests[$i]['serveradmin']) {
                    $text .= getViewRequestHTMLitem('openmoreoptions');
                    $text .= getViewRequestHTMLitem('editoption', $editcont);
                    if (array_key_exists($imageid, $resources['image']) && !$cluster && ($requests[$i]['currstateid'] == 8 || $requests[$i]['laststateid'] == 8)) {
                        # reservation has been in inuse state
                        $text .= getViewRequestHTMLitem('endcreateoption', $imgcont);
                    }
                    /*else
                    		$text .= getViewRequestHTMLitem('endcreateoptiondisable');*/
                    if (array_key_exists($imageid, $resources['image']) && !$cluster && $requests[$i]['server'] && ($requests[$i]['currstateid'] == 8 || $requests[$i]['currstateid'] == 14 && $requests[$i]['laststateid'] == 8)) {
                        $chkcdata = $cdata;
                        $chkcdata['checkpoint'] = 1;
                        $imgcont = addContinuationsEntry('AJstartImage', $chkcdata, SECINDAY);
                        $text .= getViewRequestHTMLitem('checkpointoption', $imgcont);
                    } elseif ($requests[$i]['server'] && $requests[$i]['currstateid'] == 24) {
                        $text .= getViewRequestHTMLitem('checkpointoptiondisable');
                    }
                    if ($requests[$i]['currstateid'] == 8 || !$cluster && $requests[$i]['OSinstalltype'] != 'none' && $requests[$i]['currstateid'] != 3 && $requests[$i]['laststateid'] != 3 && $requests[$i]['currstateid'] != 13 && $requests[$i]['laststateid'] != 13 && $requests[$i]['currstateid'] != 24 && $requests[$i]['laststateid'] != 24 && $requests[$i]['currstateid'] != 16 && $requests[$i]['laststateid'] != 16 && $requests[$i]['currstateid'] != 26 && $requests[$i]['laststateid'] != 26 && $requests[$i]['currstateid'] != 28 && $requests[$i]['laststateid'] != 28 && $requests[$i]['currstateid'] != 27 && $requests[$i]['laststateid'] != 27) {
                        $cont = addContinuationsEntry('AJrebootRequest', $cdata, SECINDAY);
                        $text .= getViewRequestHTMLitem('rebootoption', $cont);
                        $cont = addContinuationsEntry('AJshowReinstallRequest', $cdata, SECINDAY);
                        $text .= getViewRequestHTMLitem('reinstalloption', $cont);
                    } else {
                        $text .= getViewRequestHTMLitem('rebootoptiondisable');
                        $text .= getViewRequestHTMLitem('reinstalloptiondisable');
                    }
                    $text .= "       </div>\n";
                    $text .= "     </div>\n";
                    $text .= getViewRequestHTMLitem('timeoutdata', $requests[$i]['id'], $requests[$i]);
                    $text .= "    </TD>\n";
                } else {
                    $text .= "    <TD>";
                    $text .= getViewRequestHTMLitem('timeoutdata', $requests[$i]['id'], $requests[$i]);
                    $text .= "</TD>\n";
                }
            } else {
                $text .= "    <TD></TD>\n";
            }
            # print name of server request
            if ($requests[$i]['server']) {
                if ($requests[$i]['servername'] == '') {
                    $text .= getViewRequestHTMLitem('servername', $requests[$i]['prettyimage']);
                } else {
                    $text .= getViewRequestHTMLitem('servername', $requests[$i]['servername']);
                }
            }
            # print name of image, add (Testing) if it is the test version of an image
            if (!$requests[$i]['server']) {
                $data = array('addtest' => 0);
                if ($requests[$i]["test"]) {
                    $data['addtest'] = 1;
                }
                $text .= getViewRequestHTMLitem('imagename', $requests[$i]['prettyimage'], $data);
            }
            # print start time
            if (!$requests[$i]['server']) {
                $data = array('start' => $requests[$i]['start'], 'requested' => $requests[$i]['daterequested']);
                $text .= getViewRequestHTMLitem('starttime', '', $data);
            }
            # print end time
            $data = array('end' => $requests[$i]['end']);
            $text .= getViewRequestHTMLitem('endtime', '', $data);
            # print date requested
            if (!$requests[$i]['server']) {
                $text .= getViewRequestHTMLitem('requesttime', $requests[$i]['daterequested']);
            }
            # print server request details
            if ($requests[$i]['server']) {
                $data = array('owner' => getUserUnityID($requests[$i]['userid']), 'requesttime' => $requests[$i]['daterequested'], 'admingroup' => $requests[$i]['serveradmingroup'], 'logingroup' => $requests[$i]['serverlogingroup'], 'image' => $requests[$i]['prettyimage'], 'starttime' => $requests[$i]['start']);
                if ($requests[$i]['currstateid'] == 14) {
                    $data['stateid'] = $requests[$i]['laststateid'];
                } else {
                    $data['stateid'] = $requests[$i]['currstateid'];
                }
                $text .= getViewRequestHTMLitem('serverdetails', $requests[$i]['id'], $data);
            }
            if (checkUserHasPerm('View Debug Information')) {
                if (!is_null($requests[$i]['vmhostid'])) {
                    $query = "SELECT c.hostname " . "FROM computer c, " . "vmhost v " . "WHERE v.id = {$requests[$i]['vmhostid']} AND " . "v.computerid = c.id";
                    $qh = doQuery($query, 101);
                    $row = mysql_fetch_assoc($qh);
                    $vmhost = $row['hostname'];
                }
                $text .= "    <TD align=center><a id=\"req{$requests[$i]['id']}\" ";
                $text .= "tabindex=0>{$requests[$i]["id"]}</a>\n";
                $text .= "<div dojoType=\"vcldojo.HoverTooltip\" connectId=\"req{$requests[$i]['id']}\">";
                $text .= "<b>Mgmt node</b>: {$nodes[$requests[$i]["managementnodeid"]]['hostname']}<br>\n";
                $text .= "<b>Computer ID</b>: {$requests[$i]['computerid']}<br>\n";
                $text .= "<b>Comp hostname</b>: {$computers[$requests[$i]["computerid"]]["hostname"]}<br>\n";
                $text .= "<b>Comp IP</b>: {$requests[$i]["IPaddress"]}<br>\n";
                $text .= "<b>Comp State ID</b>: {$computers[$requests[$i]["computerid"]]["stateid"]}<br>\n";
                $text .= "<b>Comp Type</b>: {$requests[$i]['comptype']}<br>\n";
                if (!is_null($requests[$i]['vmhostid'])) {
                    $text .= "<b>VM Host</b>: {$vmhost}<br>\n";
                }
                $text .= "<b>Current State ID</b>: {$requests[$i]["currstateid"]}<br>\n";
                $text .= "<b>Last State ID</b>: {$requests[$i]["laststateid"]}<br>\n";
                $text .= "</div></TD>\n";
            }
            $text .= "  </TR>\n";
            if ($requests[$i]['server']) {
                $server .= $text;
            } elseif ($requests[$i]['forimaging']) {
                $imaging .= $text;
            } elseif ($requests[$i]['longterm']) {
                $long .= $text;
            } else {
                $normal .= $text;
            }
        }
    }
    if (!empty($normal)) {
        if (!empty($imaging) || !empty($long)) {
            $text .= i("You currently have the following <strong>normal</strong> reservations:") . "<br>\n";
        } else {
            $text .= i("You currently have the following normal reservations:") . "<br>\n";
        }
        if ($lengthchanged) {
            $text .= "<font color=red>";
            $text .= i("NOTE: The maximum allowed reservation length for one of these reservations was less than the length you submitted, and the length of that reservation has been adjusted accordingly.");
            $text .= "</font>\n";
        }
        $text .= "<table id=reslisttable summary=\"lists reservations you currently have\" cellpadding=5>\n";
        $text .= "  <TR>\n";
        $text .= "    <TD colspan=3></TD>\n";
        $text .= "    <TH>" . i("Environment") . "</TH>\n";
        $text .= "    <TH>" . i("Starting") . "</TH>\n";
        $text .= "    <TH>" . i("Ending") . "</TH>\n";
        $text .= "    <TH>" . i("Initially requested") . "</TH>\n";
        if (checkUserHasPerm('View Debug Information')) {
            $text .= "    <TH>" . i("Req ID") . "</TH>\n";
        }
        $text .= "  </TR>\n";
        $text .= $normal;
        $text .= "</table>\n";
    }
    if (!empty($imaging)) {
        if (!empty($normal)) {
            $text .= "<hr>\n";
        }
        $text .= i("You currently have the following <strong>imaging</strong> reservations:") . "<br>\n";
        $text .= "<table id=imgreslisttable summary=\"lists imaging reservations you currently have\" cellpadding=5>\n";
        $text .= "  <TR>\n";
        $text .= "    <TD colspan=3></TD>\n";
        $text .= "    <TH>" . i("Environment") . "</TH>\n";
        $text .= "    <TH>" . i("Starting") . "</TH>\n";
        $text .= "    <TH>" . i("Ending") . "</TH>\n";
        $text .= "    <TH>" . i("Initially requested") . "</TH>\n";
        $computers = getComputers();
        if (checkUserHasPerm('View Debug Information')) {
            $text .= "    <TH>Req ID</TH>\n";
        }
        $text .= "  </TR>\n";
        $text .= $imaging;
        $text .= "</table>\n";
    }
    if (!empty($long)) {
        if (!empty($normal) || !empty($imaging)) {
            $text .= "<hr>\n";
        }
        $text .= i("You currently have the following <strong>long term</strong> reservations:") . "<br>\n";
        $text .= "<table id=\"longreslisttable\" summary=\"lists long term reservations you currently have\" cellpadding=5>\n";
        $text .= "  <TR>\n";
        $text .= "    <TD colspan=3></TD>\n";
        $text .= "    <TH>" . i("Environment") . "</TH>\n";
        $text .= "    <TH>" . i("Starting") . "</TH>\n";
        $text .= "    <TH>" . i("Ending") . "</TH>\n";
        $text .= "    <TH>" . i("Initially requested") . "</TH>\n";
        $computers = getComputers();
        if (checkUserHasPerm('View Debug Information')) {
            $text .= "    <TH>Req ID</TH>\n";
        }
        $text .= "  </TR>\n";
        $text .= $long;
        $text .= "</table>\n";
    }
    if (!empty($server)) {
        if (!empty($normal) || !empty($imaging) || !empty($long)) {
            $text .= "<hr>\n";
        }
        $text .= i("You currently have the following <strong>server</strong> reservations:") . "<br>\n";
        $text .= "<table id=\"longreslisttable\" summary=\"lists server reservations you currently have\" cellpadding=5>\n";
        $text .= "  <TR>\n";
        $text .= "    <TD colspan=3></TD>\n";
        $text .= "    <TH>" . i("Name") . "</TH>\n";
        $text .= "    <TH>" . i("Ending") . "</TH>\n";
        $computers = getComputers();
        $text .= "    <TH>" . i("Details") . "</TH>\n";
        if (checkUserHasPerm('View Debug Information')) {
            $text .= "    <TH>" . i("Req ID") . "</TH>\n";
        }
        $text .= "  </TR>\n";
        $text .= $server;
        $text .= "</table>\n";
    }
    # connect div
    if ($connect) {
        $text .= "<br><br>";
        $text .= i("Click the <b>Connect!</b> button to get further information about connecting to the reserved system. You must click the button from a web browser running on the same computer from which you will be connecting to the remote computer; otherwise, you may be denied access to the machine.") . "\n";
    }
    if ($refresh) {
        $text .= "<br><br>";
        $text .= i("This page will automatically update every 20 seconds until the <font color=red><i>Pending...</i></font> reservation is ready.") . "\n";
    }
    if ($failed) {
        $text .= "<br><br>";
        $text .= i("An error has occurred that has kept one of your reservations from being processed. We apologize for any inconvenience this may have caused.") . "\n";
    }
    $cont = addContinuationsEntry('AJviewRequests', array(), SECINDAY);
    $text .= "<INPUT type=hidden id=resRefreshCont value=\"{$cont}\">\n";
    $cont = addContinuationsEntry('AJpreviewClickThrough', array());
    $text .= "<INPUT type=hidden id=previewclickthroughcont value=\"{$cont}\">\n";
    $text .= "</div>\n";
    if ($mode != 'AJviewRequests') {
        $text .= newReservationHTML();
        $text .= newReservationConfigHTML();
        /*$text .= "<div dojoType=dijit.Dialog\n";
        		$text .= "      id=\"imageRevisionDlg\"\n";
        		$text .= "      title=\"" . i("Select Image Revisions") . "\"\n";
        		$text .= "      duration=250\n";
        		$text .= "      draggable=true\n";
        		$text .= "      width=\"50%\"\n";
        		#$text .= "      height=\"80%\">\n";
        		#$text .= "      style=\"height: 80%; width: 50%;\">\n";
        		$text .= "      style=\"width: 50%;\">\n";
        		#$text .= "<div dojoType=\"dijit.layout.BorderContainer\" gutters=\"false\" style=\"width: 100%; height: 90%;\">\n";
        		#$text .= "<div dojoType=\"dijit.layout.ContentPane\" region=\"top\" style=\"height: 25px;\">\n";
        		$text .= i("There are multiple versions of this environment available.");
        		$text .= "<br>" . i("Please select the version you would like to check out:");
        		#$text .= "\n</div>\n"; # ContentPane
        		#$text .= " <div dojoType=\"dijit.layout.ContentPane\" region=\"center\">\n";
        		#$text .= "   <div id=\"imageRevisionContent\"></div>\n";
        		$text .= "   <div id=\"imageRevisionContent\" style=\"height: 85%; overflow: auto;\"></div>\n";
        		#$text .= "</div>\n"; # ContentPane
        		#$text .= " <div dojoType=\"dijit.layout.ContentPane\" region=\"bottom\" style=\"height: 25px;\">\n";
        		$text .= "   <div align=\"center\">\n";
        		$text .= "   <button id=\"imageRevBtn\" dojoType=\"dijit.form.Button\">\n";
        		$text .= "    " . i("Create Reservation") . "\n";
        		$text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        		$text .= "       submitNewReservation();\n";
        		$text .= "     </script>\n";
        		$text .= "   </button>\n";
        		$text .= "   <button dojoType=\"dijit.form.Button\">\n";
        		$text .= "     " . i("Cancel") . "\n";
        		$text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        		$text .= "       dijit.byId('imageRevisionDlg').hide();\n";
        		$text .= "     </script>\n";
        		$text .= "   </button>\n";
        		$text .= "   </div>\n"; # center
        		#$text .= "</div>\n"; # ContentPane
        		#$text .= "</div>\n"; # BorderContainer
        		$text .= "</div>\n"; # Dialog*/
        $text .= "<div dojoType=dojox.layout.FloatingPane\n";
        $text .= "      id=resStatusPane\n";
        $text .= "      resizable=true\n";
        $text .= "      closable=true\n";
        $text .= "      title=\"" . i("Detailed Reservation Status") . "\"\n";
        $text .= "      style=\"width: 350px; ";
        $text .= "height: 300px; ";
        $text .= "position: absolute; ";
        $text .= "left: 0px; ";
        $text .= "top: 0px; ";
        $text .= "visibility: hidden; ";
        $text .= "border: solid 1px #7EABCD;\"\n";
        $text .= ">\n";
        $text .= "<script type=\"dojo/method\" event=minimize>\n";
        $text .= "  this.hide();\n";
        $text .= "</script>\n";
        $text .= "<script type=\"dojo/method\" event=close>\n";
        $text .= "  this.hide();\n";
        $text .= "  return false;\n";
        $text .= "</script>\n";
        $text .= "<div id=resStatusText></div>\n";
        $text .= "<input type=hidden id=detailreqid value=0>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"endResDlg\"\n";
        $text .= "      title=\"" . i("Delete Reservation") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true\n";
        $text .= "      style=\"width: 315px;\">\n";
        $text .= "   <div id=\"endResDlgContent\"></div>\n";
        $text .= "   <input type=\"hidden\" id=\"endrescont\">\n";
        $text .= "   <input type=\"hidden\" id=\"endresid\">\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <button id=\"endResDlgBtn\" dojoType=\"dijit.form.Button\">\n";
        $text .= "    " . i("Delete Reservation") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       submitDeleteReservation();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Cancel") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('endResDlg').hide();\n";
        $text .= "       dojo.byId('endResDlgContent').innerHTML = '';\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"remResDlg\"\n";
        $text .= "      title=\"" . i("Remove Reservation") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true>\n";
        $text .= "   <div id=\"remResDlgContent\"></div>\n";
        $text .= "   <input type=\"hidden\" id=\"remrescont\">\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <button id=\"remResDlgBtn\" dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Remove Reservation") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       submitRemoveReservation();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Cancel") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('remResDlg').hide();\n";
        $text .= "       dojo.byId('remResDlgContent').innerHTML = '';\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"editResDlg\"\n";
        $text .= "      title=\"" . i("Modify Reservation") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true>\n";
        $text .= "    <script type=\"dojo/connect\" event=onHide>\n";
        $text .= "      hideEditResDlg();\n";
        $text .= "    </script>\n";
        $text .= "   <div id=\"editResDlgContent\"></div>\n";
        $text .= "   <input type=\"hidden\" id=\"editrescont\">\n";
        $text .= "   <input type=\"hidden\" id=\"editresid\">\n";
        $text .= "   <div id=\"editResDlgErrMsg\" class=\"rederrormsg\"></div>\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <button id=\"editResDlgBtn\" dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Modify Reservation") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       submitEditReservation();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   <button dojoType=\"dijit.form.Button\" id=\"editResCancelBtn\">\n";
        $text .= "     " . i("Cancel") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('editResDlg').hide();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"rebootdlg\"\n";
        $text .= "      title=\"" . i("Reboot Reservation") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true>\n";
        $text .= "    <script type=\"dojo/connect\" event=onHide>\n";
        $text .= "      hideRebootResDlg();\n";
        $text .= "    </script>\n";
        $text .= "   <div id=\"rebootResDlgContent\">";
        $h = i("You can select either a soft or a hard reboot. A soft reboot issues a reboot command to the operating system. A hard reboot is akin to toggling the power switch on a computer. After issuing the reboot, it may take several minutes before the machine is available again. It is also possible that it will not come back up at all. Are you sure you want to continue?");
        $text .= preg_replace("/(.{1,60}([ \n]|\$))/", '\\1<br>', $h);
        $text .= "<br><br></div>\n";
        $text .= "   <div id=\"rebootRadios\" style=\"margin-left: 90px;\">\n";
        $text .= "   <input type=\"radio\" name=\"reboottype\" id=\"softreboot\" checked>\n";
        $text .= "   <label for=\"softreboot\">" . i("Soft Reboot") . "</label><br>\n";
        $text .= "   <input type=\"radio\" name=\"reboottype\" id=\"hardreboot\">\n";
        $text .= "   <label for=\"hardreboot\">" . i("Hard Reboot") . "</label><br><br>\n";
        $text .= "   </div>\n";
        $text .= "   <input type=\"hidden\" id=\"rebootrescont\">\n";
        $text .= "   <div id=\"rebootResDlgErrMsg\" class=\"rederrormsg\"></div>\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <button id=\"rebootResDlgBtn\" dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Reboot Reservation") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       submitRebootReservation();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Cancel") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('rebootdlg').hide();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"reinstalldlg\"\n";
        $text .= "      title=\"" . i("Reinstall Reservation") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true>\n";
        $text .= "    <script type=\"dojo/connect\" event=onHide>\n";
        $text .= "      hideReinstallResDlg();\n";
        $text .= "    </script>\n";
        $text .= "   <div id=\"reinstallloading\" style=\"text-align: center\">";
        $text .= "<img src=\"themes/{$skin}/css/dojo/images/loading.gif\" ";
        $text .= "style=\"vertical-align: middle;\"> " . i("Loading...") . "</div>\n";
        $text .= "   <div id=\"reinstallResDlgContent\"></div>\n";
        $text .= "   <input type=\"hidden\" id=\"reinstallrescont\">\n";
        $text .= "   <div id=\"reinstallResDlgErrMsg\" class=\"rederrormsg\"></div>\n";
        $text .= "   <div align=\"center\" id=\"reinstallbtns\" class=\"hidden\">\n";
        $text .= "   <button id=\"reinstallResDlgBtn\" dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Reinstall Reservation") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       submitReinstallReservation();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Cancel") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('reinstalldlg').hide();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"suggestedTimes\"\n";
        $text .= "      title=\"" . i("Available Times") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true>\n";
        $text .= "   <div id=\"suggestloading\" style=\"text-align: center\">";
        $text .= "<img src=\"themes/{$skin}/css/dojo/images/loading.gif\" ";
        $text .= "style=\"vertical-align: middle;\"> " . i("Loading...") . "</div>\n";
        $text .= "   <div id=\"suggestContent\"></div>\n";
        $text .= "   <input type=\"hidden\" id=\"suggestcont\">\n";
        $text .= "   <input type=\"hidden\" id=\"selectedslot\">\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <button id=\"suggestDlgBtn\" dojoType=\"dijit.form.Button\" disabled>\n";
        $text .= "     " . i("Use Selected Time") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       useSuggestedEditSlot();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   <button id=\"suggestDlgCancelBtn\" dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Cancel") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('suggestDlgBtn').set('disabled', true);\n";
        $text .= "       dojo.removeClass('suggestDlgBtn', 'hidden');\n";
        $text .= "       showDijitButton('suggestDlgBtn');\n";
        $text .= "       dijit.byId('suggestDlgCancelBtn').set('label', '" . i("Cancel") . "');\n";
        $text .= "       dijit.byId('suggestedTimes').hide();\n";
        $text .= "       dojo.byId('suggestContent').innerHTML = '';\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"startimagedlg\"\n";
        $text .= "      title=\"" . i("Create / Update Image") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true>\n";
        $text .= "    <script type=\"dojo/connect\" event=onHide>\n";
        $text .= "      hideStartImageDlg();\n";
        $text .= "    </script>\n";
        $text .= "<div id=\"imageendrescontent\">\n";
        $text .= "<H2>" . i("Create / Update an Image") . "</H2>\n";
        $text .= "</div>\n";
        # imageendrescontent
        $text .= "<div id=\"imagekeeprescontent\">\n";
        $text .= "<H2>" . i("Keep Reservation &amp; Create / Update an Image") . "</H2>\n";
        $h = i("This process will create a new image or new revision of the image while allowing you to keep your reservation. The node will be taken <strong>offline</strong> during the image capture process.");
        $h .= "\n \n";
        $h .= "<strong>" . i("NOTE: The same sanitizing that occurs during normal image capture will take place. This includes things such as deleting temporary files, cleaning out firewall rules, removing user home space, and removing user accounts.");
        $h .= "\n</strong> \n";
        $h .= i("After the imaging occurs, you will be able to connect to the reservation again. The image will appear to you as if you had just made a new reservation for it.");
        $h .= "\n \n";
        $text .= preg_replace("/(.{1,80}([ \n]|\$))/", '\\1<br>', $h);
        $text .= "</div>\n";
        # imagekeeprescontent
        $text .= i("Are you creating a new image or updating an existing image?") . "<br><br>\n";
        $text .= "<input type=radio name=imgmode id=newimage value=\"\" checked>\n";
        $text .= "<label for=newimage>" . i("Creating New Image") . "</label><br>\n";
        $text .= "<input type=radio name=imgmode id=updateimage value=\"\">\n";
        $text .= "<label for=updateimage id=\"updateimagelabel\">";
        $text .= i("Update Existing Image") . "</label>";
        $text .= "<br><br>\n";
        $text .= "   <div align=\"center\" id=\"imagebtns\">\n";
        $text .= "   <button id=\"imageDlgBtn\" dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Submit") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       submitCreateUpdateImage();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Cancel") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('startimagedlg').hide();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"startimagedisableddlg\"\n";
        $text .= "      title=\"" . i("Create / Update Image") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      style=\"width: 30%;\"\n";
        $text .= "      draggable=true>\n";
        $text .= "<H2>" . i("Create / Update an Image") . "</H2>\n";
        $text .= i("You cannot create new images from this image because the owner of the image has set \"Users have administrative access\" to No under the Advanced Options of the image.");
        $text .= "<br><br>\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Close") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('startimagedisableddlg').hide();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"connectDlg\"\n";
        $text .= "      title=\"" . i("Connect") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      autofocus=false\n";
        $text .= "      draggable=true>\n";
        $text .= "   <div dojoType=\"dijit.layout.ContentPane\" id=\"connectDlgContent\" ";
        $text .= "        style=\"overflow: auto; width: 500px;\"></div>\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Close") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('connectDlg').hide();\n";
        $text .= "       dijit.byId('connectDlgContent').set('content', '');\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"timeoutdlg\"\n";
        $text .= "      title=\"" . i("Reservation Timed Out") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=false>\n";
        $h = i("This reservation has timed out and is no longer available.");
        $text .= preg_replace("/(.{1,30}([ \n]|\$))/", '\\1<br>', $h);
        $text .= "<br><br>\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Okay") . "\n";
        $text .= "\t   <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('timeoutdlg').hide();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<input type=hidden id=addresourcecont>\n";
        $obj = new Image();
        $text .= $obj->addEditDialogHTML(1);
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"updateimagedlg\"\n";
        $text .= "      title=\"" . i("Update Existing Image") . "\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true>\n";
        $text .= "    <script type=\"dojo/connect\" event=onHide>\n";
        $text .= "      hideUpdateImageDlg();\n";
        $text .= "    </script>\n";
        $text .= "   <div id=\"updateimageDlgContent\">\n";
        $text .= "      <h3>" . i("New Revision Comments") . "</h3>\n";
        $h = i("Enter any notes for yourself and other admins about the current state of the image. These are optional and are not visible to end users:");
        $text .= preg_replace("/(.{1,85}([ \n]|\$))/", '\\1<br>', $h);
        $text .= "      <textarea dojoType=\"dijit.form.Textarea\" id=\"newcomments\" ";
        $text .= "      style=\"width: 400px; text-align: left;\">\n\n</textarea>\n";
        $text .= "      <h3>" . i("Previous Revision Comments") . "</h3>\n";
        $text .= "      <div id=\"previouscomments\"></div>\n";
        $text .= "   </div>\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <button id=\"updateImageDlgBtn\" dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Submit") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       submitUpdateImage();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Cancel") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('updateimagedlg').hide();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"clickthroughdlg\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true>\n";
        $text .= "    <script type=\"dojo/connect\" event=onHide>\n";
        $text .= "      hideClickThroughDlg();\n";
        $text .= "    </script>\n";
        $text .= "   <div id=\"clickthroughDlgContent\">\n";
        $text .= "   </div>\n";
        $text .= "   <div align=\"center\" id=\"imagebtns\">\n";
        $text .= "   <button id=\"clickthroughDlgBtn\" dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("I agree") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       clickThroughAgree();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("I do not agree") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('clickthroughdlg').hide();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"clickthroughpreviewdlg\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true>\n";
        $text .= "   <div id=\"clickthroughPreviewDlgContent\"></div>\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Close") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('clickthroughpreviewdlg').hide();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        $text .= "<div dojoType=dijit.Dialog\n";
        $text .= "      id=\"serverdeletedlg\"\n";
        $text .= "      duration=250\n";
        $text .= "      draggable=true>\n";
        $text .= "   <div id=\"serverDeleteDlgContent\">\n";
        $text .= "   <h2>Confirm Server Delete</h2>\n";
        $text .= "   <span class=\"rederrormsg\"><big>\n";
        $warn = i("WARNING: You are not the owner of this reservation. You have been granted access to manage this reservation by another user. Hover over the details icon to see who the owner is. You should not delete this reservation unless the owner is aware that you are deleting it.");
        $text .= preg_replace("/(.{1,80}([ \n]|\$))/", '\\1<br>', $warn);
        $text .= "   </big></span>\n";
        $text .= "   </div><br>\n";
        $text .= "   <div align=\"center\">\n";
        $text .= "   <input type=\"hidden\" id=\"deletecontholder\">\n";
        $text .= "   <button id=\"serverDeleteDlgBtn\" dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Confirm Delete Reservation") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       endServerReservation();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   <button dojoType=\"dijit.form.Button\">\n";
        $text .= "     " . i("Cancel") . "\n";
        $text .= "     <script type=\"dojo/method\" event=\"onClick\">\n";
        $text .= "       dijit.byId('serverdeletedlg').hide();\n";
        $text .= "     </script>\n";
        $text .= "   </button>\n";
        $text .= "   </div>\n";
        $text .= "</div>\n";
        print $text;
    } else {
        $text = str_replace("\n", ' ', $text);
        $text = str_replace("('", "(\\'", $text);
        $text = str_replace("')", "\\')", $text);
        print "document.body.style.cursor = 'default';";
        if (count($requests) == 0) {
            print "dojo.removeClass('noresspan', 'hidden');";
        } else {
            print "dojo.addClass('noresspan', 'hidden');";
        }
        if ($refresh) {
            print "refresh_timer = setTimeout(resRefresh, 20000);\n";
        }
        print setAttribute('subcontent', 'innerHTML', $text);
        print "AJdojoCreate('subcontent');";
        if ($incPaneDetails) {
            $text = detailStatusHTML($refreqid);
            print setAttribute('resStatusText', 'innerHTML', $text);
        }
        print "checkResGone(" . json_encode($reqids) . ");";
        if ($pendingcnt) {
            print "document.title = '{$pendingcnt} Pending :: VCL :: Virtual Computing Lab';";
        } else {
            print "document.title = 'VCL :: Virtual Computing Lab';";
        }
        return;
    }
}
Beispiel #5
0
function submitBlockRequest()
{
    global $submitErr, $user, $days;
    $data = processBlockRequestInput();
    if ($submitErr) {
        newBlockRequest();
        return;
    }
    # FIXME need to handle creation of a block time that we're currently in the
    #    middle of if there wasn't already on we're in the middle of
    if ($data['state'] == 1) {
        # get blockTime entry for this request if we're in the middle of one
        $checkCurBlockTime = 0;
        $query = "SELECT id, " . "start, " . "end " . "FROM blockTimes " . "WHERE start <= NOW() AND " . "end > NOW() AND " . "blockRequestid = {$data['blockRequestid']}";
        $qh = doQuery($query, 101);
        if ($row = mysql_fetch_assoc($qh)) {
            $checkCurBlockTime = 1;
            $curBlockTime = $row;
        }
        # delete entries from blockTimes that start later than now
        $query = "DELETE FROM blockTimes " . "WHERE blockRequestid = {$data['blockRequestid']} AND " . "start > NOW()";
        doQuery($query, 101);
        # delete entries from blockWebDate and blockWebTime
        $query = "DELETE FROM blockWebDate WHERE blockRequestid = {$data['blockRequestid']}";
        doQuery($query, 101);
        $query = "DELETE FROM blockWebTime WHERE blockRequestid = {$data['blockRequestid']}";
        doQuery($query, 101);
    }
    if ($data['available'] == 'weekly') {
        $daymask = 0;
        $startarr = split('/', $data['swdate']);
        $startdate = "20{$startarr[2]}-{$startarr[0]}-{$startarr[1]}";
        $startts = datetimeToUnix("20{$startarr[2]}-{$startarr[0]}-{$startarr[1]} 00:00:00");
        $endarr = split('/', $data['ewdate']);
        $enddt = "20{$endarr[2]}-{$endarr[0]}-{$endarr[1]} 23:59:59";
        $enddate = "20{$endarr[2]}-{$endarr[0]}-{$endarr[1]}";
        $endts = datetimeToUnix($enddt);
        foreach ($data['wdays'] as $day) {
            $key = array_search($day, $days);
            $daymask |= 1 << $key;
        }
    } elseif ($data['available'] == 'monthly') {
        $startarr = split('/', $data['smdate']);
        $startdate = "20{$startarr[2]}-{$startarr[0]}-{$startarr[1]}";
        $startts = datetimeToUnix("20{$startarr[2]}-{$startarr[0]}-{$startarr[1]} 00:00:00");
        $endarr = split('/', $data['emdate']);
        $enddt = "20{$endarr[2]}-{$endarr[0]}-{$endarr[1]} 23:59:59";
        $enddate = "20{$endarr[2]}-{$endarr[0]}-{$endarr[1]}";
        $endts = datetimeToUnix($enddt);
        $selectedday = $data['day'];
    } elseif ($data['available'] == 'list') {
        $last = -1;
        $enddtArr[-1] = '1970-01-01 00:00:00';
        for ($i = 0; $i < 4; $i++) {
            $data['slhour24'][$i] = hour12to24($data['slhour'][$i], $data['slmeridian'][$i]);
            $data['elhour24'][$i] = hour12to24($data['elhour'][$i], $data['elmeridian'][$i]);
            if (empty($data['date'][$i])) {
                $startdtArr[$i] = "0000-00-00 00:00:00";
                $enddtArr[$i] = "0000-00-00 00:00:00";
            } else {
                $datearr = explode('/', $data['date'][$i]);
                $startdtArr[$i] = "20{$datearr[2]}-{$datearr[0]}-{$datearr[1]} {$data['slhour24'][$i]}:{$data['slminute'][$i]}:00";
                $enddtArr[$i] = "20{$datearr[2]}-{$datearr[0]}-{$datearr[1]} {$data['elhour24'][$i]}:{$data['elminute'][$i]}:00";
            }
            if ($data['stime'][$i] == $data['etime'][$i]) {
                continue;
            }
            if ($startdtArr[$i] != $enddtArr[$i] && datetimeToUnix($enddtArr[$last]) < datetimeToUnix($enddtArr[$i])) {
                $last = $i;
            }
        }
        unset($enddtArr[-1]);
        $endts = datetimeToUnix($enddtArr[$last]);
        $enddt = $enddtArr[$last];
    }
    if ($data['state'] == 1) {
        $query = "UPDATE blockRequest " . "SET name = '{$data['blockname']}', " . "imageid = {$data['imageid']}, " . "numMachines = {$data['machinecnt']}, " . "groupid = {$data['usergroupid']}, " . "admingroupid = {$data['admingroupid']}, " . "repeating = '{$data['available']}', " . "expireTime = '{$enddt}' " . "WHERE  id = {$data['blockRequestid']}";
        doQuery($query, 101);
        $blockreqid = $data['blockRequestid'];
    } else {
        $managementnodes = getManagementNodes('future');
        if (empty($managementnodes)) {
            abort(40);
        }
        $mnid = array_rand($managementnodes);
        $query = "INSERT INTO blockRequest " . "(name, " . "imageid, " . "numMachines, " . "groupid, " . "repeating, " . "ownerid, " . "admingroupid, " . "managementnodeid, " . "expireTime) " . "VALUES " . "('{$data['blockname']}', " . "{$data['imageid']}, " . "{$data['machinecnt']}, " . "{$data['usergroupid']}, " . "'{$data['available']}', " . "{$user['id']}, " . "{$data['admingroupid']}, " . "{$mnid}, " . "'{$enddt}')";
        doQuery($query, 101);
        $qh = doQuery("SELECT LAST_INSERT_ID() FROM blockRequest", 101);
        if (!($row = mysql_fetch_row($qh))) {
            abort(380);
        }
        $blockreqid = $row[0];
    }
    if ($data['available'] == 'weekly') {
        $query = "INSERT INTO blockWebDate " . "(blockRequestid, " . "start, " . "end, " . "days) " . "VALUES " . "({$blockreqid}, " . "'{$startdate}', " . "'{$enddate}', " . "{$daymask})";
        doQuery($query, 101);
        for ($i = 0; $i < 4; $i++) {
            $query = "INSERT INTO blockWebTime " . "(blockRequestid, " . "starthour, " . "startminute, " . "startmeridian, " . "endhour, " . "endminute, " . "endmeridian, " . "`order`) " . "VALUES " . "({$blockreqid}, " . "'{$data['swhour'][$i]}', " . "'{$data['swminute'][$i]}', " . "'{$data['swmeridian'][$i]}', " . "'{$data['ewhour'][$i]}', " . "'{$data['ewminute'][$i]}', " . "'{$data['ewmeridian'][$i]}', " . "{$i})";
            doQuery($query, 101);
        }
        for ($day = $startts; $day <= $endts; $day += SECINDAY) {
            if (!in_array(date('l', $day), $data['wdays'])) {
                continue;
            }
            for ($i = 0; $i < 4; $i++) {
                if ($data['stime'][$i] == $data['etime'][$i]) {
                    continue;
                }
                $data['swhour'][$i] = hour12to24($data['swhour'][$i], $data['swmeridian'][$i]);
                $data['ewhour'][$i] = hour12to24($data['ewhour'][$i], $data['ewmeridian'][$i]);
                $start = date("Y-m-d", $day) . " {$data['swhour'][$i]}:{$data['swminute'][$i]}:00";
                $end = date("Y-m-d", $day) . " {$data['ewhour'][$i]}:{$data['ewminute'][$i]}:00";
                $query = "INSERT INTO blockTimes " . "(blockRequestid, " . "start, " . "end) " . "VALUES " . "({$blockreqid}, " . "'{$start}', " . "'{$end}')";
                doQuery($query, 101);
            }
        }
    } elseif ($data['available'] == 'monthly') {
        $query = "INSERT INTO blockWebDate " . "(blockRequestid, " . "start, " . "end, " . "days, " . "weeknum) " . "VALUES " . "({$blockreqid}, " . "'{$startdate}', " . "'{$enddate}', " . "{$selectedday}, " . "{$data['weeknum']})";
        doQuery($query, 101);
        for ($i = 0; $i < 4; $i++) {
            $query = "INSERT INTO blockWebTime " . "(blockRequestid, " . "starthour, " . "startminute, " . "startmeridian, " . "endhour, " . "endminute, " . "endmeridian, " . "`order`) " . "VALUES " . "({$blockreqid}, " . "'{$data['smhour'][$i]}', " . "'{$data['smminute'][$i]}', " . "'{$data['smmeridian'][$i]}', " . "'{$data['emhour'][$i]}', " . "'{$data['emminute'][$i]}', " . "'{$data['emmeridian'][$i]}', " . "{$i})";
            doQuery($query, 101);
        }
        for ($day = $startts; $day <= $endts; $day += SECINDAY) {
            if (date('w', $day) + 1 != $data['day']) {
                continue;
            }
            $dayofmon = date('j', $day);
            if ($data['weeknum'] == 1 && $dayofmon < 8 || $data['weeknum'] == 2 && 7 < $dayofmon && $dayofmon < 15 || $data['weeknum'] == 3 && 14 < $dayofmon && $dayofmon < 22 || $data['weeknum'] == 4 && 21 < $dayofmon && $dayofmon < 29 || $data['weeknum'] == 5 && 28 < $dayofmon && $dayofmon < 32) {
                $thedate = date("Y-m-d", $day);
                for ($i = 0; $i < 4; $i++) {
                    if ($data['stime'][$i] == $data['etime'][$i]) {
                        continue;
                    }
                    $data['smhour'][$i] = hour12to24($data['smhour'][$i], $data['smmeridian'][$i]);
                    $data['emhour'][$i] = hour12to24($data['emhour'][$i], $data['emmeridian'][$i]);
                    $start = "{$thedate} {$data['smhour'][$i]}:{$data['smminute'][$i]}:00";
                    $end = "{$thedate} {$data['emhour'][$i]}:{$data['emminute'][$i]}:00";
                    $query = "INSERT INTO blockTimes " . "(blockRequestid, " . "start, " . "end) " . "VALUES " . "({$blockreqid}, " . "'{$start}', " . "'{$end}')";
                    doQuery($query, 101);
                }
            }
        }
    } elseif ($data['available'] == 'list') {
        for ($i = 0; $i < 4; $i++) {
            $query = "INSERT INTO blockWebDate " . "(blockRequestid, " . "start, " . "end, " . "days) " . "VALUES " . "({$blockreqid}, " . "'{$startdtArr[$i]}', " . "'{$enddtArr[$i]}', " . "{$i})";
            doQuery($query, 101);
            $query = "INSERT INTO blockWebTime " . "(blockRequestid, " . "starthour, " . "startminute, " . "startmeridian, " . "endhour, " . "endminute, " . "endmeridian, " . "`order`) " . "VALUES " . "({$blockreqid}, " . "'{$data['slhour'][$i]}', " . "'{$data['slminute'][$i]}', " . "'{$data['slmeridian'][$i]}', " . "'{$data['elhour'][$i]}', " . "'{$data['elminute'][$i]}', " . "'{$data['elmeridian'][$i]}', " . "{$i})";
            doQuery($query, 101);
            if ($data['stime'][$i] == $data['etime'][$i]) {
                continue;
            }
            $query = "INSERT INTO blockTimes " . "(blockRequestid, " . "start, " . "end) " . "VALUES " . "({$blockreqid}, " . "'{$startdtArr[$i]}', " . "'{$enddtArr[$i]}')";
            doQuery($query, 101);
        }
    }
    if ($data['state'] == 1) {
        if ($checkCurBlockTime) {
            $query = "SELECT id, " . "start, " . "end " . "FROM blockTimes " . "WHERE start <= NOW() AND " . "end > NOW() AND " . "blockRequestid = {$data['blockRequestid']} AND " . "id != {$curBlockTime['id']}";
            $qh = doQuery($query, 101);
            if ($row = mysql_fetch_assoc($qh)) {
                if ($curBlockTime['end'] != $row['end']) {
                    # update old end time
                    $query = "UPDATE blockTimes " . "SET end = '{$row['end']}' " . "WHERE id = {$curBlockTime['id']}";
                    doQuery($query, 101);
                }
                # delete $row entry
                doQuery("DELETE FROM blockTimes WHERE id = {$row['id']}", 101);
            } else {
                # the blockTime we were in the middle of was not recreated, so
                #    delete the old one
                doQuery("DELETE FROM blockTimes WHERE id = {$curBlockTime['id']}", 101);
            }
        }
        print "<H2>Edit Block Reservation</H2>\n";
        print "Block request has been updated<br>\n";
    } else {
        print "<H2>New Block Reservation</H2>\n";
        print "Block request added to database<br>\n";
    }
}
Beispiel #6
0
 function AJsubmitCompStateChange()
 {
     global $user;
     $newstateid = getContinuationVar('newstateid');
     $compids = getContinuationVar('compids');
     $states = getStates();
     $ret = array('status' => 'success', 'title' => "Change State", 'clearselection' => 0, 'newstate' => $states[$newstateid], 'refreshcount' => 1);
     # get ids from getUserResources because that data should already be in cache
     $resources = getUserResources(array("imageAdmin", "imageCheckOut"));
     $tmp = array_keys($resources['image']);
     $semimageid = $tmp[0];
     $semrevid = getProductionRevisionid($semimageid);
     if (!empty($resources['managementnode'])) {
         $tmp = array_keys($resources['managementnode']);
         $semmnid = $tmp[0];
     } else {
         $allmns = array_keys(getManagementNodes('future'));
         if (empty($allmns)) {
             $ret = array('status' => 'error', 'errormsg' => 'No management nodes are available for controlling the submitted computers.');
             sendJSON($ret);
             return;
         }
         $semmnid = $allmns[0];
     }
     if ($newstateid == 2) {
         $fails = array('provnone' => array(), 'reserved' => array(), 'hostfail' => array(), 'hasvms' => array());
         $availablenow = array();
         $checkvms = array();
         $checkhosts = array();
         $noaction = array();
         $computers = $this->getData($this->defaultGetDataArgs);
         $inusecompids = array();
         $allids = implode(',', $compids);
         $query = "SELECT rs.computerid " . "FROM reservation rs, " . "request rq " . "WHERE rs.requestid = rq.id AND " . "rq.end > NOW() AND " . "rq.start < NOW() AND " . "rq.stateid NOT IN (1, 5, 11, 12) AND " . "rs.computerid IN ({$allids})";
         $qh = doQuery($query);
         while ($row = mysql_fetch_assoc($qh)) {
             $inusecompids[$row['computerid']] = 1;
         }
         # check initial conditions
         foreach ($compids as $compid) {
             # already in available
             if ($computers[$compid]['state'] == 'available') {
                 $noaction[] = $compid;
                 continue;
             }
             # no provisioning engine
             if ($computers[$compid]['provisioning'] == 'None') {
                 $fails['provnone'][] = $compid;
                 continue;
             }
             # non-VM in maintenance without a vmhost entry or in hpc
             if ($computers[$compid]['state'] == 'hpc' || $computers[$compid]['state'] == 'maintenance' && is_null($computers[$compid]['vmprofileid']) && $computers[$compid]['type'] != 'virtualmachine') {
                 $availablenow[] = $compid;
                 continue;
             }
             # has active reservation
             if (array_key_exists($compid, $inusecompids)) {
                 $fails['reserved'][] = $compid;
                 continue;
             }
             # in reload, reloading, reserved, inuse, or failed with no active reservation
             if (preg_match('/^(reload|reloading|reserved|inuse|failed|timeout)$/', $computers[$compid]['state'])) {
                 $availablenow[] = $compid;
                 continue;
             }
             # vmhostinuse - check for assigned VMs
             if ($computers[$compid]['state'] == 'vmhostinuse') {
                 $checkvms[] = $compid;
                 continue;
             }
             # VM in maintenance
             if ($computers[$compid]['state'] == 'maintenance' && $computers[$compid]['type'] == 'virtualmachine') {
                 $checkhosts[] = $compid;
                 continue;
             }
             # maintenance - check for previously being a vmhost
             if ($computers[$compid]['state'] == 'maintenance' && !is_null($computers[$compid]['vmprofileid'])) {
                 $checkvms[] = $compid;
                 continue;
             }
         }
         if (count($checkvms)) {
             $ids = implode(',', $checkvms);
             $query = "SELECT h.id, " . "COUNT(vm.id) AS count " . "FROM computer h " . "LEFT JOIN vmhost vh ON (h.id = vh.computerid) " . "LEFT JOIN computer vm ON (vh.id = vm.vmhostid) " . "WHERE h.id IN ({$ids}) " . "GROUP BY vh.computerid";
             $qh = doQuery($query);
             while ($row = mysql_fetch_assoc($qh)) {
                 if ($row['count']) {
                     $fails['hasvms'][] = $row['id'];
                 } else {
                     $availablenow[] = $row['id'];
                 }
             }
         }
         if (count($checkhosts)) {
             $ids = implode(',', $checkhosts);
             $query = "SELECT h.stateid, " . "vm.id " . "FROM computer vm " . "LEFT JOIN vmhost vh ON (vm.vmhostid = vh.id) " . "LEFT JOIN computer h ON (vh.computerid = h.id) " . "WHERE vm.id IN ({$ids})";
             $qh = doQuery($query);
             while ($row = mysql_fetch_assoc($qh)) {
                 if ($row['stateid'] != 20) {
                     $fails['hostfail'][] = $row['id'];
                 } else {
                     $availablenow[] = $row['id'];
                 }
             }
         }
         if (count($availablenow)) {
             $allids = implode(',', $availablenow);
             $query = "UPDATE computer " . "SET stateid = 2, " . "notes = '' " . "WHERE id IN ({$allids})";
             doQuery($query);
         }
         $msg = '';
         if (count($noaction)) {
             $msg .= "The following computers were already in the available ";
             $msg .= "state:<br><br>\n";
             foreach ($noaction as $compid) {
                 $msg .= "{$computers[$compid]['hostname']}<br>\n";
             }
             $msg .= "<br>\n";
         }
         if (count($availablenow)) {
             $msg .= "The following computers were changed to the available ";
             $msg .= "state:<br><br>\n";
             foreach ($availablenow as $compid) {
                 $msg .= "{$computers[$compid]['hostname']}<br>\n";
             }
             $msg .= "<br>\n";
         }
         if (count($fails['provnone'])) {
             $msg .= "<span class=\"rederrormsg\">\n";
             $msg .= "The following computers cannot be in the available state ";
             $msg .= "because they have no provisioning engine:</span><br><br>\n";
             foreach ($fails['provnone'] as $compid) {
                 $msg .= "{$computers[$compid]['hostname']}<br>\n";
             }
             $msg .= "<br>\n";
         }
         if (count($fails['reserved'])) {
             $msg .= "<span class=\"rederrormsg\">\n";
             $msg .= "The following computers are currently in use and could not have ";
             $msg .= "their states changed at this time:</span><br><br>\n";
             foreach ($fails['reserved'] as $compid) {
                 $msg .= "{$computers[$compid]['hostname']}<br>\n";
             }
             $msg .= "<br>\n";
         }
         if (count($fails['hasvms'])) {
             $msg .= "<span class=\"rederrormsg\">\n";
             $msg .= "The following computers currently have VMs assigned to them ";
             $msg .= "and cannot be moved to available until the VMs are removed:";
             $msg .= "</span><br><br>\n";
             foreach ($fails['hasvms'] as $compid) {
                 $msg .= "{$computers[$compid]['hostname']}<br>\n";
             }
             $msg .= "<br>\n";
         }
         if (count($fails['hostfail'])) {
             $msg .= "<span class=\"rederrormsg\">\n";
             $msg .= "The following VMs are not currently assigned to a host in ";
             $msg .= "the vmhostinuse state:</span><br><br>\n";
             foreach ($fails['hostfail'] as $compid) {
                 $msg .= "{$computers[$compid]['hostname']}<br>\n";
             }
             $msg .= "<br>\n";
         }
     } elseif ($newstateid == 10 || $newstateid == 23) {
         if ($newstateid == 10) {
             $notes = processInputVar('notes', ARG_STRING);
             if (get_magic_quotes_gpc()) {
                 $notes = stripslashes($notes);
             }
             $notes = mysql_real_escape_string($notes);
             $notes = $user["unityid"] . " " . unixToDatetime(time()) . "@" . $notes;
         }
         $vclreloadid = getUserlistID('vclreload@Local');
         $computers = $this->getData($this->defaultGetDataArgs);
         $noaction = array();
         $changenow = array();
         $changeasap = array();
         $changetimes = array();
         $vmwithhost = array();
         $fails = array();
         $semstart = unixToDatetime(time());
         $semend = '2038-01-01 00:00:00';
         foreach ($compids as $compid) {
             if ($newstateid == 10 && $computers[$compid]['type'] == 'virtualmachine' && in_array($computers[$compid]['vmhostcomputerid'], $compids)) {
                 $vmwithhost[] = $compid;
             }
             if ($newstateid == 10 && $computers[$compid]['state'] == 'maintenance' || $newstateid == 23 && $computers[$compid]['state'] == 'hpc') {
                 $noaction[] = $compid;
                 continue;
             }
             # try to move future reservations off of computer
             moveReservationsOffComputer($compid);
             cleanSemaphore();
             $reloadstart = getCompFinalReservationTime($compid);
             if ($computers[$compid]['state'] == 'vmhostinuse') {
                 $sem = array('imageid' => $semimageid, 'revid' => $semrevid, 'mnid' => $semmnid, 'start' => $semstart, 'end' => $semend);
                 moveReservationsOffVMs($compid, $sem);
                 cleanSemaphore();
                 $reloadstart = getCompFinalVMReservationTime($compid, 1, 1);
                 if ($reloadstart == -1) {
                     cleanSemaphore();
                     $fails[] = $compid;
                     continue;
                 } elseif ($reloadstart > 0) {
                     if (unixToDatetime($reloadstart) == '2038-01-01 00:00:00') {
                         # host has a VM reserved indefintely
                         $fails[] = $compid;
                         continue;
                     }
                     # schedule tomaintenance/tohpc reservations for VMs and host
                     $noimageid = getImageId('noimage');
                     $revid = getProductionRevisionid($noimageid);
                     $startdt = unixToDatetime($reloadstart);
                     $end = $reloadstart + SECINMONTH;
                     $enddt = unixToDatetime($end);
                     $query = "SELECT vm.id " . "FROM computer vm, " . "vmhost v " . "WHERE v.computerid = {$compid} AND " . "vm.vmhostid = v.id";
                     $qh = doQuery($query);
                     $setnoteids = array();
                     while ($row = mysql_fetch_assoc($qh)) {
                         $checkstart = getExistingChangeStateStartTime($row['id'], 18);
                         if ($checkstart) {
                             if ($checkstart > $reloadstart) {
                                 # update start time of existing tomaintenance reservation
                                 updateExistingToState($row['id'], $startdt, 18);
                             }
                             # leave existing tomaintenance reservation as is
                         } elseif (!simpleAddRequest($row['id'], $noimageid, $revid, $startdt, $enddt, 18, $vclreloadid)) {
                             cleanSemaphore();
                             $fails[] = $compid;
                             continue 2;
                             # jump out of while, continue with foreach loop
                         }
                         $setnoteids[] = $row['id'];
                     }
                     if ($newstateid == 10 && count($setnoteids)) {
                         $inids = implode(',', $setnoteids);
                         $query = "UPDATE computer " . "SET notes = 'maintenance with host {$compid}' " . "WHERE id IN ({$inids})";
                         doQuery($query);
                     }
                     $start = $reloadstart + 300;
                     # allow 5 minutes for VMs to get removed
                     $startdt = unixToDatetime($start);
                     # lock this computer
                     if (!retryGetSemaphore($semimageid, $semrevid, $semmnid, $compid, $startdt, $enddt)) {
                         cleanSemaphore();
                         $fails[] = $compid;
                         continue;
                     }
                     if ($newstateid == 10) {
                         $tostateid = 18;
                     } else {
                         $tostateid = 22;
                     }
                     $checkstart = getExistingChangeStateStartTime($compid, $tostateid);
                     if ($checkstart) {
                         if ($checkstart > $start) {
                             # update start time of existing tomaintenance/tohpc reservation
                             updateExistingToState($compid, $startdt, $tostateid);
                         }
                         # leave existing tomaintenance/tohpc reservation as is
                     } elseif (!simpleAddRequest($compid, $noimageid, $revid, $startdt, $enddt, $tostateid, $vclreloadid)) {
                         cleanSemaphore();
                         $fails[] = $compid;
                         continue;
                     }
                     cleanSemaphore();
                     $changetimes[$compid] = $start;
                     $changeasap[] = $compid;
                     continue;
                 } else {
                     if ($newstateid == 10) {
                         $note = "maintenance with host {$compid}";
                     } else {
                         $note = "maintenance so {$compid} can go to hpc";
                     }
                     # no VMs or no reservations on assigned VMs
                     $query = "UPDATE computer c " . "INNER JOIN vmhost v ON (c.vmhostid = v.id) " . "SET c.stateid = 10, " . "c.notes = '{$note}' " . "WHERE v.computerid = {$compid}";
                     doQuery($query);
                 }
             } elseif ($reloadstart) {
                 if (unixToDatetime($reloadstart) == '2038-01-01 00:00:00') {
                     # node is reserved indefintely
                     $fails[] = $compid;
                     continue;
                 }
                 # computer has reservations, schedule tomaintenance
                 $noimageid = getImageId('noimage');
                 $revid = getProductionRevisionid($noimageid);
                 $startdt = unixToDatetime($reloadstart);
                 $end = $reloadstart + SECINMONTH;
                 $enddt = unixToDatetime($end);
                 # lock this computer
                 if (!retryGetSemaphore($semimageid, $semrevid, $semmnid, $compid, $startdt, $enddt)) {
                     $fails[] = $compid;
                     cleanSemaphore();
                     continue;
                 }
                 if ($newstateid == 10) {
                     $tostateid = 18;
                 } else {
                     $tostateid = 22;
                 }
                 $checkstart = getExistingChangeStateStartTime($compid, $tostateid);
                 if ($checkstart) {
                     if ($checkstart > $reloadstart) {
                         # update start time of existing tomaintenance/tohpc reservation
                         updateExistingToState($compid, $startdt, $tostateid);
                     } else {
                         # leave existing tomaintenance/tohpc reservation as is
                         $reloadstart = $checkstart;
                     }
                 } elseif (!simpleAddRequest($compid, $noimageid, $revid, $startdt, $enddt, $tostateid, $vclreloadid)) {
                     $fails[] = $compid;
                     cleanSemaphore();
                     continue;
                 }
                 cleanSemaphore();
                 $changetimes[$compid] = $reloadstart;
                 $changeasap[] = $compid;
                 continue;
             }
             # change to maintenance/tohpc state and save in $changenow
             // if we wait and put them all in maintenance/hpc at the same time,
             # we may end up moving reservations to the computer later in the
             # loop
             # lock this computer
             if (!retryGetSemaphore($semimageid, $semrevid, $semmnid, $compid, $semstart, $semend)) {
                 $fails[] = $compid;
                 cleanSemaphore();
                 continue;
             }
             $query = "UPDATE computer " . "SET stateid = {$newstateid} " . "WHERE id = {$compid}";
             doQuery($query, 101);
             $changenow[] = $compid;
             cleanSemaphore();
         }
         if ($newstateid == 10 && (count($noaction) || count($changeasap))) {
             $comparr = array_merge($noaction, $changeasap);
             $allids = implode(',', $comparr);
             if (count($vmwithhost)) {
                 $skipids = implode(',', $vmwithhost);
             } else {
                 $skipids = "''";
             }
             $query = "UPDATE computer " . "SET notes = '{$notes}' " . "WHERE id IN ({$allids}) AND " . "id NOT IN ({$skipids})";
             doQuery($query, 101);
             $updatevms = array_intersect($vmwithhost, $comparr);
             if (count($updatevms)) {
                 $inids = implode(',', $updatevms);
                 $query = "UPDATE computer vm " . "INNER JOIN vmhost v ON (vm.vmhostid = v.id) " . "SET vm.notes = CONCAT('maintenance with host ', v.computerid) " . "WHERE vm.id IN ({$inids})";
                 doQuery($query);
             }
         }
         if ($newstateid == 10) {
             $newstate = 'maintenance';
         } else {
             $newstate = 'hpc';
         }
         $msg = '';
         if (count($changenow)) {
             $msg .= "The following computers were immediately placed into the ";
             $msg .= "{$newstate} state:<br><br>\n";
             $msg .= "<span class=\"ready\">\n";
             foreach ($changenow as $compid) {
                 $msg .= "{$computers[$compid]['hostname']}<br>\n";
             }
             $msg .= "</span><br>\n";
         }
         if (count($changeasap)) {
             $msg .= "The following computers are currently reserved ";
             $msg .= "and will be placed in the {$newstate} state at the time listed ";
             $msg .= "for each computer:\n";
             $msg .= "<table>\n";
             $msg .= "  <tr>\n";
             $msg .= "    <th>Computer</th>\n";
             $msg .= "    <th>Time</th>\n";
             $msg .= "  </tr>\n";
             foreach ($changeasap as $compid) {
                 $msg .= "  <tr>\n";
                 $msg .= "    <td align=center><span class=\"wait\">{$computers[$compid]['hostname']}</span></td>\n";
                 $time = date('n/j/y g:i a', $changetimes[$compid]);
                 $msg .= "    <td align=center>{$time}</td>\n";
                 $msg .= "  </tr>\n";
             }
             $msg .= "</table>\n";
             $msg .= "<br>\n";
         }
         if (count($fails)) {
             $msg .= "The following computers are currently reserved ";
             $msg .= "but could not be scheduled to be moved to the {$newstate} state ";
             $msg .= "at this time:<br><br>\n";
             $msg .= "<span class=\"rederrormsg\">\n";
             foreach ($fails as $compid) {
                 $msg .= "{$computers[$compid]['hostname']}<br>\n";
             }
             $msg .= "</span><br>\n";
         }
         if (count($noaction)) {
             $msg .= "The following computers were already in the {$newstate} state";
             if ($newstateid == 10) {
                 $msg .= " and had their notes on being in the maintenance state updated";
             }
             $msg .= ":<br><br>\n";
             foreach ($noaction as $compid) {
                 $msg .= "{$computers[$compid]['hostname']}<br>\n";
             }
             $msg .= "<br>\n";
         }
     } elseif ($newstateid == 20) {
         $profileid = processInputVar('profileid', ARG_NUMERIC);
         $profiles = getContinuationVar('profiles');
         if (!array_key_exists($profileid, $profiles)) {
             $ret = array('status' => 'error', 'errormsg' => 'Invalid profile submitted');
             sendJSON($ret);
             return;
         }
         $vclreloadid = getUserlistID('vclreload@Local');
         $imagerevisionid = getProductionRevisionid($profiles[$profileid]['imageid']);
         $computers = $this->getData($this->defaultGetDataArgs);
         $noaction = array();
         $changenow = array();
         $changenowreload = array();
         $changeasap = array();
         $changetimes = array();
         $fails = array();
         $semstart = unixToDatetime(time());
         $semend = '2038-01-01 00:00:00';
         $maintvmids = array();
         $vmnotallowed = array();
         $allvmids = array();
         $allids = implode(',', $compids);
         $query = "SELECT v.computerid AS compid, " . "vm.id AS vmid, " . "vm.notes, " . "vm.stateid AS vmstateid " . "FROM computer vm, " . "vmhost v " . "WHERE v.computerid IN ({$allids}) AND " . "vm.vmhostid = v.id";
         $qh = doQuery($query);
         while ($row = mysql_fetch_assoc($qh)) {
             if (!array_key_exists($row['compid'], $maintvmids)) {
                 $maintvmids[$row['compid']] = array();
             }
             if ($row['vmstateid'] == 10 && $row['notes'] == "maintenance with host {$row['compid']}") {
                 $maintvmids[$row['compid']][] = $row['vmid'];
             }
             $allvmids[$row['compid']][] = $row['vmid'];
         }
         foreach ($compids as $compid) {
             if ($computers[$compid]['type'] == 'virtualmachine') {
                 $vmnotallowed[] = $compid;
                 continue;
             }
             # try to move future reservations off of computer
             moveReservationsOffComputer($compid);
             cleanSemaphore();
             if ($computers[$compid]['state'] == 'maintenance') {
                 if ($computers[$compid]['provisioning'] != 'None') {
                     # schedule tovmhostinuse
                     $start = getReloadStartTime();
                     # put computer in reload state so vcld will not ignore due to being in maintenance
                     $query = "UPDATE computer " . "SET stateid = 19 " . "WHERE id = {$compid}";
                     doQuery($query);
                     $rc = $this->scheduleTovmhostinuse($compid, $profiles[$profileid]['imageid'], $start, $profileid, $computers[$compid]['vmprofileid']);
                     cleanSemaphore();
                     if (!$rc) {
                         $fails[] = $compid;
                         continue;
                     }
                     if (!is_null($computers[$compid]['vmprofileid']) && array_key_exists($compid, $maintvmids) && count($maintvmids[$compid])) {
                         $noimageid = getImageId('noimage');
                         $revid = getProductionRevisionid($noimageid);
                         $reloadstart = $start + 1800;
                         $reloadstartdt = unixToDatetime($reloadstart);
                         $end = $reloadstart + 3600;
                         $enddt = unixToDatetime($end);
                         foreach ($maintvmids[$compid] as $vmid) {
                             if (!retryGetSemaphore($semimageid, $semrevid, $semmnid, $vmid, $reloadstartdt, $enddt)) {
                                 continue;
                             }
                             simpleAddRequest($vmid, $noimageid, $revid, $reloadstartdt, $enddt, 19, $vclreloadid);
                             # continue even if failed to schedule VM to be reloaded
                         }
                         cleanSemaphore();
                     }
                     $changenowreload[] = $compid;
                 } else {
                     $query = "UPDATE computer " . "SET stateid = 20, " . "notes = '' " . "WHERE id = {$compid}";
                     doQuery($query);
                     $this->updateVmhostProfile($compid, $profileid, $computers[$compid]['vmprofileid']);
                     if (array_key_exists($compid, $maintvmids) && count($maintvmids[$compid])) {
                         $allids = implode(',', $maintvmids[$compid]);
                         $query = "UPDATE computer " . "SET stateid = 2, " . "notes = '' " . "WHERE id in ({$allids})";
                         doQuery($query);
                     }
                     $changenow[] = $compid;
                 }
             } elseif ($computers[$compid]['state'] == 'hpc') {
                 if ($computers[$compid]['provisioning'] != 'None') {
                     # schedule tovmhostinuse
                     $start = getReloadStartTime();
                     # put computer in reload state so vcld will not ignore due to being in maintenance
                     $query = "UPDATE computer " . "SET stateid = 19 " . "WHERE id = {$compid}";
                     doQuery($query);
                     $rc = $this->scheduleTovmhostinuse($compid, $profiles[$profileid]['imageid'], $start, $profileid, $computers[$compid]['vmprofileid']);
                     cleanSemaphore();
                     if (!$rc) {
                         $fails[] = $compid;
                         continue;
                     }
                     $changenowreload[] = $compid;
                 } else {
                     $query = "UPDATE computer " . "SET stateid = 20, " . "notes = '' " . "WHERE id = {$compid}";
                     doQuery($query);
                     $this->updateVmhostProfile($compid, $profileid, $computers[$compid]['vmprofileid']);
                     $changenow[] = $compid;
                 }
             } elseif ($computers[$compid]['state'] == 'vmhostinuse') {
                 if ($profiles[$computers[$compid]['vmprofileid']]['imageid'] != $profiles[$profileid]['imageid']) {
                     if ($computers[$compid]['provisioning'] != 'None') {
                         $sem = array('imageid' => $semimageid, 'revid' => $semrevid, 'mnid' => $semmnid, 'start' => $semstart, 'end' => $semend);
                         moveReservationsOffVMs($compid, $sem);
                         cleanSemaphore();
                         $reloadstart = getCompFinalVMReservationTime($compid, 1);
                         if ($reloadstart < 0) {
                             $fails[] = $compid;
                             cleanSemaphore();
                             continue;
                         }
                         if ($reloadstart == 0) {
                             $start = getReloadStartTime();
                         } else {
                             $start = $reloadstart;
                         }
                         $noimageid = getImageId('noimage');
                         $revid = getProductionRevisionid($noimageid);
                         $startdt = unixToDatetime($start);
                         $end = $start + SECINWEEK;
                         $enddt = unixToDatetime($end);
                         if ($start == $reloadstart) {
                             # check for existing reload reservations for all VMs and host
                             $times = array();
                             $reqids = array();
                             $inids = implode(',', $allvmids[$compid]);
                             $query = "SELECT UNIX_TIMESTAMP(MIN(rq.start)) AS start, " . "rs.computerid, " . "rq.id " . "FROM request rq, " . "reservation rs " . "WHERE rs.requestid = rq.id AND " . "rs.computerid IN ({$inids}) AND " . "rq.stateid = 19 AND " . "rs.imageid = {$noimageid} AND " . "rq.start > NOW() " . "GROUP BY rs.computerid " . "ORDER BY start";
                             $qh = doQuery($query);
                             if (mysql_num_rows($qh) == count($allvmids)) {
                                 while ($row = mysql_fetch_assoc($qh)) {
                                     $times[$row['start']] = 1;
                                     $reqids[] = $row['id'];
                                 }
                                 if (count($times) == 1) {
                                     # found existing reload reservations for all VMs, now check host
                                     $hoststart = $times[0] + 300;
                                     $hoststartdt = unixToDatetime($hoststart);
                                     $hostend = $hoststart + SECINYEAR;
                                     $hostenddt = unixToDatetime($hostend);
                                     $query = "SELECT rq.id, " . "rq.start " . "FROM request rq, " . "reservation rs " . "WHERE rs.requestid = rq.id AND " . "rs.computerid = {$compid} AND " . "rq.start = '{$hoststartdt}' AND " . "rq.end = '{$hostenddt}' AND " . "rs.imageid = '{$profiles[$profileid]['imageid']}' AND " . "rq.stateid = 21";
                                     $qh = doQuery($query);
                                     if ($row = mysql_fetch_assoc($qh)) {
                                         # node was previously scheduled to be reloaded for vmhostinuse
                                         if ($times[0] > $start) {
                                             # update existing reservations
                                             $allreqids = implode(',', $reqids);
                                             $query1 = "UPDATE request " . "SET start = '{$startdt}', " . "end = '{$enddt}' " . "WHERE id IN ({$allreqids})";
                                             # delay host by 5 minutes
                                             $start = $start + 300;
                                             $startdt = unixToDatetime($start);
                                             $end = $start + SECINYEAR;
                                             $enddt = unixToDatetime($end);
                                             # lock this computer
                                             if (!retryGetSemaphore($semimageid, $semrevid, $semmnid, $compid, $startdt, $enddt)) {
                                                 $fails[] = $compid;
                                                 continue;
                                             }
                                             doQuery($query1);
                                             $query2 = "UPDATE request " . "SET start = '{$startdt}', " . "end = '{$enddt}' " . "WHERE id = {$row['id']}";
                                             doQuery($query2);
                                             $changeasap[] = $compid;
                                             $changetimes[$compid] = $start;
                                         } else {
                                             # just leave the existing ones there
                                             $changeasap[] = $compid;
                                             $changetimes[$compid] = $times[0] + 300;
                                         }
                                         cleanSemaphore();
                                         continue;
                                     }
                                 }
                             }
                         }
                         if (array_key_exists($compid, $allvmids)) {
                             foreach ($allvmids[$compid] as $vmid) {
                                 $rc = simpleAddRequest($vmid, $noimageid, $revid, $startdt, $enddt, 19, $vclreloadid);
                                 if (!$rc) {
                                     $fails[] = $compid;
                                     cleanSemaphore();
                                     continue 2;
                                     # jump out of this foreach to the bigger foreach
                                 }
                             }
                         }
                         $start = $start + 300;
                         # give 5 minutes for VMs
                         $rc = $this->scheduleTovmhostinuse($compid, $profiles[$profileid]['imageid'], $start, $profileid, $computers[$compid]['vmprofileid']);
                         if (!$rc) {
                             $fails[] = $compid;
                             continue;
                         }
                         if ($reloadstart) {
                             $changeasap[] = $compid;
                             $changetimes[$compid] = $reloadstart;
                         } else {
                             $changenowreload[] = $compid;
                         }
                     } else {
                         $this->updateVmhostProfile($compid, $profileid, $computers[$compid]['vmprofileid']);
                         $changenow[] = $compid;
                     }
                 } else {
                     $noaction[] = $compid;
                 }
             } elseif (($reloadstart = moveReservationsOffComputer($compid)) == 0) {
                 $start = getCompFinalReservationTime($compid, 21);
                 $rc = $this->scheduleTovmhostinuse($compid, $profiles[$profileid]['imageid'], $start, $profileid, $computers[$compid]['vmprofileid']);
                 if (!$rc) {
                     $fails[] = $compid;
                     continue;
                 }
                 $changeasap[] = $compid;
                 if (isset($this->startchange)) {
                     $start = $this->startchange;
                 }
                 $changetimes[$compid] = $start;
             } else {
                 if ($computers[$compid]['provisioning'] != 'None') {
                     $start = getCompFinalReservationTime($compid, 21);
                     $now = 0;
                     if ($start == 0) {
                         $start = getReloadStartTime();
                         $now = 1;
                     }
                     $rc = $this->scheduleTovmhostinuse($compid, $profiles[$profileid]['imageid'], $start, $profileid, $computers[$compid]['vmprofileid']);
                     if (!$rc) {
                         $fails[] = $compid;
                         continue;
                     }
                     if ($now) {
                         $changenowreload[] = $compid;
                     } else {
                         $changeasap[] = $compid;
                         $changetimes[$compid] = $start;
                     }
                 } else {
                     $query = "UPDATE computer " . "SET stateid = 20, " . "notes = '' " . "WHERE id = {$compid}";
                     doQuery($query);
                     $this->updateVmhostProfile($compid, $profileid, $computers[$compid]['vmprofileid']);
                     $changenow[] = $compid;
                 }
             }
         }
         $msg = '';
         if (count($changenow)) {
             $msg .= "The following computers were placed into the vmhostinuse state ";
             $msg .= "or had their VM Host Profiles updated:<br><br>\n";
             foreach ($changenow as $compid) {
                 $msg .= "<span class=\"ready\">{$computers[$compid]['hostname']}</span><br>\n";
             }
             $msg .= "<br>\n";
             $ret['clearselection'] = 1;
             $ret['refreshcount'] = 5;
         }
         if (count($changenowreload)) {
             $msg .= "The following computers have been scheduled to be immediately reloaded<br>\n";
             $msg .= "and placed into the vmhostinuse state:<br><br>\n";
             foreach ($changenowreload as $compid) {
                 $msg .= "<span class=\"ready\">{$computers[$compid]['hostname']}</span><br>\n";
             }
             $msg .= "<br>\n";
             $ret['clearselection'] = 1;
             $ret['refreshcount'] = 5;
         }
         if (count($changeasap)) {
             $msg .= "The following computers are currently reserved and have been scheduled<br>\n";
             $msg .= "to be reloaded and placed into the vmhostinuse state at the time listed<br>\n";
             $msg .= "for each computers:<br><br>\n";
             $msg .= "<table>\n";
             $msg .= "  <tr>\n";
             $msg .= "    <th>Computer</th>\n";
             $msg .= "    <th>Reload time</th>\n";
             $msg .= "  </tr>\n";
             foreach ($changeasap as $compid) {
                 $msg .= "  <tr>\n";
                 $msg .= "    <td align=center><span class=\"wait\">{$computers[$compid]['hostname']}</span></td>\n";
                 $time = date('n/j/y g:i a', $changetimes[$compid]);
                 $msg .= "    <td align=center>{$time}</td>\n";
                 $msg .= "  </tr>\n";
             }
             $msg .= "</table>\n";
             $msg .= "<br>\n";
         }
         if (count($fails)) {
             $msg .= "Problems were encountered while trying to move the following computers<br>\n";
             $msg .= "to the vmhostinuse state:<br><br>\n";
             foreach ($fails as $compid) {
                 $msg .= "<span class=\"rederrormsg\">{$computers[$compid]['hostname']}</span><br>\n";
             }
             $msg .= "<br>\n";
         }
         if (count($vmnotallowed)) {
             $msg .= "The following computers are VMs which cannot be placed into the ";
             $msg .= "vmhostinuse state:<br><br>\n";
             foreach ($vmnotallowed as $compid) {
                 $msg .= "<span class=\"rederrormsg\">{$computers[$compid]['hostname']}</span><br>\n";
             }
             $msg .= "<br>\n";
         }
         if (count($noaction)) {
             $msg .= "The following computers were already in the vmhostinuse state:<br><br>\n";
             foreach ($noaction as $compid) {
                 $msg .= "{$computers[$compid]['hostname']}<br>\n";
             }
             $msg .= "<br>\n";
         }
     }
     # clear user resource cache for this type
     $key = getKey(array(array($this->restype . "Admin"), array("administer"), 0, 1, 0, 0));
     unset($_SESSION['userresources'][$key]);
     $key = getKey(array(array($this->restype . "Admin"), array("administer"), 0, 0, 0, 0));
     unset($_SESSION['userresources'][$key]);
     $ret['msg'] = $msg;
     sendJSON($ret);
 }
Beispiel #7
0
function findManagementNode($compid, $start, $nowfuture)
{
    global $HTMLheader;
    $allmgmtnodes = array_keys(getManagementNodes($nowfuture));
    $mapped = getMappedResources($compid, "computer", "managementnode");
    $usablemgmtnodes = array_intersect($allmgmtnodes, $mapped);
    $mgmtnodecnt = array();
    foreach ($usablemgmtnodes as $id) {
        $mgmtnodecnt[$id] = 0;
    }
    if (!count($usablemgmtnodes)) {
        return 0;
    }
    $inlist = implode(',', $usablemgmtnodes);
    $mystart = datetimeToUnix($start);
    $start = unixToDatetime($mystart - 1800);
    $end = unixToDatetime($mystart + 1800);
    $query = "SELECT DISTINCT COUNT(rs.managementnodeid) AS count, " . "rs.managementnodeid AS mnid " . "FROM reservation rs, " . "request rq " . "WHERE rs.managementnodeid IN ({$inlist}) AND " . "rq.start > \"{$start}\" AND " . "rq.start < \"{$end}\" " . "GROUP BY rs.managementnodeid " . "ORDER BY count";
    $qh = doQuery($query, 101);
    while ($row = mysql_fetch_assoc($qh)) {
        $mgmtnodecnt[$row["mnid"]] = $row["count"];
    }
    uasort($mgmtnodecnt, "sortKeepIndex");
    $keys = array_keys($mgmtnodecnt);
    return array_shift($keys);
}
Beispiel #8
0
function checkAvailableNetworks($ip)
{
    $ip = ip2long($ip);
    $mnids = array();
    $mns = getManagementNodes();
    foreach ($mns as $mn) {
        foreach ($mn['availablenetworks'] as $net) {
            if ($net == '') {
                continue;
            }
            list($net, $netmask) = explode('/', $net);
            $net = ip2long($net);
            $mask = pow(2, 32 - $netmask) - 1;
            $mask = ~$mask;
            if (($ip & $mask) == ($net & $mask)) {
                $mnids[$mn['id']] = 1;
            }
        }
    }
    return array_keys($mnids);
}
Beispiel #9
0
function XMLRPCblockAllocation($imageid, $start, $end, $requestcount, $usergroupid, $ignoreprivileges = 0)
{
    global $user, $xmlrpcBlockAPIUsers;
    if (!in_array($user['id'], $xmlrpcBlockAPIUsers)) {
        return array('status' => 'error', 'errorcode' => 34, 'errormsg' => 'access denied for managing block allocations');
    }
    $ownerid = getUserlistID('vclreload@Local');
    $name = "API:{$start}";
    $managementnodes = getManagementNodes('future');
    if (empty($managementnodes)) {
        return array('status' => 'error', 'errorcode' => 12, 'errormsg' => 'could not allocate a management node to handle block allocation');
    }
    $mnid = array_rand($managementnodes);
    $query = "INSERT INTO blockRequest " . "(name, " . "imageid, " . "numMachines, " . "groupid, " . "repeating, " . "ownerid, " . "admingroupid, " . "managementnodeid, " . "expireTime) " . "VALUES " . "('{$name}', " . "{$imageid}, " . "{$requestcount}, " . "{$usergroupid}, " . "'list', " . "{$ownerid}, " . "0, " . "{$mnid}, " . "'{$end}')";
    doQuery($query, 101);
    $brid = dbLastInsertID();
    $query = "INSERT INTO blockTimes " . "(blockRequestid, " . "start, " . "end) " . "VALUES " . "({$brid}, " . "'{$start}', " . "'{$end}')";
    doQuery($query, 101);
    $btid = dbLastInsertID();
    $return = XMLRPCprocessBlockTime($btid, $ignoreprivileges);
    $return['blockTimesid'] = $btid;
    return $return;
}
Beispiel #10
0
function XMLRPCblockAllocation($imageid, $start, $end, $numMachines, $usergroupid, $ignoreprivileges = 0)
{
    global $user, $xmlrpcBlockAPIUsers;
    if (!in_array($user['id'], $xmlrpcBlockAPIUsers)) {
        return array('status' => 'error', 'errorcode' => 34, 'errormsg' => 'access denied for managing block allocations');
    }
    # valid $imageid
    $resources = getUserResources(array("imageAdmin", "imageCheckOut"));
    $resources["image"] = removeNoCheckout($resources["image"]);
    if (!array_key_exists($imageid, $resources['image'])) {
        return array('status' => 'error', 'errorcode' => 3, 'errormsg' => "access denied to {$imageid}");
    }
    # validate $start and $end
    $dtreg = '([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})';
    $startts = datetimeToUnix($start);
    $endts = datetimeToUnix($end);
    $maxend = datetimeToUnix("2038-01-01 00:00:00");
    if (!preg_match("/^{$dtreg}\$/", $start) || $startts < 0 || $startts > $maxend) {
        return array('status' => 'error', 'errorcode' => 4, 'errormsg' => "received invalid input for start");
    }
    if (!preg_match("/^{$dtreg}\$/", $end) || $endts < 0 || $endts > $maxend) {
        return array('status' => 'error', 'errorcode' => 36, 'errormsg' => "received invalid input for end");
    }
    # validate $numMachines
    if (!is_numeric($numMachines) || $numMachines < MIN_BLOCK_MACHINES || $numMachines > MAX_BLOCK_MACHINES) {
        return array('status' => 'error', 'errorcode' => 64, 'errormsg' => 'The submitted number of seats must be between ' . MIN_BLOCK_MACHINES . ' and ' . MAX_BLOCK_MACHINES . '.');
    }
    # validate $usergroupid
    $groups = getUserGroups();
    if (!array_key_exists($usergroupid, $groups)) {
        return array('status' => 'error', 'errorcode' => 67, 'errormsg' => 'Submitted user group does not exist');
    }
    # validate ignoreprivileges
    if (!is_numeric($ignoreprivileges) || $ignoreprivileges < 0 || $ignoreprivileges > 1) {
        return array('status' => 'error', 'errorcode' => 86, 'errormsg' => 'ignoreprivileges must be 0 or 1');
    }
    $ownerid = getUserlistID('vclreload@Local');
    $name = "API:{$start}";
    $managementnodes = getManagementNodes('future');
    if (empty($managementnodes)) {
        return array('status' => 'error', 'errorcode' => 12, 'errormsg' => 'could not allocate a management node to handle block allocation');
    }
    $mnid = array_rand($managementnodes);
    $query = "INSERT INTO blockRequest " . "(name, " . "imageid, " . "numMachines, " . "groupid, " . "repeating, " . "ownerid, " . "managementnodeid, " . "expireTime, " . "status) " . "VALUES " . "('{$name}', " . "{$imageid}, " . "{$numMachines}, " . "{$usergroupid}, " . "'list', " . "{$ownerid}, " . "{$mnid}, " . "'{$end}', " . "'accepted')";
    doQuery($query, 101);
    $brid = dbLastInsertID();
    $query = "INSERT INTO blockTimes " . "(blockRequestid, " . "start, " . "end) " . "VALUES " . "({$brid}, " . "'{$start}', " . "'{$end}')";
    doQuery($query, 101);
    $btid = dbLastInsertID();
    $query = "INSERT INTO blockWebDate " . "(blockRequestid, " . "start, " . "end, " . "days) " . "VALUES " . "({$brid}, " . "'{$start}', " . "'{$end}', " . "0)";
    doQuery($query);
    $sh = date('g', $startts);
    $smi = date('i', $startts);
    $sme = date('a', $startts);
    $eh = date('g', $startts);
    $emi = date('i', $startts);
    $eme = date('a', $startts);
    $query = "INSERT INTO blockWebTime " . "(blockRequestid, " . "starthour, " . "startminute, " . "startmeridian, " . "endhour, " . "endminute, " . "endmeridian, " . "`order`) " . "VALUES " . "({$brid}, " . "{$sh}," . "{$smi}," . "'{$sme}'," . "{$eh}," . "{$emi}," . "'{$eme}'," . "0)";
    doQuery($query);
    $return = XMLRPCprocessBlockTime($btid, $ignoreprivileges);
    $return['blockTimesid'] = $btid;
    return $return;
}
Beispiel #11
0
 function getData($args)
 {
     return getManagementNodes($args['alive'], $args['includedeleted'], $args['rscid']);
 }