Example #1
0
function addToStatGraphCache($type, $addcache, $affilid, $provid)
{
    $nosave = time() - SECINDAY;
    $values = array();
    if ($affilid == 0) {
        $affilid = 'NULL';
    }
    if ($provid == 0) {
        $provid = 'NULL';
    }
    foreach ($addcache as $date => $value) {
        $startts = datetimeToUnix($date);
        if ($startts < $nosave) {
            $tmp = explode(' ', $date);
            $statdate = $tmp[0];
            $values[] = "('{$type}', '{$statdate}', {$affilid}, {$value}, {$provid})";
        }
    }
    if (count($values)) {
        $insval = implode(',', $values);
        $query = "INSERT IGNORE INTO statgraphcache " . "(graphtype, statdate, affiliationid, value, provisioningid) " . "VALUES {$insval}";
        doQuery($query, 101);
    }
}
Example #2
0
function processRequestInput()
{
    global $user;
    $baseaccess = getContinuationVar('baseaccess', 0);
    $imagingaccess = getContinuationVar('imagingaccess', 0);
    $serveraccess = getContinuationVar('serveraccess', 0);
    $openend = getContinuationVar('openend', 0);
    $nousercheck = getContinuationVar('nousercheck', 0);
    $return['imaging'] = getContinuationVar('imaging', 0);
    $maxinitial = getContinuationVar('maxinitial', 0);
    $noimaging = getContinuationVar('noimaging', array());
    $return = array('err' => 0);
    # type
    $return['type'] = processInputVar('type', ARG_STRING);
    if (!preg_match('/^basic|imaging|server$/', $return['type'])) {
        $return['err'] = 1;
        $return['errmsg'] = i('Invalid data submitted');
        return $return;
    }
    if ($return['type'] == 'basic' && !$baseaccess || $return['type'] == 'imaging' && !$imagingaccess || $return['type'] == 'server' && !$serveraccess) {
        $return['err'] = 1;
        $return['errmsg'] = i('No access to submitted reservation type');
        return $return;
    }
    # ending
    $return['ending'] = processInputVar('ending', ARG_STRING);
    if (!preg_match('/^indefinite|endat|duration$/', $return['ending'])) {
        $return['err'] = 1;
        $return['errmsg'] = i('Invalid data submitted');
        return $return;
    }
    if ($return['ending'] == 'duration' && !$baseaccess || $return['ending'] == 'indefinite' && !$serveraccess || $return['ending'] == 'endat' && !$openend && !$serveraccess) {
        $return['err'] = 1;
        $return['errmsg'] = i('No access to submitted end type');
        return $return;
    }
    # imageid
    $return['imageid'] = processInputVar('imageid', ARG_NUMERIC);
    $resources = getUserResources(array("imageAdmin", "imageCheckOut"));
    $withnocheckout = $resources['image'];
    $images = removeNoCheckout($resources["image"]);
    $extraimages = getServerProfileImages($user['id']);
    if (!array_key_exists($return['imageid'], $images) && ($return['type'] != 'server' || !array_key_exists($return['imageid'], $extraimages)) && ($return['type'] != 'imaging' || !array_key_exists($return['imageid'], $withnocheckout)) || $return['type'] == 'imaging' && array_key_exists($return['imageid'], $noimaging)) {
        $return['err'] = 1;
        $return['errmsg'] = i('No access to submitted environment');
        return $return;
    }
    # nousercheck
    $return['nousercheck'] = processInputVar('nousercheck', ARG_NUMERIC);
    if (!$nousercheck || $return['nousercheck'] != 1) {
        $return['nousercheck'] = 0;
    }
    # revisionid
    $revids = processInputVar("revisionid", ARG_STRING);
    $revids = explode(':', $revids);
    $images = getImages(0, $return['imageid']);
    $return['revisionids'] = array();
    if (array_key_exists('subimages', $images[$return['imageid']])) {
        $subimages = $images[$return['imageid']]['subimages'];
        array_unshift($subimages, $return['imageid']);
        foreach ($subimages as $key => $imgid) {
            $revisions = getImageRevisions($imgid);
            if (!array_key_exists($key, $revids) || !is_numeric($revids[$key]) || !array_key_exists($revids[$key], $revisions)) {
                $revid = getProductionRevisionid($imgid);
            } else {
                $revid = $revids[$key];
            }
            if (!array_key_exists($imgid, $return['revisionids'])) {
                $return['revisionids'][$imgid] = array();
            }
            $return['revisionids'][$imgid][] = $revid;
        }
    } elseif ($revids[0] != '' && is_numeric($revids[0])) {
        $return['revisionids'][$return['imageid']][] = $revids[0];
    } else {
        $return['revisionids'][$return['imageid']][] = getProductionRevisionid($return['imageid']);
    }
    # duration
    if ($return['ending'] == 'duration') {
        $return['duration'] = processInputVar('duration', ARG_NUMERIC, 0);
        if ($return['duration'] > $maxinitial) {
            $return['duration'] = $maxinitial;
        }
    }
    # start/end
    $return['start'] = processInputVar('start', ARG_NUMERIC);
    $return['end'] = processInputVar('end', ARG_NUMERIC, 0);
    $now = time();
    if ($return['start'] == 0) {
        $start = $now;
    } else {
        $start = $return['start'];
    }
    if ($return['ending'] == 'endat') {
        $end = $return['end'];
    }
    if ($return['ending'] == 'indefinite') {
        $end = datetimeToUnix('2038-01-01 00:00:00');
    } elseif ($return['ending'] == 'duration') {
        $end = $start + $return['duration'] * 60;
    }
    if ($start < $now) {
        $return['err'] = 1;
        $return['errmsg'] = i('The submitted start time is in the past.');
        return $return;
    }
    if ($start + 900 > $end) {
        $return['err'] = 1;
        $return['errmsg'] = i('The end time must be at least 15 minutes later than the start time.');
        return $return;
    }
    $return['ipaddr'] = '';
    $return['macaddr'] = '';
    # server specific input
    if ($return['type'] == 'server') {
        # name
        $return['name'] = processInputVar('name', ARG_STRING);
        if (!preg_match('/^([-a-zA-Z0-9_\\. ]){0,255}$/', $return['name'])) {
            $return['err'] = 1;
            $return['errmsg'] = i('The reservation name can only contain letters, numbers, spaces, dashes(-), underscores(_), and periods(.) and can be up to 255 characters long');
            return $return;
        }
        # ipaddr
        $return['ipaddr'] = processInputVar('ipaddr', ARG_STRING);
        if ($return['ipaddr'] != '') {
            # validate fixed IP address
            if (!validateIPv4addr($return['ipaddr'])) {
                $return['err'] = 1;
                $return['errmsg'] = i('Invalid IP address. Must be w.x.y.z with each of w, x, y, and z being between 1 and 255 (inclusive)');
                return $return;
            }
            # validate netmask
            $return['netmask'] = processInputVar('netmask', ARG_STRING);
            $bnetmask = ip2long($return['netmask']);
            if (!preg_match('/^[1]+0[^1]+$/', sprintf('%032b', $bnetmask))) {
                $return['err'] = 1;
                $return['errmsg'] = i('Invalid netmask specified');
                return $return;
            }
            # validate router
            $return['router'] = processInputVar('router', ARG_STRING);
            if (!validateIPv4addr($return['router'])) {
                $return['err'] = 1;
                $return['errmsg'] = i('Invalid router address. Must be w.x.y.z with each of w, x, y, and z being between 1 and 255 (inclusive)');
                return $return;
            }
            $return['network'] = ip2long($return['ipaddr']) & $bnetmask;
            if ($return['network'] != (ip2long($return['router']) & $bnetmask)) {
                $return['err'] = 1;
                $return['errmsg'] = i('IP address and router are not on the same subnet based on the specified netmask.');
                return $return;
            }
            # validate dns server(s)
            $dns = processInputVar('dns', ARG_STRING);
            $tmp = explode(',', $dns);
            $cnt = 0;
            $return['dnsArr'] = array();
            foreach ($tmp as $dnsaddr) {
                if ($cnt && $dnsaddr == '') {
                    continue;
                }
                if ($cnt == 3) {
                    $return['err'] = 1;
                    $return['errmsg'] = i('Too many DNS servers specified - up to 3 are allowed.');
                    return $return;
                }
                if (!validateIPv4addr($dnsaddr)) {
                    $return['err'] = 1;
                    $return['errmsg'] = i('Invalid DNS server specified.');
                    return $return;
                }
                $return['dnsArr'][] = $dnsaddr;
                $cnt++;
            }
            # check that a management node can handle the network
            $mappedmns = getMnsFromImage($return['imageid']);
            $mnnets = checkAvailableNetworks($return['ipaddr']);
            $intersect = array_intersect($mappedmns, $mnnets);
            if (empty($intersect)) {
                $return['err'] = 1;
                $return['errmsg'] = i('There are no management nodes that can deploy the selected image with the specified IP address.');
                return $return;
            }
        }
        # macaddr
        $return['macaddr'] = processInputVar('macaddr', ARG_STRING);
        if ($return['macaddr'] != '' && !preg_match('/^(([A-Fa-f0-9]){2}:){5}([A-Fa-f0-9]){2}$/', $return['macaddr'])) {
            $return['err'] = 1;
            $return['errmsg'] = i('Invalid MAC address. Must be XX:XX:XX:XX:XX:XX with each pair of XX being from 00 to FF (inclusive)');
            return $return;
        }
        # profileid
        $return['profileid'] = processInputVar('profileid', ARG_NUMERIC, 0);
        $resources = getUserResources(array("serverCheckOut", "serverProfileAdmin"), array("available", "administer"));
        if (!array_key_exists($return['profileid'], $resources['serverprofile'])) {
            $return['profileid'] = 0;
        } elseif ($return['profileid'] != 0) {
            $tmp = getServerProfiles($return['profileid']);
            $tmp = $tmp[$return['profileid']];
            if ($tmp['imageid'] != $return['imageid'] && ($tmp['fixedIP'] != $return['ipaddr'] && $tmp['fixedMAC'] != $return['macaddr'] || $tmp['fixedIP'] == $return['ipaddr'] && $return['ipaddr'] == '' && $tmp['fixedMAC'] == $return['macaddr'] && $return['macaddr'] == '')) {
                $return['profileid'] = 0;
            }
        }
        # admingroupid
        $usergroups = getUserGroups();
        $return['admingroupid'] = processInputVar('admingroupid', ARG_NUMERIC);
        if ($return['admingroupid'] != 0 && !array_key_exists($return['admingroupid'], $usergroups)) {
            $return['err'] = 1;
            $return['errmsg'] = i('You do not have access to use the specified admin user group.');
            return $return;
        }
        # logingroupid
        $return['logingroupid'] = processInputVar('logingroupid', ARG_NUMERIC);
        if ($return['logingroupid'] != 0 && !array_key_exists($return['logingroupid'], $usergroups)) {
            $return['err'] = 1;
            $return['errmsg'] = i('You do not have access to use the specified access user group.');
            return $return;
        }
        # monitored
        $return['monitored'] = processInputVar('monitored', ARG_NUMERIC, 0);
        if ($return['monitored'] != 0 && $return['monitored'] != 1) {
            $return['monitored'] = 0;
        }
        # configs
        # TODO configs
        /*$tmp = getUserResources(array("configAdmin"));
        		$userconfigs = $tmp['config'];
        		$initconfigs = getMappedConfigs($return['imageid']);
        		if(array_key_exists('configdata', $_POST)) {
        			if(get_magic_quotes_gpc())
        				$_POST['configdata'] = stripslashes($_POST['configdata']);
        			$configdata = json_decode($_POST['configdata']);
        		}
        		if(array_key_exists('configdata', $_POST) &&
        			isset($configdata->configs))
        			$configs = $configdata->configs;
        		else
        			$configs = (object)array();
        		$return['configs'] = array();
        		foreach($initconfigs as $id => $config) {
        			if(isset($configs->{$id}) &&
        				isset($configs->{$id}->applied) &&
        			   $configs->{$config['id']}->applied != 'true' &&
        				$configs->{$config['id']}->applied != 'false')
        				unset($configs->{$config['id']});
        			if($config['optional'] &&
        			   (! isset($configs->{$id}) ||
        			   ! $configs->{$id}->applied))
        				continue;
        			$return['configs'][$id] = array('configid' => $config['configid'],
        			                                'configmapid' => $config['configmapid'],
        			                                'imageid' => $config['subimageid']);
        			if(isset($configs->{$id}))
        				unset($configs->{$id});
        		}
        		$rescfgmapids = array();
        		foreach($configs as $id => $config) {
        			if(! array_key_exists($config->configid, $userconfigs))
        				continue;
        			$return['configs'][$id] = array('configid' => $config->configid,
        			                                'configstageid' => $config->configstageid,
        			                                'imageid' => $config->imageid);
        			$tmp = explode('/', $id);
        			$rescfgmapids[$tmp[1]] = 1;
        		}
        
        		# configvars
        		$tmp = array_splice($initconfigs, 0);
        		$initconfigvars = getImageConfigVariables($tmp);
        		if(array_key_exists('configdata', $_POST) &&
        			isset($configdata->configvars))
        			$configvars = $configdata->configvars;
        		else
        			$configvars = (object)array();
        		#print "/*";
        		#printArray($initconfigvars);
        		#printArray($configvars);
        		#print "*" . "/";
        		$return['configvars'] = array();
        		foreach($initconfigvars as $id => $configvar) {
        			$tmp = explode('/', $id);
        			$cfgid = "{$tmp[0]}/{$tmp[1]}";
        			$varid = $tmp[2];
        			if($configvar['ask'] == 0 ||
        			   ! isset($configvars->{$id}) ||
        			   ! isset($configvars->{$id}->value)) {
        				$return['configvars'][$cfgid][$varid] =
        				         array('value' => $configvar['defaultvalue']);
        			}
        			else {
        				switch($configvar['datatype']) {
        					case 'bool':
        					case 'int':
        					case 'float':
        						$value = processInputData($configvars->{$id}->value, ARG_NUMERIC);
        						break;
        					default:
        						$value = processInputData($configvars->{$id}->value, ARG_STRING);
        						break;
        				}
        				$return['configvars'][$cfgid][$varid] = array('value' => $value);
        			}
        			if(isset($configvars->{$id}))
        				unset($configvars->{$id});
        		}*/
        /*print "/*";
        		printArray($rescfgmapids);
        		foreach($configvars as $id => $var) {
        			$cfgid = explode('/', $id);
        			print "cfgid: {$cfgid[1]}\n";
        			if(! array_key_exists($cfgid[1], $rescfgmapids))
        				continue;
        			// TODO validate based on var type
        			$value = processInputData($configvars->{$id}->value, ARG_STRING);
        			$return['configvars']["{$cfgid[0]}/{$cfgid[1]}"][$cfgid[2]] = array('value' => $value);
        		}
        		printArray($configvars);*/
        #print "*/";
    }
    return $return;
}
Example #3
0
 function AJshowReservationHistory()
 {
     $compids = $this->validateCompIDs();
     if (array_key_exists('error', $compids)) {
         $ret = array('status' => 'error', 'errormsg' => $compids['msg']);
         sendJSON($ret);
         return;
     }
     if (count($compids) == 0) {
         $ret = array('status' => 'noaction');
         sendJSON($ret);
         return;
     }
     $complist = implode(',', $compids);
     $query = "SELECT UNIX_TIMESTAMP(l.start) AS start, " . "UNIX_TIMESTAMP(l.finalend) AS end, " . "i.prettyname AS image, " . "ir.revision, " . "c.hostname AS hostname, " . "mn.hostname AS managementnode, " . "l.ending, " . "CONCAT(u.unityid, '@', a.name) AS username " . "FROM computer c " . "LEFT JOIN sublog s ON (c.id = s.computerid) " . "LEFT JOIN image i ON (s.imageid = i.id) " . "LEFT JOIN imagerevision ir ON (s.imagerevisionid = ir.id) " . "LEFT JOIN managementnode mn ON (s.managementnodeid = mn.id) " . "LEFT JOIN log l ON (s.logid = l.id) " . "LEFT JOIN user u ON (l.userid = u.id) " . "LEFT JOIN affiliation a ON (u.affiliationid = a.id) " . "WHERE c.id IN ({$complist}) " . "ORDER BY c.hostname, " . "l.start DESC";
     $qh = doQuery($query);
     $data = array();
     while ($row = mysql_fetch_assoc($qh)) {
         if (!is_numeric($row['end'])) {
             continue;
         }
         $msg = "<strong>{$row['hostname']}</strong><br>";
         if ($row['start'] == '') {
             $msg .= "(No reservations)<br><hr>";
             $data[] = array('name' => $row['hostname'], 'msg' => $msg);
             continue;
         }
         $msg .= "User: {$row['username']}<br>";
         $msg .= "Image: {$row['image']}<br>";
         $msg .= "Revision: {$row['revision']}<br>";
         $msg .= "Start: " . prettyDatetime($row['start'], 1) . "<br>";
         if ($row['end'] == datetimeToUnix('2038-01-01 00:00:00')) {
             $msg .= "End: (indefinite)<br>";
         } else {
             $msg .= "End: " . prettyDatetime($row['end'], 1) . "<br>";
         }
         $msg .= "Management Node: {$row['managementnode']}<br>";
         $msg .= "Ending: {$row['ending']}<br>";
         $msg .= "<hr>";
         $data[] = array('name' => $row['hostname'], 'msg' => $msg);
     }
     $msg = '';
     foreach ($data as $item) {
         $msg .= $item['msg'];
     }
     $msg = substr($msg, 0, -4);
     $ret = array('status' => 'onestep', 'title' => 'Reservation History', 'actionmsg' => $msg);
     sendJSON($ret);
 }
Example #4
0
function processSiteMaintenanceInput()
{
    $start = processInputVar('start', ARG_NUMERIC);
    $end = processInputVar('end', ARG_NUMERIC);
    $data['hoursahead'] = processInputVar('hoursahead', ARG_NUMERIC);
    $data['allowreservations'] = processInputVar('allowreservations', ARG_NUMERIC);
    $data['reason'] = processInputVar('reason', ARG_STRING);
    $data['usermessage'] = processInputVar('usermessage', ARG_STRING);
    $err = 0;
    $now = time();
    $data['startdt'] = numdatetimeToDatetime($start . '00');
    $data['startts'] = datetimeToUnix($data['startdt']);
    $data['enddt'] = numdatetimeToDatetime($end . '00');
    $data['endts'] = datetimeToUnix($data['enddt']);
    $reg = "/^[-0-9a-zA-Z\\.,\\?:;_@!#\\(\\)\n ]+\$/";
    if (!preg_match($reg, $data['reason'])) {
        $errmsg = "Reason can only contain letters, numbers, spaces,\\nand these characters: . , ? : ; - _ @ ! # ( )";
        $err = 1;
    }
    if (!preg_match($reg, $data['usermessage'])) {
        $errmsg = "User Message can only contain letters, numbers, spaces,\\nand these characters: . , ? : ; - _ @ ! # ( )";
        $err = 1;
    }
    if (!$err && $data['startts'] < $now) {
        $errmsg = 'The start time and date must be later than the current time.';
        $err = 1;
    }
    if (!$err && $data['endts'] <= $data['startts']) {
        $errmsg = 'The end time and date must be later than the start time and date.';
        $err = 1;
    }
    if (!$err && $data['hoursahead'] < 1) {
        $errmsg = 'Inform Hours Ahead must be at least 1.';
        $err = 1;
    }
    if (!$err && $data['hoursahead'] > 65535) {
        $errmsg = 'Inform Hours Ahead must be less than 65536.';
        $err = 1;
    }
    if (!$err && ($data['allowreservations'] != 0 && $data['allowreservations'] != 1)) {
        $data['allowreservations'] = 0;
    }
    if (!$err && !preg_match('/[A-Za-z]{2,}/', $data['usermessage'])) {
        $errmsg = 'Something must be filled in for the User Message.';
        $err = 1;
    }
    if ($err) {
        print "alert('{$errmsg}');";
    }
    $data['err'] = $err;
    return $data;
}
Example #5
0
 function getRevisionHTML($imageid)
 {
     $revisions = getImageRevisions($imageid);
     $rt = '';
     $rt .= "<h3>" . i("Revisions of this Image") . "</h3>\n";
     $rt .= "<table summary=\"\"><tr><td>\n";
     if (count($revisions) > 1 && isImageBlockTimeActive($imageid)) {
         $rt .= "<font color=\"red\">";
         $warn = i("WARNING: This image is part of an active block allocation. Changing the production revision of the image at this time will result in new reservations under the block allocation to have full reload times instead of a &lt; 1 minutes wait.");
         $rt .= preg_replace("/(.{1,100}([ \n]|\$))/", '\\1<br>', $warn);
         $rt .= "</font><br>\n";
     }
     $rt .= "<table summary=\"\" id=\"revisiontable\">\n";
     $rt .= "  <tr>\n";
     $rt .= "    <td></td>\n";
     $rt .= "    <th>" . i("Revision") . "</th>\n";
     $rt .= "    <th>" . i("Creator") . "</th>\n";
     $rt .= "    <th>" . i("Created") . "</th>\n";
     $rt .= "    <th nowrap>" . i("In Production") . "</th>\n";
     $rt .= "    <th>" . i("Comments (click to edit)") . "</th>\n";
     $rt .= "  </tr>\n";
     foreach ($revisions as $rev) {
         if ($rev['deleted'] == 1) {
             continue;
         }
         $rt .= "  <tr>\n";
         $rt .= "    <td><INPUT type=checkbox\n";
         $rt .= "              id=chkrev{$rev['id']}\n";
         $rt .= "              name=chkrev[{$rev['id']}]\n";
         $rt .= "              value=1></td>\n";
         $rt .= "    <td align=center>{$rev['revision']}</td>\n";
         $rt .= "    <td>{$rev['creator']}</td>\n";
         $created = date('g:ia n/j/Y', datetimeToUnix($rev['datecreated']));
         $rt .= "    <td>{$created}</td>\n";
         $cdata = $this->basecdata;
         $cdata['imageid'] = $imageid;
         $cdata['revisionid'] = $rev['id'];
         $cont = addContinuationsEntry('AJupdateRevisionProduction', $cdata);
         $rt .= "    <td align=center><INPUT type=radio\n";
         $rt .= "           name=production\n";
         $rt .= "           value={$rev['id']}\n";
         $rt .= "           id=radrev{$rev['id']}\n";
         $rt .= "           onclick=\"updateRevisionProduction('{$cont}');\"\n";
         if ($rev['production']) {
             $rt .= "           checked\n";
         }
         $rt .= "           ></td>\n";
         $cont = addContinuationsEntry('AJupdateRevisionComments', $cdata);
         $rt .= "    <td width=200px><span id=comments{$rev['id']} \n";
         $rt .= "              dojoType=\"dijit.InlineEditBox\"\n";
         $rt .= "              editor=\"dijit.form.Textarea\"\n";
         $rt .= "              onChange=\"updateRevisionComments('comments{$rev['id']}', '{$cont}');\"\n";
         $rt .= "              noValueIndicator=\"(empty)\">\n";
         $rt .= "        {$rev['comments']}</span></td>\n";
         $rt .= "  </tr>\n";
     }
     $rt .= "</table>\n";
     $rt .= "<div align=left>\n";
     $keys = array_keys($revisions);
     $cdata = $this->basecdata;
     $cdata['revids'] = $keys;
     $cdata['imageid'] = $imageid;
     $cont = addContinuationsEntry('AJdeleteRevisions', $cdata);
     $ids = implode(',', $keys);
     $rt .= "<button onclick=\"deleteRevisions('{$cont}', '{$ids}'); return false;\">";
     $rt .= i("Delete selected revisions") . "</button>\n";
     $rt .= "</div>\n";
     $rt .= "</td></tr></table>\n";
     return $rt;
 }
Example #6
0
function statXaxisConBladeUserCallback($val)
{
    global $xaxislabels;
    if (array_key_exists((int) $val, $xaxislabels)) {
        return date('n/d/Y', datetimeToUnix($xaxislabels[$val] . " 00:00:00")) . " ";
    } else {
        return $val;
    }
}
Example #7
0
function printHTMLHeader()
{
    global $mode, $user, $authed, $oldmode, $viewmode, $HTMLheader;
    global $printedHTMLheader, $docreaders, $skin, $noHTMLwrappers, $actions;
    if ($printedHTMLheader) {
        return;
    }
    $refresh = 0;
    if ($authed && $mode == "viewRequests") {
        $requests = getUserRequests("all", $user["id"]);
        if ($count = count($requests)) {
            $now = time() + 15 * 60;
            for ($i = 0; $i < $count; $i++) {
                if (datetimeToUnix($requests[$i]["start"]) < $now && ($requests[$i]["currstateid"] == 13 || $requests[$i]["currstateid"] == 14 && $requests[$i]["laststateid"] == 13 || $requests[$i]["currstateid"] == 3)) {
                    $refresh = 1;
                }
            }
        }
    }
    if ($mode != 'selectauth' && $mode != 'submitLogin') {
        $HTMLheader .= getHeader($refresh);
    }
    if (!in_array($mode, $noHTMLwrappers)) {
        print $HTMLheader;
        $printedHTMLheader = 1;
    }
}
Example #8
0
function submitCompStateChange()
{
    global $user;
    print "<H2>Change State of Computers</H2>\n";
    $data = getContinuationVar();
    $computers = getComputers(1);
    # switching to available
    if ($data['stateid'] == 2) {
        $compids = implode(',', $data['computerids']);
        $query = "UPDATE computer " . "SET stateid = 2, " . "notes = '' " . "WHERE id IN ({$compids})";
        doQuery($query, 101);
        print "The following computers were changed to the available state:\n";
        print "<TABLE>\n";
        foreach ($data['computerids'] as $compid) {
            print "  <TR>\n";
            print "    <TD>{$computers[$compid]['hostname']}</TD>\n";
            print "  </TR>\n";
        }
        print "</TABLE>\n";
    } elseif ($data['stateid'] == 10) {
        $data['notes'] = processInputVar('notes', ARG_STRING);
        if (get_magic_quotes_gpc()) {
            $data['notes'] = stripslashes($data['notes']);
        }
        $data['notes'] = mysql_escape_string($data['notes']);
        $data["notes"] = $user["unityid"] . " " . unixToDatetime(time()) . "@" . $data["notes"];
        $vclreloadid = getUserlistID('vclreload@Local');
        // get semaphore lock
        if (!semLock()) {
            abort(3);
        }
        $noaction = array();
        $changenow = array();
        $changeasap = array();
        $changetimes = array();
        foreach ($data['computerids'] as $compid) {
            if ($computers[$compid]['state'] == 'maintenance') {
                array_push($noaction, $compid);
            } else {
                array_push($changeasap, $compid);
            }
        }
        $passes = array();
        $fails = array();
        foreach ($changeasap as $compid) {
            # TODO what about blockComputers?
            # try to move future reservations off of computer
            moveReservationsOffComputer($compid);
            # get end time of last reservation
            $query = "SELECT rq.end " . "FROM request rq, " . "reservation rs " . "WHERE rs.requestid = rq.id AND " . "rs.computerid = {$compid} AND " . "rq.stateid NOT IN (1,5,12) " . "ORDER BY end DESC " . "LIMIT 1";
            $qh = doQuery($query, 101);
            # create a really long reservation starting at that time in state tomaintenance
            if ($row = mysql_fetch_assoc($qh)) {
                $start = $row['end'];
                $changetimes[$compid] = $start;
                $end = datetimeToUnix($start) + SECINWEEK;
                // hopefully keep future reservations off of it
                $end = unixToDatetime($end);
                if (simpleAddRequest($compid, 4, 3, $start, $end, 18, $vclreloadid)) {
                    $passes[] = $compid;
                } else {
                    $fails[] = $compid;
                }
            } else {
                $query = "UPDATE computer " . "SET stateid = 10, " . "notes = '{$data['notes']}' " . "WHERE id = {$compid}";
                doQuery($query, 101);
                unset_by_val($compid, $changeasap);
                array_push($changenow, $compid);
            }
        }
        // release semaphore lock
        semUnlock();
        if (count($noaction) || count($changeasap)) {
            $comparr = array_merge($noaction, $changeasap);
            $compids = implode(',', $comparr);
            $query = "UPDATE computer " . "SET notes = '{$data['notes']}' " . "WHERE id IN ({$compids})";
            doQuery($query, 101);
        }
        if (count($changenow)) {
            print "The following computers were immediately placed into the ";
            print "maintenance state:\n";
            print "<TABLE>\n";
            foreach ($changenow as $compid) {
                print "  <TR>\n";
                print "    <TD><font color=\"#008000\">{$computers[$compid]['hostname']}</font></TD>\n";
                print "  </TR>\n";
            }
            print "</TABLE>\n";
            print "<br>\n";
        }
        if (count($passes)) {
            print "The following computers currently have reservations on them ";
            print "and will be placed in the maintenance state at the time listed ";
            print "for each computer:\n";
            print "<TABLE>\n";
            print "  <TR>\n";
            print "    <TH>Computer</TH>\n";
            print "    <TH>Maintenance time</TH>\n";
            print "  </TR>\n";
            foreach ($passes as $compid) {
                print "  <TR>\n";
                print "    <TD align=center><font color=\"ff8c00\">{$computers[$compid]['hostname']}</font></TD>\n";
                $time = date('n/j/y g:i a', datetimeToUnix($changetimes[$compid]));
                print "    <TD align=center>{$time}</TD>\n";
                print "  </TR>\n";
            }
            print "</TABLE>\n";
            print "<br>\n";
        }
        if (count($fails)) {
            print "The following computers currently have reservations on them ";
            print "but no functional management node was found for them. Nothing ";
            print "be done with them at this time:\n";
            print "<TABLE>\n";
            print "  <TR>\n";
            print "    <TH>Computer</TH>\n";
            print "  </TR>\n";
            foreach ($passes as $compid) {
                print "  <TR>\n";
                print "    <TD align=center><font color=\"ff0000\">{$computers[$compid]['hostname']}</font></TD>\n";
                print "  </TR>\n";
            }
            print "</TABLE>\n";
            print "<br>\n";
        }
        if (count($noaction)) {
            print "The following computers were already in the maintenance ";
            print "state and had their notes on being in the maintenance state ";
            print "updated:\n";
            print "<TABLE>\n";
            foreach ($noaction as $compid) {
                print "  <TR>\n";
                print "    <TD>{$computers[$compid]['hostname']}</TD>\n";
                print "  </TR>\n";
            }
            print "</TABLE>\n";
            print "<br>\n";
        }
    } elseif ($data['stateid'] == 20) {
        $profileid = processInputVar('profileid', ARG_NUMERIC);
        if (!array_key_exists($profileid, $data['profiles'])) {
            $keys = array_keys($data['profiles']);
            $profileid = $keys[0];
        }
        $noaction = array();
        $changenow = array();
        $changeasap = array();
        $changetimes = array();
        foreach ($data['computerids'] as $compid) {
            if ($computers[$compid]['state'] == 'vmhostinuse') {
                array_push($noaction, $compid);
            } else {
                array_push($changeasap, $compid);
            }
        }
        if (!semLock()) {
            abort(3);
        }
        foreach ($changeasap as $compid) {
            # TODO what about blockComputers?
            moveReservationsOffComputer($compid);
            # get end time of last reservation
            $query = "SELECT rq.end " . "FROM request rq, " . "reservation rs " . "WHERE rs.requestid = rq.id AND " . "rs.computerid = {$compid} AND " . "rq.stateid NOT IN (1,5,12) " . "ORDER BY end DESC " . "LIMIT 1";
            $qh = doQuery($query, 101);
            if ($row = mysql_fetch_assoc($qh)) {
                // if there is a reservation, leave in $changeasap so we can
                #   notify that we can't change this one
            } else {
                # create a reload reservation to load machine with image
                #   corresponding to selected vm profile
                $start = getReloadStartTime();
                $end = $start + SECINYEAR;
                # don't want anyone making a future reservation for this machine
                $start = unixToDatetime($start);
                $end = unixToDatetime($end);
                $imagerevisionid = getProductionRevisionid($data['profiles'][$profileid]['imageid']);
                $vclreloadid = getUserlistID('vclreload@Local');
                simpleAddRequest($compid, $data['profiles'][$profileid]['imageid'], $imagerevisionid, $start, $end, 21, $vclreloadid);
                unset_by_val($compid, $changeasap);
                array_push($changenow, $compid);
                # check for existing vmhost entry
                $query = "SELECT id, " . "vmprofileid " . "FROM vmhost " . "WHERE computerid = {$compid}";
                $qh = doQuery($query, 101);
                if ($row = mysql_fetch_assoc($qh)) {
                    if ($row['vmprofileid'] != $profileid) {
                        # update vmprofile
                        $query = "UPDATE vmhost " . "SET vmprofileid = {$profileid} " . "WHERE id = {$row['id']}";
                        doQuery($query, 101);
                    }
                } else {
                    # create vmhost entry
                    $query = "INSERT INTO vmhost " . "(computerid, " . "vmlimit, " . "vmprofileid) " . "VALUES ({$compid}, " . "2, " . "{$profileid})";
                    doQuery($query, 101);
                }
            }
        }
        // release semaphore lock
        semUnlock();
        if (count($changenow)) {
            print "The following computers were placed into the ";
            print "vmhostinuse state:\n";
            print "<TABLE>\n";
            foreach ($changenow as $compid) {
                print "  <TR>\n";
                print "    <TD><font color=\"#008000\">{$computers[$compid]['hostname']}</font></TD>\n";
                print "  </TR>\n";
            }
            print "</TABLE>\n";
            print "<br>\n";
        }
        if (count($changeasap)) {
            print "The following computers currently have reservations on them ";
            print "and cannot be placed in the vmhostinuse state at this time:\n";
            print "<TABLE>\n";
            foreach ($changeasap as $compid) {
                print "  <TR>\n";
                print "    <TD><font color=\"ff0000\">{$computers[$compid]['hostname']}</font></TD>\n";
                print "  </TR>\n";
            }
            print "</TABLE>\n";
            print "<br>\n";
        }
        if (count($noaction)) {
            print "The following computers were already in the vmhostinuse ";
            print "state:\n";
            print "<TABLE>\n";
            foreach ($noaction as $compid) {
                print "  <TR>\n";
                print "    <TD>{$computers[$compid]['hostname']}</TD>\n";
                print "  </TR>\n";
            }
            print "</TABLE>\n";
            print "<br>\n";
        }
    } elseif ($data['stateid'] == 23) {
        $noaction = array();
        $changenow = array();
        $changeasap = array();
        $changetimes = array();
        foreach ($data['computerids'] as $compid) {
            if ($computers[$compid]['state'] == 'hpc') {
                array_push($noaction, $compid);
            } else {
                array_push($changeasap, $compid);
            }
        }
        if (!semLock()) {
            abort(3);
        }
        foreach ($changeasap as $compid) {
            # TODO what about blockComputers?
            moveReservationsOffComputer($compid);
            # get end time of last reservation
            $query = "SELECT rq.end " . "FROM request rq, " . "reservation rs " . "WHERE rs.requestid = rq.id AND " . "rs.computerid = {$compid} AND " . "rq.stateid NOT IN (1,5,12) " . "ORDER BY end DESC " . "LIMIT 1";
            $qh = doQuery($query, 101);
            if ($row = mysql_fetch_assoc($qh)) {
                // if there is a reservation, leave in $changeasap so we can
                #   notify that we can't change this one
            } else {
                $query = "UPDATE computer " . "SET stateid = 23 " . "WHERE id = {$compid}";
                doQuery($query, 101);
                unset_by_val($compid, $changeasap);
                array_push($changenow, $compid);
            }
        }
        // release semaphore lock
        semUnlock();
        if (count($changenow)) {
            print "The following computers were placed into the ";
            print "hpc state:\n";
            print "<TABLE>\n";
            foreach ($changenow as $compid) {
                print "  <TR>\n";
                print "    <TD><font color=\"#008000\">{$computers[$compid]['hostname']}</font></TD>\n";
                print "  </TR>\n";
            }
            print "</TABLE>\n";
            print "<br>\n";
        }
        if (count($changeasap)) {
            print "The following computers currently have reservations on them ";
            print "and cannot be placed in the hpc state at this time:\n";
            print "<TABLE>\n";
            foreach ($changeasap as $compid) {
                print "  <TR>\n";
                print "    <TD><font color=\"ff0000\">{$computers[$compid]['hostname']}</font></TD>\n";
                print "  </TR>\n";
            }
            print "</TABLE>\n";
            print "<br>\n";
        }
        if (count($noaction)) {
            print "The following computers were already in the hpc ";
            print "state:\n";
            print "<TABLE>\n";
            foreach ($noaction as $compid) {
                print "  <TR>\n";
                print "    <TD>{$computers[$compid]['hostname']}</TD>\n";
                print "  </TR>\n";
            }
            print "</TABLE>\n";
            print "<br>\n";
        }
    } else {
        abort(50);
    }
}
Example #9
0
function AJcancelVMmove()
{
    $hostid = processInputVar('hostid', ARG_NUMERIC);
    $hostdata = getVMHostData($hostid);
    $resources = getUserResources(array("computerAdmin"), array("administer"));
    if (!array_key_exists($hostdata[$hostid]['computerid'], $resources['computer'])) {
        $arr = array('failed' => 'nohostaccess');
        header('Content-Type: text/json-comment-filtered; charset=utf-8');
        print '/*{"items":' . json_encode($arr) . '}*/';
        return;
    }
    $fails = array();
    $requestids = processInputVar('listids', ARG_STRING);
    $now = time();
    $msg = 'FAIL';
    foreach (explode(',', $requestids) as $reqid) {
        $request = getRequestInfo($reqid);
        if (!array_key_exists($request['reservations'][0]['computerid'], $resources['computer'])) {
            $fails[] = array('id' => $request['reservations'][0]['computerid'], 'name' => $request['reservations'][0]['hostname'], 'reason' => 'noaccess');
            continue;
        }
        if (datetimeToUnix($request["start"]) < $now) {
            # set stateid and laststateid for each request to deleted
            $query = "UPDATE request " . "SET stateid = 1, " . "laststateid = 1 " . "WHERE id = {$reqid}";
            doQuery($query, 101);
        } else {
            $query = "DELETE FROM request WHERE id = {$reqid}";
            doQuery($query, 101);
            $query = "DELETE FROM reservation WHERE requestid = {$reqid}";
            doQuery($query, 101);
        }
        $msg = 'SUCCESS';
    }
    header('Content-Type: text/json-comment-filtered; charset=utf-8');
    $cont = addContinuationsEntry('vmhostdata');
    $arr = array('msg' => $msg, 'cont' => $cont, 'fails' => $fails);
    print '/*{"items":' . json_encode($arr) . '}*/';
}
Example #10
0
function printHTMLHeader()
{
    global $mode, $user, $authed, $oldmode, $HTMLheader, $contdata;
    global $printedHTMLheader, $docreaders, $noHTMLwrappers, $actions;
    if ($printedHTMLheader) {
        return;
    }
    $refresh = 0;
    if ($authed && $mode == "viewRequests") {
        $requests = getUserRequests("all", $user["id"]);
        if ($count = count($requests)) {
            $now = time() + 15 * 60;
            for ($i = 0; $i < $count; $i++) {
                if (datetimeToUnix($requests[$i]["start"]) < $now && ($requests[$i]["currstateid"] == 13 || $requests[$i]["currstateid"] == 14 && $requests[$i]["laststateid"] == 13 || $requests[$i]["currstateid"] == 3 || $requests[$i]["currstateid"] == 8 && !$requests[$i]["useraccountready"])) {
                    $refresh = 1;
                }
            }
        }
    }
    if ($mode != 'selectauth' && $mode != 'submitLogin') {
        $HTMLheader .= getHeader($refresh);
    }
    if (!in_array($mode, $noHTMLwrappers) && (!is_array($contdata) || !array_key_exists('noHTMLwrappers', $contdata) || $contdata['noHTMLwrappers'] == 0)) {
        print $HTMLheader;
        if ($mode != 'inmaintenance') {
            print maintenanceNotice();
        }
        $printedHTMLheader = 1;
    }
}
Example #11
0
function getRevisionHTML($imageid)
{
    $rt = '';
    $rt .= "<h3>Revisions of this Image</h3>\n";
    $rt .= "<table summary=\"\"><tr><td>\n";
    $rt .= "<table summary=\"\" id=\"revisiontable\">\n";
    $rt .= "  <tr>\n";
    $rt .= "    <td></td>\n";
    $rt .= "    <th>Revision</th>\n";
    $rt .= "    <th>Creator</th>\n";
    $rt .= "    <th>Created</th>\n";
    $rt .= "    <th nowrap>In Production</th>\n";
    $rt .= "    <th>Comments (click to edit)</th>\n";
    $rt .= "  </tr>\n";
    $revisions = getImageRevisions($imageid);
    foreach ($revisions as $rev) {
        $rt .= "  <tr>\n";
        $rt .= "    <td><INPUT type=checkbox\n";
        $rt .= "              id=chkrev{$rev['id']}\n";
        $rt .= "              name=chkrev[{$rev['id']}]\n";
        $rt .= "              value=1></td>\n";
        $rt .= "    <td align=center>{$rev['revision']}</td>\n";
        $rt .= "    <td>{$rev['creator']}</td>\n";
        $created = date('g:ia n/j/Y', datetimeToUnix($rev['datecreated']));
        $rt .= "    <td>{$created}</td>\n";
        $cdata = array('imageid' => $imageid, 'revisionid' => $rev['id']);
        $cont = addContinuationsEntry('AJupdateRevisionProduction', $cdata);
        if ($rev['production']) {
            $rt .= "    <td align=center><INPUT type=radio\n";
            $rt .= "           name=production\n";
            $rt .= "           value={$rev['id']}\n";
            $rt .= "           id=radrev{$rev['id']}\n";
            $rt .= "           onclick=\"updateRevisionProduction('{$cont}');\"\n";
            $rt .= "           checked></td>\n";
        } else {
            $rt .= "    <td align=center><INPUT type=radio\n";
            $rt .= "           name=production\n";
            $rt .= "           value={$rev['id']}\n";
            $rt .= "           id=radrev{$rev['id']}\n";
            $rt .= "           onclick=\"updateRevisionProduction('{$cont}');\">\n";
            $rt .= "           </td>\n";
        }
        $cdata = array('imageid' => $imageid, 'revisionid' => $rev['id']);
        $cont = addContinuationsEntry('AJupdateRevisionComments', $cdata);
        $rt .= "    <td width=200px><span id=comments{$rev['id']} \n";
        $rt .= "              dojoType=\"dijit.InlineEditBox\"\n";
        $rt .= "              editor=\"dijit.form.Textarea\"\n";
        $rt .= "              onChange=\"updateRevisionComments('comments{$rev['id']}', '{$cont}');\"\n";
        $rt .= "              noValueIndicator=\"(empty)\">\n";
        $rt .= "        {$rev['comments']}</span></td>\n";
        $rt .= "  </tr>\n";
    }
    $rt .= "</table>\n";
    $rt .= "<div align=left>\n";
    $keys = array_keys($revisions);
    $cdata = array('revids' => $keys, 'imageid' => $imageid);
    $cont = addContinuationsEntry('AJdeleteRevisions', $cdata);
    $ids = implode(',', $keys);
    $rt .= "<button onclick=\"deleteRevisions('{$cont}', '{$ids}'); return false;\">Delete selected revisions</button>\n";
    $rt .= "</div>\n";
    $rt .= "</td></tr></table>\n";
    return $rt;
}
Example #12
0
function submitHelpForm()
{
    global $user, $submitErr, $submitErrMsg;
    $name = processInputVar("name", ARG_STRING);
    $email = processInputVar("email", ARG_STRING);
    $summary = processInputVar("summary", ARG_STRING);
    $text = processInputVar("comments", ARG_STRING);
    if (!ereg('^([A-Za-z]{1,}( )([A-Za-z]){2,})$', $name)) {
        $submitErr |= NAMEERR;
        $submitErrMsg[NAMEERR] = "You must submit your first and last name";
    }
    if (!eregi('^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$', $email)) {
        $submitErr |= EMAILERR;
        $submitErrMsg[EMAILERR] = "Invalid email address, please correct";
    }
    if (empty($summary)) {
        $submitErr |= SUMMARYERR;
        $submitErrMsg[SUMMARYERR] = "Please fill in a very short summary of the " . "problem";
    }
    if (empty($text)) {
        $submitErr |= TEXTERR;
        $submitErrMsg[TEXTERR] = "Please fill in your problem in the box below.<br>";
    }
    if ($submitErr) {
        printHelpForm();
        return;
    }
    $computers = getComputers();
    $requests = getUserRequests("all");
    $query = "SELECT l.start AS start, " . "l.finalend AS end, " . "l.computerid AS computerid, " . "i.prettyname AS prettyimage " . "FROM log l, " . "image i " . "WHERE l.userid = " . $user["id"] . " AND " . "i.id = l.imageid AND " . "(unix_timestamp(NOW()) - unix_timestamp(l.finalend)) < 14400";
    $qh = doQuery($query, 290);
    while ($row = mysql_fetch_assoc($qh)) {
        array_push($requests, $row);
    }
    $from = $user["email"];
    if (get_magic_quotes_gpc()) {
        $text = stripslashes($text);
    }
    $message = "Problem report submitted from VCL web form:\n\n" . "User: "******"unityid"] . "\n" . "Name: " . $name . "\n" . "Email: " . $email . "\n" . "Problem description:\n\n{$text}\n\n";
    $end = time();
    $start = $end - 14400;
    $recentrequests = "";
    foreach ($requests as $request) {
        if (datetimeToUnix($request["end"]) > $start || datetimeToUnix($request["start"] < $end)) {
            $thisstart = str_replace('&nbsp;', ' ', prettyDatetime($request["start"]));
            $thisend = str_replace('&nbsp;', ' ', prettyDatetime($request["end"]));
            $recentrequests .= "Image: " . $request["prettyimage"] . "\n" . "Computer: " . $computers[$request["computerid"]]["hostname"] . "\n" . "Start: {$thisstart}\n" . "End: {$thisend}\n\n";
        }
    }
    if (!empty($recentrequests)) {
        $message .= "-----------------------------------------------\n";
        $message .= "User's recent reservations:\n\n" . $recentrequests . "\n";
    } else {
        $message .= "User has no recent reservations\n";
    }
    $indrupal = getContinuationVar('indrupal', 0);
    if (!$indrupal) {
        print "<H2>VCL Help</H2>\n";
    }
    $mailParams = "-f" . ENVELOPESENDER;
    if (!mail(HELPEMAIL, "{$summary}", $message, "From: {$from}\r\nReply-To: {$email}\r\n", $mailParams)) {
        print "The Server was unable to send mail at this time. Please e-mail ";
        print "<a href=\"mailto:" . HELPEMAIL . "\">" . HELPEMAIL . "</a> for ";
        print "help with your problem.";
    } else {
        print "Your problem report has been submitted.  Thank you for letting ";
        print "us know of your problem so that we can improve this site.<br>\n";
    }
}
Example #13
0
function XMLRPCprocessBlockTime($blockTimesid, $ignoreprivileges = 0)
{
    global $requestInfo, $user, $xmlrpcBlockAPIUsers;
    if (!in_array($user['id'], $xmlrpcBlockAPIUsers)) {
        return array('status' => 'error', 'errorcode' => 34, 'errormsg' => 'access denied for managing block allocations');
    }
    $return = array('status' => 'success');
    $query = "SELECT bt.start, " . "bt.end, " . "br.imageid, " . "br.numMachines, " . "br.groupid, " . "br.expireTime " . "FROM blockRequest br, " . "blockTimes bt " . "WHERE bt.blockRequestid = br.id AND " . "bt.id = {$blockTimesid}";
    $qh = doQuery($query, 101);
    if (!($rqdata = mysql_fetch_assoc($qh))) {
        return array('status' => 'error', 'errorcode' => 8, 'errormsg' => 'unknown blockTimesid');
    }
    if (datetimeToUnix($rqdata['expireTime']) < time()) {
        return array('status' => 'error', 'errorcode' => 9, 'errormsg' => 'expired block reservation');
    }
    $images = getImages(0, $rqdata['imageid']);
    if (empty($images)) {
        return array('status' => 'error', 'errorcode' => 10, 'errormsg' => 'invalid image associated with block request');
    }
    # check to see if all computers have been allocated
    $query = "SELECT COUNT(computerid) AS allocated " . "FROM blockComputers " . "WHERE blockTimeid = {$blockTimesid}";
    $qh = doQuery($query, 101);
    if (!($row = mysql_fetch_assoc($qh))) {
        return array('status' => 'error', 'errorcode' => 15, 'errormsg' => 'failure to communicate with database');
    }
    $compCompleted = $row['allocated'];
    $compsPerRequest = 1 + count($images[$rqdata['imageid']]['subimages']);
    $toallocate = $rqdata['numMachines'] * $compsPerRequest - $compCompleted;
    if ($toallocate == 0) {
        return array('status' => 'completed');
    }
    $reqToAlloc = $toallocate / $compsPerRequest;
    if (!$ignoreprivileges) {
        # get userids in user group
        $tmp = getUserGroupMembers($rqdata['groupid']);
        if (empty($tmp)) {
            return array('status' => 'error', 'errorcode' => 11, 'errormsg' => 'empty user group and ignoreprivileges set to 0');
        }
        $userids = array_keys($tmp);
        # make length of $userids match $reqToAlloc by duplicating or trimming some users
        while ($reqToAlloc > count($userids)) {
            $userids = array_merge($userids, $userids);
        }
        if ($reqToAlloc < count($userids)) {
            $userids = array_splice($userids, 0, $reqToAlloc);
        }
    }
    # staggering: stagger start times for this round (ie, don't worry about
    #   previous processing of this block time) such that there is 1 minute
    #   between the start times for each request
    $stagExtra = $reqToAlloc * 60;
    # determine estimated load time
    $imgLoadTime = getImageLoadEstimate($rqdata['imageid']);
    if ($imgLoadTime == 0) {
        $imgLoadTime = $images[$rqdata['imageid']]['reloadtime'] * 60;
    }
    $loadtime = $imgLoadTime + 10 * 60;
    # add 10 minute fudge factor
    $unixstart = datetimeToUnix($rqdata['start']);
    if (time() + $loadtime + $stagExtra > $unixstart) {
        $return['status'] = 'warning';
        $return['warningcode'] = 13;
        $return['warningmsg'] = 'possibly insufficient time to load machines';
    }
    $start = unixToDatetime($unixstart - $loadtime);
    $unixend = datetimeToUnix($rqdata['end']);
    $userid = 0;
    $allocated = 0;
    $vclreloadid = getUserlistID('vclreload@Local');
    $revisionid = getProductionRevisionid($rqdata['imageid']);
    $blockCompVals = array();
    # FIXME (maybe) - if some subset of users in the user group have available
    # computers, but others do not, $allocated will be less than the desired
    # number of machines; however, calling this function enough times will
    # result in enough machines being allocated because they will continue to be
    # allocated based on the ones with machines available; this seems like odd
    # behavior
    $stagCnt = 0;
    for ($i = 0; $i < $reqToAlloc; $i++) {
        $stagunixstart = $unixstart - $loadtime - $stagCnt * 60;
        $stagstart = unixToDatetime($stagunixstart);
        if (!$ignoreprivileges) {
            $userid = array_pop($userids);
        }
        # use end of block time to find available computers, but...
        $rc = isAvailable($images, $rqdata['imageid'], $stagunixstart, $unixend, 0, 0, $userid, $ignoreprivileges);
        if ($rc < 1) {
            continue;
        }
        $compid = $requestInfo['computers'][0];
        # ...use start of block time as end of reload reservation
        $reqid = simpleAddRequest($compid, $rqdata['imageid'], $revisionid, $stagstart, $rqdata['start'], 19, $vclreloadid);
        if ($reqid == 0) {
            continue;
        }
        $stagCnt++;
        $allocated++;
        $blockCompVals[] = "({$blockTimesid}, {$compid}, {$rqdata['imageid']})";
        # process any subimages
        for ($key = 1; $key < count($requestInfo['computers']); $key++) {
            $subimageid = $requestInfo['images'][$key];
            $subrevid = getProductionRevisionid($subimageid);
            $compid = $requestInfo['computers'][$key];
            $mgmtnodeid = $requestInfo['mgmtnodes'][$key];
            $blockCompVals[] = "({$blockTimesid}, {$compid}, {$subimageid})";
            $query = "INSERT INTO reservation " . "(requestid, " . "computerid, " . "imageid, " . "imagerevisionid, " . "managementnodeid) " . "VALUES " . "({$reqid}, " . "{$compid}, " . "{$subimageid}, " . "{$subrevid}, " . "{$mgmtnodeid})";
            doQuery($query, 101);
        }
        semUnlock();
        $blockComps = implode(',', $blockCompVals);
        $query = "INSERT INTO blockComputers " . "(blockTimeid, computerid, imageid) " . "VALUES {$blockComps}";
        doQuery($query, 101);
        $blockCompVals = array();
    }
    if ($allocated == 0) {
        $return['status'] = 'warning';
        $return['warningcode'] = 14;
        $return['warningmsg'] = 'unable to allocate any machines';
    }
    $return['allocated'] = $compCompleted / $compsPerRequest + $allocated;
    $return['unallocated'] = $rqdata['numMachines'] - $return['allocated'];
    return $return;
}
Example #14
0
function AJviewBlockAllocationUsage()
{
    $blockid = processInputVar('blockid', ARG_NUMERIC);
    $allowedblockids = getContinuationVar('blockids');
    if (!in_array($blockid, $allowedblockids)) {
        sendJSON(array('status' => 'failed', 'message' => 'noaccess'));
        return;
    }
    $query = "SELECT COUNT(s.computerid) AS used, " . "br.numMachines AS allocated, " . "s.blockStart " . "FROM blockRequest br " . "LEFT JOIN sublog s ON (s.blockRequestid = br.id) " . "WHERE br.id = {$blockid} " . "GROUP BY s.blockRequestid, s.blockStart, s.blockEnd " . "ORDER BY s.blockStart";
    $qh = doQuery($query);
    $usage = array();
    $first = 1;
    $firststart = '';
    $laststart = '';
    while ($row = mysql_fetch_assoc($qh)) {
        if ($first && !is_null($row['blockStart'])) {
            $firststart = datetimeToUnix($row['blockStart']);
            $first = 0;
        } elseif (!is_null($row['blockStart'])) {
            $laststart = datetimeToUnix($row['blockStart']);
        }
        if (is_null($row['blockStart'])) {
            continue;
        }
        $percent = (int) ($row['used'] / $row['allocated'] * 100);
        $startts = datetimeToUnix($row['blockStart']);
        $usage[$startts] = array('percent' => $percent, 'label' => $row['blockStart']);
    }
    if ($firststart == '') {
        sendJSON(array('status' => 'empty', 'message' => 'nousage'));
        return;
    }
    $data = array('points' => array(), 'xlabels' => array());
    $cnt = 0;
    $tmp = localtime($firststart, 1);
    $firstisdst = 0;
    if ($tmp['tm_isdst']) {
        $firstisdst = 1;
    }
    for ($i = $firststart; $i <= $laststart + 3600; $i += SECINDAY) {
        $tmp = localtime($i, 1);
        $time = $i;
        if ($firstisdst && !$tmp['tm_isdst']) {
            $time += 3600;
        }
        if (!$firstisdst && $tmp['tm_isdst']) {
            $time -= 3600;
        }
        $cnt++;
        $label = date('m/d g:i a', $time);
        if (array_key_exists($time, $usage)) {
            $data['points'][] = array('y' => $usage[$time]['percent'], 'tooltip' => "{$label}: " . $usage[$time]['percent'] . " %");
        } else {
            $data['points'][] = array('y' => 0, 'tooltip' => "{$label}: 0");
        }
        $data['xlabels'][] = array('value' => $cnt, 'text' => $label);
    }
    sendJSON(array('status' => 'success', 'usage' => $data));
}
Example #15
0
function processBlockRequestInput($checks = 1)
{
    global $submitErr, $submitErrMsg, $mode, $user, $days;
    $return = array();
    $return['blockname'] = getContinuationVar("blockname", processInputVar("blockname", ARG_STRING));
    $return['imageid'] = getContinuationVar("imageid", processInputVar("imageid", ARG_NUMERIC));
    $return['machinecnt'] = getContinuationVar("machinecnt", processInputVar("machinecnt", ARG_NUMERIC, 0));
    $return['swhour'] = getContinuationVar("swhour", processInputVar("swhour", ARG_MULTINUMERIC));
    $return['swminute'] = getContinuationVar("swminute", processInputVar("swminute", ARG_MULTINUMERIC));
    $return['swmeridian'] = getContinuationVar("swmeridian", processInputVar("swmeridian", ARG_MULTISTRING));
    $return['ewhour'] = getContinuationVar("ewhour", processInputVar("ewhour", ARG_MULTINUMERIC));
    $return['ewminute'] = getContinuationVar("ewminute", processInputVar("ewminute", ARG_MULTINUMERIC));
    $return['ewmeridian'] = getContinuationVar("ewmeridian", processInputVar("ewmeridian", ARG_MULTISTRING));
    $return['smhour'] = getContinuationVar("smhour", processInputVar("smhour", ARG_MULTINUMERIC));
    $return['smminute'] = getContinuationVar("smminute", processInputVar("smminute", ARG_MULTINUMERIC));
    $return['smmeridian'] = getContinuationVar("smmeridian", processInputVar("smmeridian", ARG_MULTISTRING));
    $return['emhour'] = getContinuationVar("emhour", processInputVar("emhour", ARG_MULTINUMERIC));
    $return['emminute'] = getContinuationVar("emminute", processInputVar("emminute", ARG_MULTINUMERIC));
    $return['emmeridian'] = getContinuationVar("emmeridian", processInputVar("emmeridian", ARG_MULTISTRING));
    $return['slhour'] = getContinuationVar("slhour", processInputVar("slhour", ARG_MULTINUMERIC));
    $return['slminute'] = getContinuationVar("slminute", processInputVar("slminute", ARG_MULTINUMERIC));
    $return['slmeridian'] = getContinuationVar("slmeridian", processInputVar("slmeridian", ARG_MULTISTRING));
    $return['elhour'] = getContinuationVar("elhour", processInputVar("elhour", ARG_MULTINUMERIC));
    $return['elminute'] = getContinuationVar("elminute", processInputVar("elminute", ARG_MULTINUMERIC));
    $return['elmeridian'] = getContinuationVar("elmeridian", processInputVar("elmeridian", ARG_MULTISTRING));
    $return['weeknum'] = getContinuationVar("weeknum", processInputVar("weeknum", ARG_NUMERIC));
    $return['day'] = getContinuationVar("day", processInputVar("day", ARG_NUMERIC));
    $return['date'] = getContinuationVar("date", processInputVar("date", ARG_MULTISTRING));
    $return['available'] = getContinuationVar("available", processInputVar("available", ARG_STRING, 'weekly'));
    $return['usergroupid'] = getContinuationVar("usergroupid", processInputVar("usergroupid", ARG_NUMERIC));
    $return['admingroupid'] = getContinuationVar("admingroupid", processInputVar("admingroupid", ARG_NUMERIC));
    $return['swdate'] = getContinuationVar("swdate", processInputVar("swdate", ARG_STRING));
    $return['ewdate'] = getContinuationVar("ewdate", processInputVar("ewdate", ARG_STRING));
    $return['smdate'] = getContinuationVar("smdate", processInputVar("smdate", ARG_STRING));
    $return['emdate'] = getContinuationVar("emdate", processInputVar("emdate", ARG_STRING));
    $return['wdays'] = getContinuationVar("wdays", processInputVar("wdays", ARG_MULTISTRING));
    $return['state'] = getContinuationVar("state", 0);
    $return['blockRequestid'] = getContinuationVar("blockRequestid", processInputVar("blockRequestid", ARG_NUMERIC));
    $return['wdayschecked'] = array();
    foreach ($days as $day) {
        if (in_array($day, $return['wdays'])) {
            $return['wdayschecked'][$day] = 'checked';
        } else {
            $return['wdayschecked'][$day] = '';
        }
    }
    if (!$checks) {
        return $return;
    }
    if (!preg_match('/^([-a-zA-Z0-9\\. ]){3,80}$/', $return["blockname"])) {
        $submitErr |= BLOCKNAMEERR;
        $submitErrMsg[BLOCKNAMEERR] = "Name can only contain letters, numbers, spaces, dashes(-),<br>and periods(.) and can be from 3 to 80 characters long";
    }
    $resources = getUserResources(array("imageAdmin", "imageCheckOut"));
    $resources["image"] = removeNoCheckout($resources["image"]);
    if (!in_array($return['imageid'], array_keys($resources['image']))) {
        $submitErr |= IMAGEIDERR;
        $submitErrMsg[IMAGEIDERR] = "The submitted image is invalid.";
    }
    if ($return['machinecnt'] < MIN_BLOCK_MACHINES) {
        $submitErr |= BLOCKCNTERR;
        $submitErrMsg[BLOCKCNTERR] = "You must request at least " . MIN_BLOCK_MACHINES . " machines";
    } elseif ($return['machinecnt'] > MAX_BLOCK_MACHINES) {
        $submitErr |= BLOCKCNTERR;
        $submitErrMsg[BLOCKCNTERR] = "You cannot request more than " . MAX_BLOCK_MACHINES . " machines";
    }
    // FIXME should we limit the course groups that show up?
    $groups = getUserGroups();
    if (!array_key_exists($return['usergroupid'], $groups)) {
        $submitErr |= USERGROUPIDERR;
        $submitErrMsg[USERGROUPIDERR] = "The submitted user group is invalid.";
    }
    if (!array_key_exists($return['admingroupid'], $groups) && $return['admingroupid'] != 0) {
        $submitErr |= ADMINGROUPIDERR;
        $submitErrMsg[ADMINGROUPIDERR] = "The submitted user group is invalid.";
    }
    if ($return['available'] == 'weekly') {
        $keys = array('1' => 'swhour', '2' => 'ewhour', '3' => 'swminute', '4' => 'ewminute', '5' => 'swmeridian', '6' => 'ewmeridian', '7' => 'swdate', '8' => 'ewdate');
        // check days of week
        foreach ($return['wdays'] as $index => $day) {
            if (!in_array($day, $days)) {
                unset($return['wdays'][$index]);
            }
        }
        /*foreach($days as $day) {
        			if(in_array($day, $return['wdays']))
        				$return['wdayschecked'][$day] = 'checked';
        		}*/
        if (!count($return['wdays'])) {
            $submitErr |= STARTDAYERR;
            $submitErrMsg[STARTDAYERR] = "You must select at least one day of the week";
        }
    } elseif ($return['available'] == 'monthly') {
        $keys = array('1' => 'smhour', '2' => 'emhour', '3' => 'smminute', '4' => 'emminute', '5' => 'smmeridian', '6' => 'emmeridian', '7' => 'smdate', '8' => 'emdate');
        // check weeknum
        if ($return['weeknum'] < 1 || $return['weeknum'] > 5) {
            $submitErr |= WEEKNUMERR;
            $submitErrMsg[WEEKNUMERR] = "Invalid week of the month submitted";
        }
        // check day
        if ($return['day'] < 1 || $return['day'] > 7) {
            $submitErr |= DAYERR;
            $submitErrMsg[DAYERR] = "Invalid day of the week submitted";
        }
    } elseif ($return['available'] == 'list') {
        $keys = array('1' => 'slhour', '2' => 'elhour', '3' => 'slminute', '4' => 'elminute', '5' => 'slmeridian', '6' => 'elmeridian');
    }
    // check each timeslot
    for ($i = 0; $i < 4; $i++) {
        $submitErrMsg[STARTHOURERR][$i] = "";
        $submitErrMsg[ENDHOURERR][$i] = "";
        // start hour
        if ($return[$keys[1]][$i] < 1 || $return[$keys[1]][$i] > 12) {
            $submitErr |= STARTHOURERR;
            $submitErrMsg[STARTHOURERR][$i] = "The start hour must be between 1 and 12.";
        }
        // end hour
        if ($return[$keys[2]][$i] < 1 || $return[$keys[2]][$i] > 12) {
            $submitErr |= ENDHOURERR;
            $submitErrMsg[ENDHOURERR][$i] = " The end hour must be between 1 and 12.";
        }
        // start minute
        if ($return[$keys[3]][$i] < 0 || $return[$keys[3]][$i] > 59) {
            $submitErr |= STARTHOURERR;
            // we reuse STARTHOURERR here, it overwrites the last one, but oh well
            $submitErrMsg[STARTHOURERR][$i] = "The start minute must be between 0 and 59.";
        }
        // end minute
        if ($return[$keys[4]][$i] < 0 || $return[$keys[4]][$i] > 59) {
            $submitErr |= ENDHOURERR;
            $submitErrMsg[ENDHOURERR][$i] = " The end minute must be between 0 and 59.";
        }
        // start meridian
        if ($return[$keys[5]][$i] != 'am' && $return[$keys[5]][$i] != 'pm') {
            $return[$keys[5]][$i] = 'pm';
            // just set it to one of them
        }
        // end meridian
        if ($return[$keys[6]][$i] != 'am' && $return[$keys[6]][$i] != 'pm') {
            $return[$keys[6]][$i] = 'am';
            // just set it to one of them
        }
        // check that start is before end
        $return['stime'][$i] = minuteOfDay2("{$return[$keys[1]][$i]}:{$return[$keys[3]][$i]} {$return[$keys[5]][$i]}");
        $return['etime'][$i] = minuteOfDay2("{$return[$keys[2]][$i]}:{$return[$keys[4]][$i]} {$return[$keys[6]][$i]}");
        if ($return['stime'][$i] > $return['etime'][$i]) {
            $submitErr |= STARTHOURERR;
            // we reuse STARTHOURERR here, it overwrites the last one, but oh well
            $submitErrMsg[STARTHOURERR][$i] = "The start time must be before the end time (or be equal to ignore this slot)";
        }
    }
    if ($return['available'] == 'weekly' || $return['available'] == 'monthly') {
        // check that timeslots do not overlap
        if (!($submitErr & STARTHOURERR) && !($submitErr & ENDHOURERR)) {
            for ($i = 0; $i < 4; $i++) {
                for ($j = $i + 1; $j < 4; $j++) {
                    if ($return['etime'][$i] > $return['stime'][$j] && $return['stime'][$i] < $return['etime'][$j]) {
                        $submitErr |= STARTHOURERR;
                        $submitErrMsg[STARTHOURERR][$i] = "This timeslot overlaps with Slot" . ($j + 1);
                    }
                }
            }
        }
        // check that start date is valid
        $startarr = split('/', $return[$keys[7]]);
        if (!preg_match('/^((\\d){1,2})\\/((\\d){1,2})\\/(\\d){2}$/', $return[$keys[7]])) {
            $submitErr |= STARTDATEERR;
            $submitErrMsg[STARTDATEERR] = "The start date must be in the form mm/dd/yy.";
        } elseif (!checkdate($startarr[0], $startarr[1], $startarr[2])) {
            $submitErr |= STARTDATEERR;
            $submitErrMsg[STARTDATEERR] = "This is an invalid date.";
        } elseif (datetimeToUnix("{$startarr[2]}-{$startarr[0]}-{$startarr[1]} 23:59:59") < time()) {
            $submitErr |= STARTDATEERR;
            $submitErrMsg[STARTDATEERR] = "The start date must be today or later.";
        }
        // check that end date is valid
        $endarr = split('/', $return[$keys[8]]);
        if (!preg_match('/^((\\d){1,2})\\/((\\d){1,2})\\/(\\d){2}$/', $return[$keys[8]])) {
            $submitErr |= ENDDATEERR;
            $submitErrMsg[ENDDATEERR] = "The end date must be in the form mm/dd/yy.";
        } elseif (!checkdate($endarr[0], $endarr[1], $endarr[2])) {
            $submitErr |= ENDDATEERR;
            $submitErrMsg[ENDDATEERR] = "This is an invalid date.";
        } elseif (datetimeToUnix("{$startarr[2]}-{$startarr[0]}-{$startarr[1]} 00:00:00") > datetimeToUnix("{$endarr[2]}-{$endarr[0]}-{$endarr[1]} 00:00:00")) {
            $submitErr |= ENDDATEERR;
            $submitErrMsg[ENDDATEERR] = "The end date must be later than the start date.";
        }
    } elseif ($return['available'] == 'list') {
        if (!($submitErr & STARTHOURERR) && !($submitErr & ENDHOURERR)) {
            // check date[1-n]
            for ($i = 0; $i < 4; $i++) {
                $submitErrMsg[STARTDATEERR][$i] = "";
                if ($return['stime'][$i] == $return['etime'][$i]) {
                    continue;
                }
                $submitErrMsg[STARTDATEERR][$i] = "";
                $datearr = split('/', $return['date'][$i]);
                if (!preg_match('/^((\\d){1,2})\\/((\\d){1,2})\\/(\\d){2}$/', $return['date'][$i])) {
                    $submitErr |= STARTDATEERR;
                    $submitErrMsg[STARTDATEERR][$i] = "The date must be in the form mm/dd/yy.";
                } elseif (!checkdate($datearr[0], $datearr[1], $datearr[2])) {
                    $submitErr |= STARTDATEERR;
                    $submitErrMsg[STARTDATEERR][$i] = "Invalid date submitted.";
                } elseif (datetimeToUnix("{$datearr[2]}-{$datearr[0]}-{$datearr[1]} 23:59:59") < time()) {
                    $submitErr |= STARTDATEERR;
                    $submitErrMsg[STARTDATEERR][$i] = "The date must be today or later.";
                }
            }
        }
    }
    if (0) {
        # FIXME
        $submitErr |= AVAILABLEERR;
        $submitErrMsg[AVAILABLEERR] = "The submitted availability selection is invalid.";
    }
    return $return;
}
Example #16
0
function checkExpiredDemoUser($userid, $groups = 0)
{
    global $mode, $skin, $noHTMLwrappers;
    if ($groups == 0) {
        $groups = getUsersGroups($userid, 1);
    }
    if (count($groups) != 1) {
        return;
    }
    $tmp = array_values($groups);
    if ($tmp[0] != 'demo') {
        return;
    }
    $query = "SELECT start " . "FROM log " . "WHERE userid = {$userid} " . "AND finalend < NOW() " . "ORDER BY start " . "LIMIT 3";
    $qh = doQuery($query, 101);
    $expire = time() - SECINDAY * 3;
    $rows = mysql_num_rows($qh);
    if ($row = mysql_fetch_assoc($qh)) {
        if ($rows >= 3 || datetimeToUnix($row['start']) < $expire) {
            if (in_array($mode, $noHTMLwrappers)) {
                # do a redirect and handle removal on next page load so user can
                #   be notified - doesn't always work, but handles a few extra
                #   cases
                header("Location: " . BASEURL . SCRIPT);
            } else {
                $nodemoid = getUserGroupID('nodemo', getAffiliationID('ITECS'));
                $query = "DELETE FROM usergroupmembers " . "WHERE userid = {$userid}";
                # because updateGroups doesn't
                # delete from custom groups
                doQuery($query, 101);
                updateGroups(array($nodemoid), $userid);
                checkUpdateServerRequestGroups($groupid);
                if (empty($skin)) {
                    $skin = 'default';
                    require_once "themes/{$skin}/page.php";
                }
                $mode = 'expiredemouser';
                printHTMLHeader();
                print "<h2>Account Expired</h2>\n";
                print "The account you are using is a demo account that has now expired. ";
                print "You cannot make any more reservations. Please contact <a href=\"";
                print "mailto:" . HELPEMAIL . "\">" . HELPEMAIL . "</a> if you need ";
                print "further access to VCL.<br>\n";
            }
            cleanSemaphore();
            # probably not needed but ensures we do not leave stale entries
            printHTMLFooter();
            dbDisconnect();
            exit;
        }
    }
}
Example #17
0
function XMLRPCprocessBlockTime($blockTimesid, $ignoreprivileges = 0)
{
    global $requestInfo, $user, $xmlrpcBlockAPIUsers;
    if (!in_array($user['id'], $xmlrpcBlockAPIUsers)) {
        return array('status' => 'error', 'errorcode' => 34, 'errormsg' => 'access denied for managing block allocations');
    }
    # validate $blockTimesid
    if (!is_numeric($blockTimesid)) {
        return array('status' => 'error', 'errorcode' => 77, 'errormsg' => 'Invalid blockTimesid specified');
    }
    # validate ignoreprivileges
    if (!is_numeric($ignoreprivileges) || $ignoreprivileges < 0 || $ignoreprivileges > 1) {
        return array('status' => 'error', 'errorcode' => 86, 'errormsg' => 'ignoreprivileges must be 0 or 1');
    }
    $return = array('status' => 'success');
    $query = "SELECT bt.start, " . "bt.end, " . "br.imageid, " . "br.numMachines, " . "br.groupid, " . "br.expireTime " . "FROM blockRequest br, " . "blockTimes bt " . "WHERE bt.blockRequestid = br.id AND " . "bt.id = {$blockTimesid}";
    $qh = doQuery($query, 101);
    if (!($rqdata = mysql_fetch_assoc($qh))) {
        return array('status' => 'error', 'errorcode' => 8, 'errormsg' => 'unknown blockTimesid');
    }
    if (datetimeToUnix($rqdata['expireTime']) < time()) {
        return array('status' => 'error', 'errorcode' => 9, 'errormsg' => 'expired block allocation');
    }
    $images = getImages(0, $rqdata['imageid']);
    if (empty($images)) {
        return array('status' => 'error', 'errorcode' => 10, 'errormsg' => 'invalid image associated with block allocation');
    }
    $unixstart = datetimeToUnix($rqdata['start']);
    $unixend = datetimeToUnix($rqdata['end']);
    $revisionid = getProductionRevisionid($rqdata['imageid']);
    $imgLoadTime = getImageLoadEstimate($rqdata['imageid']);
    if ($imgLoadTime == 0) {
        $imgLoadTime = $images[$rqdata['imageid']]['reloadtime'] * 60;
    }
    $vclreloadid = getUserlistID('vclreload@Local');
    $groupmembers = getUserGroupMembers($rqdata['groupid']);
    $userids = array_keys($groupmembers);
    # add any computers from future reservations users in the group made
    if (!empty($groupmembers)) {
        ## find reservations by users
        $allids = implode(',', $userids);
        $query = "SELECT rq.id AS reqid, " . "UNIX_TIMESTAMP(rq.start) AS start, " . "rq.userid " . "FROM request rq, " . "reservation rs " . "WHERE rs.requestid = rq.id AND " . "rq.userid IN ({$allids}) AND " . "rq.start < '{$rqdata['end']}' AND " . "rq.end > '{$rqdata['start']}' AND " . "rs.imageid = {$rqdata['imageid']} AND " . "rs.computerid NOT IN (SELECT computerid " . "FROM blockComputers " . "WHERE blockTimeid = {$blockTimesid})";
        $qh = doQuery($query);
        $donereqids = array();
        $blockCompVals = array();
        $checkstartbase = $unixstart - $imgLoadTime - 300;
        $reloadstartbase = unixToDatetime($checkstartbase);
        $rows = mysql_num_rows($qh);
        while ($row = mysql_fetch_assoc($qh)) {
            if (array_key_exists($row['reqid'], $donereqids)) {
                continue;
            }
            $donereqids[$row['reqid']] = 1;
            if ($row['start'] < datetimeToUnix($rqdata['start'])) {
                $checkstart = $row['start'] - $imgLoadTime - 300;
                $reloadstart = unixToDatetime($checkstart);
                $reloadend = unixToDatetime($row['start']);
            } else {
                $checkstart = $checkstartbase;
                $reloadstart = $reloadstartbase;
                $reloadend = $rqdata['start'];
            }
            # check to see if computer is available for whole block
            $rc = isAvailable($images, $rqdata['imageid'], $revisionid, $checkstart, $unixend, 1, $row['reqid'], $row['userid'], $ignoreprivileges, 0, '', '', 1);
            // if not available for whole block, just skip this one
            if ($rc < 1) {
                continue;
            }
            $compid = $requestInfo['computers'][0];
            # create reload reservation
            $reqid = simpleAddRequest($compid, $rqdata['imageid'], $revisionid, $reloadstart, $reloadend, 19, $vclreloadid);
            if ($reqid == 0) {
                continue;
            }
            # add to blockComputers
            $blockCompVals[] = "({$blockTimesid}, {$compid}, {$rqdata['imageid']}, {$reqid})";
            # process any subimages
            for ($key = 1; $key < count($requestInfo['computers']); $key++) {
                $subimageid = $requestInfo['images'][$key];
                $subrevid = getProductionRevisionid($subimageid);
                $compid = $requestInfo['computers'][$key];
                $mgmtnodeid = $requestInfo['mgmtnodes'][$key];
                $blockCompVals[] = "({$blockTimesid}, {$compid}, {$subimageid}, {$reqid})";
                $query = "INSERT INTO reservation " . "(requestid, " . "computerid, " . "imageid, " . "imagerevisionid, " . "managementnodeid) " . "VALUES " . "({$reqid}, " . "{$compid}, " . "{$subimageid}, " . "{$subrevid}, " . "{$mgmtnodeid})";
                doQuery($query, 101);
            }
        }
        if (count($blockCompVals)) {
            $blockComps = implode(',', $blockCompVals);
            $query = "INSERT INTO blockComputers " . "(blockTimeid, computerid, imageid, reloadrequestid) " . "VALUES {$blockComps}";
            doQuery($query);
        }
        cleanSemaphore();
    }
    # check to see if all computers have been allocated
    $query = "SELECT COUNT(computerid) AS allocated " . "FROM blockComputers " . "WHERE blockTimeid = {$blockTimesid}";
    $qh = doQuery($query, 101);
    if (!($row = mysql_fetch_assoc($qh))) {
        return array('status' => 'error', 'errorcode' => 15, 'errormsg' => 'failure to communicate with database');
    }
    $compCompleted = $row['allocated'];
    if (array_key_exists('subimages', $images[$rqdata['imageid']])) {
        $compsPerAlloc = 1 + count($images[$rqdata['imageid']]['subimages']);
    } else {
        $compsPerAlloc = 1;
    }
    $toallocate = $rqdata['numMachines'] * $compsPerAlloc - $compCompleted;
    if ($toallocate == 0) {
        if (count($blockCompVals)) {
            return array('status' => 'success', 'allocated' => $rqdata['numMachines'], 'unallocated' => 0);
        }
        return array('status' => 'completed');
    }
    $reqToAlloc = $toallocate / $compsPerAlloc;
    if (!$ignoreprivileges) {
        # get userids in user group
        if (empty($groupmembers)) {
            return array('status' => 'error', 'errorcode' => 11, 'errormsg' => 'empty user group and ignoreprivileges set to 0');
        }
        # make length of $userids match $reqToAlloc by duplicating or trimming some users
        while ($reqToAlloc > count($userids)) {
            $userids = array_merge($userids, $userids);
        }
        if ($reqToAlloc < count($userids)) {
            $userids = array_splice($userids, 0, $reqToAlloc);
        }
    }
    # staggering: stagger start times for this round (ie, do not worry about
    #   previous processing of this block time) such that there is 1 minute
    #   between the start times for each allocation
    $stagExtra = $reqToAlloc * 60;
    # determine estimated load time
    $loadtime = $imgLoadTime + 10 * 60;
    # add 10 minute fudge factor
    if (time() + $loadtime + $stagExtra > $unixstart) {
        $return['status'] = 'warning';
        $return['warningcode'] = 13;
        $return['warningmsg'] = 'possibly insufficient time to load machines';
    }
    $start = unixToDatetime($unixstart - $loadtime);
    $userid = 0;
    $allocated = 0;
    $blockCompVals = array();
    # FIXME (maybe) - if some subset of users in the user group have available
    # computers, but others do not, $allocated will be less than the desired
    # number of machines; however, calling this function enough times will
    # result in enough machines being allocated because they will continue to be
    # allocated based on the ones with machines available; this seems like odd
    # behavior
    $stagCnt = 0;
    $stagTime = 60;
    # stagger reload reservations by 1 min
    if ($imgLoadTime > 840) {
        // if estimated load time is > 14 min
        $stagTime = 120;
    }
    #    stagger reload reservations by 2 min
    for ($i = 0; $i < $reqToAlloc; $i++) {
        $stagunixstart = $unixstart - $loadtime - $stagCnt * $stagTime;
        $stagstart = unixToDatetime($stagunixstart);
        if (!$ignoreprivileges) {
            $userid = array_pop($userids);
        }
        # use end of block time to find available computers, but...
        $rc = isAvailable($images, $rqdata['imageid'], $revisionid, $stagunixstart, $unixend, 1, 0, $userid, $ignoreprivileges);
        if ($rc < 1) {
            continue;
        }
        $compid = $requestInfo['computers'][0];
        # ...use start of block time as end of reload reservation
        $reqid = simpleAddRequest($compid, $rqdata['imageid'], $revisionid, $stagstart, $rqdata['start'], 19, $vclreloadid);
        if ($reqid == 0) {
            continue;
        }
        $stagCnt++;
        $allocated++;
        $blockCompVals[] = "({$blockTimesid}, {$compid}, {$rqdata['imageid']}, {$reqid})";
        # process any subimages
        for ($key = 1; $key < count($requestInfo['computers']); $key++) {
            $subimageid = $requestInfo['images'][$key];
            $subrevid = getProductionRevisionid($subimageid);
            $compid = $requestInfo['computers'][$key];
            $mgmtnodeid = $requestInfo['mgmtnodes'][$key];
            $blockCompVals[] = "({$blockTimesid}, {$compid}, {$subimageid}, {$reqid})";
            $query = "INSERT INTO reservation " . "(requestid, " . "computerid, " . "imageid, " . "imagerevisionid, " . "managementnodeid) " . "VALUES " . "({$reqid}, " . "{$compid}, " . "{$subimageid}, " . "{$subrevid}, " . "{$mgmtnodeid})";
            doQuery($query, 101);
        }
        $blockComps = implode(',', $blockCompVals);
        $query = "INSERT INTO blockComputers " . "(blockTimeid, computerid, imageid, reloadrequestid) " . "VALUES {$blockComps}";
        doQuery($query, 101);
        cleanSemaphore();
        $blockCompVals = array();
    }
    if ($allocated == 0) {
        $return['status'] = 'warning';
        $return['warningcode'] = 14;
        $return['warningmsg'] = 'unable to allocate any machines';
    }
    $return['allocated'] = $compCompleted / $compsPerAlloc + $allocated;
    $return['unallocated'] = $rqdata['numMachines'] - $return['allocated'];
    return $return;
}