예제 #1
0
function editOrAddGroup($state)
{
    global $submitErr, $user, $mode;
    $usergroups = getUserGroups();
    $type = getContinuationVar("type");
    if ($state) {
        $isowner = 1;
    } elseif ($type == 'resource') {
        $isowner = getContinuationVar('isowner');
    }
    if (!$state) {
        $groupid = getContinuationVar('groupid', processInputVar('groupid', ARG_NUMERIC));
        if ($type == 'user') {
            if (!array_key_exists($groupid, $usergroups)) {
                print "<h2>Edit User Group</h2>\n";
                print "The selected user group does not exist.\n";
                return;
            }
            $isowner = 0;
            if ($usergroups[$groupid]['ownerid'] != $user['id']) {
                if ($usergroups[$groupid]['custom'] == 0 || $usergroups[$groupid]['courseroll'] == 1) {
                    if (!checkUserHasPerm('Manage Federated User Groups (global)') && (!checkUserHasPerm('Manage Federated User Groups (affiliation only)') || $usergroups[$groupid]['groupaffiliationid'] != $user['affiliationid'])) {
                        print "<h2>Edit User Group</h2>\n";
                        print "You do not have access to modify the selected user group.\n";
                        return;
                    } else {
                        $isowner = 1;
                    }
                } elseif (!array_key_exists("editgroupid", $usergroups[$groupid]) || !array_key_exists($usergroups[$groupid]["editgroupid"], $user["groups"])) {
                    print "<h2>Edit User Group</h2>\n";
                    print "You do not have access to modify the selected user group.\n";
                    return;
                }
            } else {
                $isowner = 1;
            }
        } else {
            $userresources = getUserResources(array("groupAdmin"), array("manageGroup"), 1);
            $noaccess = 1;
            foreach (array_keys($userresources) as $rtype) {
                if (array_key_exists($groupid, $userresources[$rtype])) {
                    $noaccess = 0;
                    break;
                }
            }
            if ($noaccess) {
                print "<h2>Edit Resource Group</h2>\n";
                print "You do not have access to modify the selected resource group.\n";
                return;
            }
        }
    }
    $allcustomgroups = getUserGroups(1);
    if ($user['showallgroups']) {
        $affilusergroups = $allcustomgroups;
    } else {
        $affilusergroups = getUserGroups(1, $user['affiliationid']);
    }
    $defaultusergroupid = getUserGroupID('Default for Editable by', 1);
    if ($type == 'resource') {
        $dispUserGrpIDs = array();
        $dispUserGrpIDsAllAffils = array();
        foreach (array_keys($allcustomgroups) as $id) {
            # figure out if user is owner or in editor group
            $owner = 0;
            $editor = 0;
            if ($allcustomgroups[$id]["ownerid"] == $user["id"]) {
                $owner = 1;
            }
            if (array_key_exists("editgroupid", $allcustomgroups[$id]) && array_key_exists($allcustomgroups[$id]["editgroupid"], $user["groups"])) {
                $editor = 1;
            }
            if (!$owner && !$editor) {
                continue;
            }
            if ($user['showallgroups']) {
                $dispUserGrpIDs[$id] = $allcustomgroups[$id]['name'];
            } elseif (array_key_exists($id, $affilusergroups) && $allcustomgroups[$id]['groupaffiliation'] == $user['affiliation']) {
                $dispUserGrpIDs[$id] = $allcustomgroups[$id]['name'];
            }
            $dispUserGrpIDsAllAffils[$id] = $allcustomgroups[$id]['name'];
        }
    }
    $resourcegroups = getResourceGroups();
    $affils = getAffiliations();
    $resourcetypes = getTypes("resources");
    if ($submitErr) {
        $data = processGroupInput(0);
        if ($mode == "submitEditGroup") {
            $id = $data["groupid"];
            if ($data["type"] == "resource") {
                list($grouptype, $junk) = explode('/', $resourcegroups[$id]["name"]);
                $ownerid = $resourcegroups[$id]["ownerid"];
            }
        } else {
            if ($data["type"] == "resource") {
                if ($state) {
                    $grouptype = $resourcetypes['resources'][$data['resourcetypeid']];
                } else {
                    list($grouptype, $junk) = explode('/', $resourcegroups[$data['groupid']]["name"]);
                }
                $ownerid = $data["ownergroup"];
            } else {
                $selectAffil = getContinuationVar('selectAffil');
                if (empty($selectAffil) && $user['showallgroups']) {
                    $selectAffil = 1;
                }
            }
        }
    } else {
        $data["groupid"] = getContinuationVar("groupid");
        $data["type"] = getContinuationVar("type");
        $data["isowner"] = $isowner;
        if (!$state) {
            $id = $groupid;
            $data['groupid'] = $id;
        } else {
            $id = $data["groupid"];
        }
        if ($data["type"] == "user") {
            if ($state) {
                $data["name"] = '';
                $data["affiliationid"] = $user['affiliationid'];
                $data["owner"] = $user['unityid'];
                if (array_key_exists('VCLEDITGROUPID', $_COOKIE) && (array_key_exists($_COOKIE['VCLEDITGROUPID'], $affilusergroups) || $_COOKIE['VCLEDITGROUPID'] == $defaultusergroupid)) {
                    $data["editgroupid"] = $_COOKIE['VCLEDITGROUPID'];
                } else {
                    $data["editgroupid"] = $defaultusergroupid;
                }
                if (!array_key_exists($data['editgroupid'], $affilusergroups)) {
                    if ($user['showallgroups']) {
                        $affil = getAffiliationName(1);
                        $affilusergroups[$data['editgroupid']]['name'] = "Default for Editable by@{$affil}";
                    } else {
                        $affilusergroups[$data['editgroupid']]['name'] = 'Default for Editable by';
                    }
                }
                $data["initialmax"] = 240;
                $data["totalmax"] = 360;
                $data["maxextend"] = 30;
                $data["overlap"] = 0;
                $data["custom"] = 1;
                $data["courseroll"] = 0;
                $tmp = explode('@', $data['name']);
                $data['name'] = $tmp[0];
                if ($user['showallgroups']) {
                    $selectAffil = 1;
                } else {
                    $selectAffil = 0;
                }
            } else {
                $data["name"] = $usergroups[$id]["name"];
                $data["affiliationid"] = $usergroups[$id]["groupaffiliationid"];
                $data["owner"] = $usergroups[$id]["owner"];
                $data["editgroupid"] = $usergroups[$id]["editgroupid"];
                $data["initialmax"] = $usergroups[$id]["initialmaxtime"];
                $data["totalmax"] = $usergroups[$id]["totalmaxtime"];
                $data["maxextend"] = $usergroups[$id]["maxextendtime"];
                $data["overlap"] = $usergroups[$id]["overlapResCount"];
                $data["custom"] = $usergroups[$id]["custom"];
                $data["courseroll"] = $usergroups[$id]["courseroll"];
                $tmp = explode('@', $data['name']);
                $data['name'] = $tmp[0];
                if ($user['showallgroups'] || array_key_exists(1, $tmp) && $tmp[1] != $user['affiliation']) {
                    $selectAffil = 1;
                } else {
                    $selectAffil = 0;
                }
            }
        } else {
            unset($affilusergroups[$defaultusergroupid]);
            if ($state) {
                $grouptype = 'computer';
                $data['name'] = '';
                if (array_key_exists('VCLOWNERGROUPID', $_COOKIE) && array_key_exists($_COOKIE['VCLOWNERGROUPID'], $user['groups'])) {
                    $ownerid = $_COOKIE['VCLOWNERGROUPID'];
                } else {
                    $ownerid = "";
                    foreach (array_keys($user["groups"]) as $grpid) {
                        if (array_key_exists($grpid, $dispUserGrpIDs)) {
                            $ownerid = $grpid;
                            break;
                        }
                    }
                }
            } else {
                list($grouptype, $data["name"]) = explode('/', $resourcegroups[$id]["name"]);
                $ownerid = $resourcegroups[$id]["ownerid"];
            }
        }
    }
    if ($data['type'] == 'user' && !array_key_exists($defaultusergroupid, $affilusergroups)) {
        if ($user['showallgroups']) {
            $affil = getAffiliationName(1);
            $affilusergroups[$defaultusergroupid]['name'] = "Default for Editable by@{$affil}";
        } else {
            $affilusergroups[$defaultusergroupid]['name'] = 'Default for Editable by';
        }
        uasort($affilusergroups, "sortKeepIndex");
    }
    $editusergroup = 0;
    if ($data['type'] != 'user') {
        print "<FORM action=\"" . BASEURL . SCRIPT . "#resources\" method=post>\n";
    } else {
        print "<FORM action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
    }
    print "<DIV align=center>\n";
    if ($state) {
        if ($data["type"] == "user") {
            print "<H2>Add User Group</H2>\n";
        } else {
            print "<H2>Add Resource Group</H2>\n";
        }
    } else {
        if ($data["type"] == "user") {
            print "<H2>Edit User Group</H2>\n";
            print "{$usergroups[$data['groupid']]['name']}<br><br>\n";
            if ($data['courseroll'] == 1) {
                print "Type: Course Roll<br><br>\n";
            } elseif ($data['custom'] == 0) {
                print "Type: Federated<br><br>\n";
            }
            $editusergroup = 1;
        } else {
            print "<H2>Edit Resource Group</H2>\n";
        }
    }
    if ($state && $data["type"] == "user" || $data["isowner"] || $data["type"] == "resource") {
        print "<TABLE>\n";
        if ($data["type"] == "resource") {
            print "  <TR>\n";
            print "    <TH align=right>Type:</TH>\n";
            print "    <TD>\n";
            if ($state && $submitErr) {
                $resourcetypeid = $data['resourcetypeid'];
            } else {
                $resourcetypeid = array_search($grouptype, $resourcetypes["resources"]);
            }
            if ($state) {
                printSelectInput("resourcetypeid", $resourcetypes["resources"], $resourcetypeid);
            } else {
                print "      {$grouptype}\n";
            }
            print "    </TD>\n";
            print "    <TD></TD>\n";
            print "  </TR>\n";
        }
        $editname = 1;
        if ($data['type'] == 'user' && $state == 0 && $usergroups[$groupid]['groupaffiliationid'] == 1) {
            $tmp = explode('@', $usergroups[$groupid]['name']);
            if ($tmp[0] == 'Specify End Time' || $tmp[0] == 'Allow No User Check' || $tmp[0] == 'Default for Editable by') {
                $editname = 0;
            }
        }
        if ($data['type'] == 'resource' || $editname && $data['courseroll'] == 0 && $data['custom'] == 1) {
            print "  <TR>\n";
            print "    <TH align=right>Name:</TH>\n";
            print "    <TD><INPUT type=text name=name value=\"{$data['name']}\" ";
            print "maxlength=30>";
            if ($data['type'] == 'user' && $selectAffil) {
                print "@";
                printSelectInput('affiliationid', $affils, $data['affiliationid']);
            }
            print "</TD>\n";
            print "    <TD>";
            printSubmitErr(GRPNAMEERR);
            print "</TD>\n";
            print "  </TR>\n";
        }
        if ($editname == 0) {
            print "<TR><TD colspan=2 align=\"center\">\n";
            print "(This is a system group whose name cannot be modified.)\n";
            print "</TD></TR>\n";
        }
        if ($data["type"] == "user") {
            if ($data['courseroll'] == 0 && $data['custom'] == 1) {
                print "  <TR>\n";
                print "    <TH align=right>Owner:</TH>\n";
                print "    <TD><INPUT type=text name=owner value=\"" . $data["owner"];
                print "\"></TD>\n";
                print "    <TD>";
                printSubmitErr(GRPOWNER);
                print "</TD>\n";
                print "  </TR>\n";
                print "  <TR>\n";
                print "    <TH align=right>Editable by:</TH>\n";
                print "    <TD valign=\"top\">\n";
                $groupwasnone = 0;
                if ($submitErr & EDITGROUPERR) {
                    if ($state == 0) {
                        $data['editgroupid'] = $usergroups[$data['groupid']]['editgroupid'];
                    } elseif (count($affilusergroups)) {
                        $tmp = array_keys($affilusergroups);
                        $data['editgroupid'] = $tmp[0];
                    }
                }
                $notice = '';
                if ($state == 0 && empty($usergroups[$data['groupid']]["editgroup"])) {
                    $affilusergroups = array_reverse($affilusergroups, TRUE);
                    $affilusergroups[0] = array('name' => 'None');
                    $affilusergroups = array_reverse($affilusergroups, TRUE);
                    $groupwasnone = 1;
                    $notice = "<strong>Note:</strong> You are the only person that can<br>" . "edit membership of this group. Select a<br>user group here " . "to allow members of that<br>group to edit membership of this one.";
                } elseif (!array_key_exists($data['editgroupid'], $affilusergroups) && $data['editgroupid'] != 0) {
                    $affilusergroups[$data['editgroupid']] = array('name' => getUserGroupName($data['editgroupid'], 1));
                    uasort($affilusergroups, "sortKeepIndex");
                }
                if ($state == 1 && $data['editgroupid'] == 0) {
                    print "None\n";
                } else {
                    printSelectInput("editgroupid", $affilusergroups, $data["editgroupid"]);
                }
                print "    </TD>\n";
                print "    <TD>";
                if ($submitErr & EDITGROUPERR) {
                    printSubmitErr(EDITGROUPERR);
                } else {
                    print $notice;
                }
                print "</TD>";
                print "  </TR>\n";
            } else {
                $groupwasnone = 1;
            }
            print "  <TR>\n";
            print "    <TH align=right>Initial Max Time:</TH>\n";
            print "    <TD>";
            $lengths = getReservationLengths(65535);
            if (!array_key_exists($data['initialmax'], $lengths)) {
                $data['initialmax'] = getReservationLengthCeiling($data['initialmax']);
            }
            printSelectInput("initialmax", $lengths, $data['initialmax']);
            print "    </TD>";
            print "    <TD>";
            printSubmitErr(INITIALMAXERR);
            print "</TD>\n";
            print "  </TR>\n";
            print "  <TR>\n";
            print "    <TH align=right>Total Max Time:</TH>\n";
            print "    <TD>";
            if (!array_key_exists($data['totalmax'], $lengths)) {
                $data['totalmax'] = getReservationLengthCeiling($data['totalmax']);
            }
            printSelectInput("totalmax", $lengths, $data['totalmax']);
            print "    </TD>\n";
            print "    <TD>";
            printSubmitErr(TOTALMAXERR);
            print "</TD>\n";
            print "  </TR>\n";
            print "  <TR>\n";
            print "    <TH align=right>Max Extend Time:</TH>\n";
            print "    <TD>";
            if (!array_key_exists($data['maxextend'], $lengths)) {
                $data['maxextend'] = getReservationLengthCeiling($data['maxextend']);
            }
            printSelectInput("maxextend", $lengths, $data['maxextend']);
            print "    </TD>\n";
            print "    <TD>";
            printSubmitErr(MAXEXTENDERR);
            print "</TD>\n";
            print "  </TR>\n";
            if (checkUserHasPerm('Set Overlapping Reservation Count')) {
                print "  <TR>\n";
                print "    <TH align=right>Max Overlapping Reservations:</TH>\n";
                print "    <TD><INPUT type=text name=overlap value=\"";
                print $data["overlap"] . "\" maxlength=4></TD>\n";
                print "    <TD>";
                printSubmitErr(MAXOVERLAPERR);
                print "</TD>\n";
                print "  </TR>\n";
            }
        } else {
            print "  <TR>\n";
            print "    <TH align=right>Owning User Group:</TH>\n";
            print "    <TD>\n";
            if ($submitErr & EDITGROUPERR) {
                $ownerid = $resourcegroups[$groupid]['ownerid'];
            }
            if ($state == 0 && $ownerid != '' && !array_key_exists($ownerid, $dispUserGrpIDs)) {
                $dispUserGrpIDs[$ownerid] = $usergroups[$ownerid]['name'];
                uasort($dispUserGrpIDs, "sortKeepIndex");
            }
            if (!empty($dispUserGrpIDs)) {
                printSelectInput("ownergroup", $dispUserGrpIDs, $ownerid);
            } else {
                printSelectInput("ownergroup", $dispUserGrpIDsAllAffils, $ownerid);
            }
            print "    </TD>\n";
            print "    <TD>\n";
            if ($submitErr & EDITGROUPERR) {
                printSubmitErr(EDITGROUPERR);
            }
            print "    </TD>\n";
            print "  </TR>\n";
        }
        print "</TABLE>\n";
        print "<TABLE>\n";
        print "  <TR valign=top>\n";
        print "    <TD>\n";
        if ($state) {
            $cdata = array('type' => $data['type']);
            if ($data['type'] == 'user') {
                $cdata['isowner'] = $data['isowner'];
                if ($data['editgroupid'] == 0) {
                    $cdata['editgroupid'] = 0;
                    $cdata['groupwasnone'] = 1;
                }
                $cdata['editgroupids'] = implode(',', array_keys($affilusergroups));
            } else {
                if (!empty($dispUserGrpIDs)) {
                    $cdata['ownergroupids'] = implode(',', array_keys($dispUserGrpIDs));
                } else {
                    $cdata['ownergroupids'] = implode(',', array_keys($dispUserGrpIDsAllAffils));
                }
            }
            $cont = addContinuationsEntry('submitAddGroup', $cdata);
            print "      <INPUT type=hidden name=continuation value=\"{$cont}\">\n";
            print "      <INPUT type=submit value=\"Add Group\">\n";
        } else {
            $cdata = array('type' => $data['type'], 'groupid' => $data['groupid'], 'isowner' => $data['isowner'], 'editname' => $editname);
            if ($data['type'] == 'resource') {
                $cdata['resourcetypeid'] = $resourcetypeid;
                if (!empty($dispUserGrpIDs)) {
                    $cdata['ownergroupids'] = implode(',', array_keys($dispUserGrpIDs));
                } else {
                    $cdata['ownergroupids'] = implode(',', array_keys($dispUserGrpIDsAllAffils));
                }
            } else {
                if ($data['courseroll'] == 1 || $data['custom'] == 0 || $editname == 0) {
                    $cdata['name'] = $data['name'];
                    $cdata['affiliationid'] = $data['affiliationid'];
                }
                $cdata['selectAffil'] = $selectAffil;
                $cdata['groupwasnone'] = $groupwasnone;
                $cdata['custom'] = $data['custom'];
                $cdata['courseroll'] = $data['courseroll'];
                $cdata['editgroupids'] = implode(',', array_keys($affilusergroups));
            }
            $cont = addContinuationsEntry('confirmEditGroup', $cdata);
            print "      <INPUT type=hidden name=continuation value=\"{$cont}\">\n";
            print "      <INPUT type=submit value=\"Confirm Changes\">\n";
        }
        print "      </FORM>\n";
        print "    </TD>\n";
        print "    <TD>\n";
        print "      <FORM action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        print "      <INPUT type=hidden name=mode value=viewGroups>\n";
        print "      <INPUT type=submit value=Cancel>\n";
        print "      </FORM>\n";
        print "    </TD>\n";
        print "  </TR>\n";
        print "</TABLE>\n";
    }
    if ($data["type"] != "user") {
        print "</DIV>\n";
        return;
    }
    if ($editusergroup) {
        $newuser = processInputVar("newuser", ARG_STRING);
        print "<H3>Group Membership</H3>\n";
        if ($mode == "addGroupUser" && !($submitErr & IDNAMEERR)) {
            print "<font color=\"#008000\">{$newuser} successfully added to group";
            print "</font><br><br>\n";
        }
        if ($mode == "deleteGroupUser") {
            print "<font color=\"#008000\">{$newuser} successfully deleted from ";
            print "group</font><br><br>\n";
        }
        $groupmembers = getUserGroupMembers($data["groupid"]);
        $edit = 1;
        if ($data['courseroll'] == 1 || $data['custom'] == 0) {
            $edit = 0;
        }
        if (empty($groupmembers) && !$edit) {
            print "(empty group)<br>\n";
        }
        print "<TABLE border=1>\n";
        if ($edit) {
            print "  <TR>\n";
            print "  <FORM action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
            print "    <TD align=right><INPUT type=submit value=Add></TD>\n";
            print "    <TD><INPUT type=text name=newuser maxlength=80 size=40 ";
            if ($submitErr & IDNAMEERR) {
                print "value=\"{$newuser}\"></TD>\n";
            } else {
                print "></TD>\n";
            }
            if ($submitErr) {
                print "    <TD>\n";
                printSubmitErr(IDNAMEERR);
                print "    </TD>\n";
            }
            $cont = addContinuationsEntry('addGroupUser', $data);
            print "  <INPUT type=hidden name=continuation value=\"{$cont}\">\n";
            print "  </FORM>\n";
            print "  </TR>\n";
        }
        foreach ($groupmembers as $id => $login) {
            print "  <TR>\n";
            if ($edit) {
                print "    <TD>\n";
                print "      <FORM action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
                print "      <INPUT type=submit value=Delete>\n";
                $data['userid'] = $id;
                $data['newuser'] = $login;
                $cont = addContinuationsEntry('deleteGroupUser', $data);
                print "      <INPUT type=hidden name=continuation value=\"{$cont}\">\n";
                print "      </FORM>\n";
                print "    </TD>\n";
            }
            print "    <TD>{$login}</TD>\n";
            print "  </TR>\n";
        }
        print "</TABLE>\n";
    }
    print "</DIV>\n";
}
예제 #2
0
function AJeditRequest()
{
    global $submitErr, $user;
    $requestid = getContinuationVar('requestid', 0);
    $request = getRequestInfo($requestid, 1);
    # check to see if reservation exists
    if (is_null($request) || $request['stateid'] == 11 || $request['stateid'] == 12 || $request['stateid'] == 14 && ($request['laststateid'] == 11 || $request['laststateid'] == 12)) {
        sendJSON(array('status' => 'resgone'));
        return;
    }
    $unixstart = datetimeToUnix($request["start"]);
    $unixend = datetimeToUnix($request["end"]);
    $duration = $unixend - $unixstart;
    $now = time();
    $maxtimes = getUserMaxTimes();
    $groupid = getUserGroupID('Specify End Time', 1);
    $members = getUserGroupMembers($groupid);
    if (array_key_exists($user['id'], $members) || $request['serverrequest']) {
        $openend = 1;
    } else {
        $openend = 0;
    }
    $groupid = getUserGroupID('Allow No User Check', 1);
    $members = getUserGroupMembers($groupid);
    if (array_key_exists($user['id'], $members)) {
        $nousercheck = 1;
    } else {
        $nousercheck = 0;
    }
    $h = '';
    # determine the current total length of the reservation
    $reslen = ($unixend - unixFloor15($unixstart)) / 60;
    $timeval = getdate($unixstart);
    if ($timeval["minutes"] % 15 != 0) {
        $reslen -= 15;
    }
    $cdata = array('requestid' => $requestid, 'openend' => $openend, 'nousercheck' => $nousercheck, 'modifystart' => 0, 'allowindefiniteend' => 0);
    # generate HTML
    if ($request['serverrequest']) {
        if (empty($request['servername'])) {
            $request['servername'] = $request['reservations'][0]['prettyimage'];
        }
        $h .= i("Name") . ": <input type=\"text\" name=\"servername\" id=\"servername\" ";
        $h .= "dojoType=\"dijit.form.TextBox\" style=\"width: 330px\" ";
        $h .= "value=\"{$request['servername']}\"><br>";
        if ($user['showallgroups']) {
            $groups = getUserGroups();
        } else {
            $groups = getUserGroups(0, $user['affiliationid']);
        }
        $h .= "<div style=\"display: table-row;\">\n";
        $h .= "<div style=\"display: table-cell;\">\n";
        $h .= i("Admin User Group") . ": ";
        $h .= "</div>\n";
        $h .= "<div style=\"display: table-cell;\">\n";
        $disabled = '';
        if ($request['stateid'] == 14 && $request['laststateid'] == 24) {
            $disabled = "disabled=\"true\"";
        }
        if (USEFILTERINGSELECT && count($groups) < FILTERINGSELECTTHRESHOLD) {
            $h .= "<select dojoType=\"dijit.form.FilteringSelect\" id=\"admingrpsel\" ";
            $h .= "{$disabled} highlightMatch=\"all\" autoComplete=\"false\">";
        } else {
            $h .= "<select id=\"admingrpsel\" {$disabled}>";
        }
        if (!empty($request['admingroupid']) && !array_key_exists($request['admingroupid'], $groups)) {
            $id = $request['admingroupid'];
            $name = getUserGroupName($request['admingroupid'], 1);
            $h .= "<option value=\"{$id}\">{$name}</option>\n";
        }
        $h .= "<option value=\"0\">" . i("None") . "</option>\n";
        foreach ($groups as $id => $group) {
            if ($id == $request['admingroupid']) {
                $h .= "<option value=\"{$id}\" selected>{$group['name']}</option>";
            } else {
                $h .= "<option value=\"{$id}\">{$group['name']}</option>";
            }
        }
        $h .= "</select><br>";
        $imageinfo = getImages(0, $request['reservations'][0]['imageid']);
        if ($imageinfo[$request['reservations'][0]['imageid']]['rootaccess'] == 0) {
            $h .= "<div style=\"width: 240px; margin: 3px 0 3px 0; padding: 1px; border: 1px solid;\">";
            $h .= i("Administrative access has been disabled for this image. Users in the Admin User Group will have control of the reservaion on the Reservations page but will not have administrative access within the reservation.");
            $h .= "</div>\n";
        }
        $h .= "</div>\n";
        $h .= "</div>\n";
        $h .= i("Access User Group") . ": ";
        if (USEFILTERINGSELECT && count($groups) < FILTERINGSELECTTHRESHOLD) {
            $h .= "<select dojoType=\"dijit.form.FilteringSelect\" id=\"logingrpsel\" ";
            $h .= "{$disabled} highlightMatch=\"all\" autoComplete=\"false\">";
        } else {
            $h .= "<select id=\"logingrpsel\" {$disabled}>";
        }
        if (!empty($request['logingroupid']) && !array_key_exists($request['logingroupid'], $groups)) {
            $id = $request['logingroupid'];
            $name = getUserGroupName($request['logingroupid'], 1);
            $h .= "<option value=\"{$id}\">{$name}</option>\n";
        }
        $h .= "<option value=\"0\">None</option>\n";
        foreach ($groups as $id => $group) {
            if ($id == $request['logingroupid']) {
                $h .= "<option value=\"{$id}\" selected>{$group['name']}</option>";
            } else {
                $h .= "<option value=\"{$id}\">{$group['name']}</option>";
            }
        }
        $h .= "</select><br><br>";
    } elseif ($nousercheck) {
        $extra = array();
        if ($request['checkuser'] == 0) {
            $extra['checked'] = 'checked';
        }
        $h .= labeledFormItem('newnousercheck', i('Disable timeout for disconnected users'), 'check', '', '', '1', '', '', $extra);
        $h .= "<br>\n";
    }
    // if future, allow start to be modified
    if ($unixstart > $now) {
        $cdata['modifystart'] = 1;
        $txt = i("Modify reservation for") . " <b>{$request['reservations'][0]['prettyimage']}</b> ";
        $txt .= i("starting") . " " . prettyDatetime($request["start"]) . ": <br>";
        $h .= preg_replace("/(.{1,60}([ \n]|\$))/", '\\1<br>', $txt);
        $days = array();
        $startday = date('l', $unixstart);
        for ($cur = time(), $end = $cur + DAYSAHEAD * SECINDAY; $cur < $end; $cur += SECINDAY) {
            $index = date('Ymd', $cur);
            $days[$index] = date('l', $cur);
        }
        $cdata['startdays'] = array_keys($days);
        $h .= i("Start") . ": <select dojoType=\"dijit.form.Select\" id=\"day\" ";
        $h .= "onChange=\"resetEditResBtn();\">";
        foreach ($days as $id => $name) {
            if ($name == $startday) {
                $h .= "<option value=\"{$id}\" selected=\"selected\">{$name}</option>";
            } else {
                $h .= "<option value=\"{$id}\">{$name}</option>";
            }
        }
        $h .= "</select>";
        $h .= i("&nbsp;At&nbsp;");
        $tmp = explode(' ', $request['start']);
        $stime = $tmp[1];
        $h .= "<div type=\"text\" dojoType=\"dijit.form.TimeTextBox\" ";
        $h .= "id=\"editstarttime\" style=\"width: 78px\" value=\"T{$stime}\" ";
        $h .= "onChange=\"resetEditResBtn();\"></div>";
        $h .= "<small>(" . date('T') . ")</small><br><br>";
        $durationmatch = 0;
        if ($request['serverrequest']) {
            $cdata['allowindefiniteend'] = 1;
            if ($request['end'] == '2038-01-01 00:00:00') {
                $h .= "<INPUT type=\"radio\" name=\"ending\" id=\"indefiniteradio\" ";
                $h .= "checked onChange=\"resetEditResBtn();\">";
            } else {
                $h .= "<INPUT type=\"radio\" name=\"ending\" id=\"indefiniteradio\" ";
                $h .= "onChange=\"resetEditResBtn();\">";
            }
            $h .= "<label for=\"indefiniteradio\">" . i("Indefinite Ending") . "</label>";
        } else {
            $durationmin = $duration / 60;
            if ($request['forimaging'] && $maxtimes['initial'] < 720) {
                # make sure at least 12 hours available for imaging reservations
                $maxtimes['initial'] = 720;
            }
            $imgdata = getImages(1, $request['reservations'][0]['imageid']);
            $maxlen = $imgdata[$request['reservations'][0]['imageid']]['maxinitialtime'];
            if ($maxlen > 0 && $maxlen < $maxtimes['initial']) {
                $maxtimes['initial'] = $maxlen;
            }
            $lengths = array();
            if ($maxtimes["initial"] >= 30) {
                $lengths["30"] = "30 " . i("minutes");
                if ($durationmin == 30) {
                    $durationmatch = 1;
                }
            }
            if ($maxtimes["initial"] >= 45) {
                $lengths["45"] = "45 " . i("minutes");
                if ($durationmin == 45) {
                    $durationmatch = 1;
                }
            }
            if ($maxtimes["initial"] >= 60) {
                $lengths["60"] = "1 " . i("hour");
                if ($durationmin == 60) {
                    $durationmatch = 1;
                }
            }
            for ($i = 120; $i <= $maxtimes["initial"] && $i < 2880; $i += 120) {
                $lengths[$i] = $i / 60 . " " . i("hours");
                if ($durationmin == $i) {
                    $durationmatch = 1;
                }
            }
            for ($i = 2880; $i <= $maxtimes["initial"]; $i += 1440) {
                $lengths[$i] = $i / 1440 . " " . i("days");
                if ($durationmin == $i) {
                    $durationmatch = 1;
                }
            }
            if ($openend) {
                if ($durationmatch) {
                    $h .= "<INPUT type=\"radio\" name=\"ending\" id=\"lengthradio\" ";
                    $h .= "onChange=\"resetEditResBtn();\" checked>";
                } else {
                    $h .= "<INPUT type=\"radio\" name=\"ending\" id=\"lengthradio\" ";
                    $h .= "onChange=\"resetEditResBtn();\">";
                }
                $h .= "<label for=\"lengthradio\">";
            }
            $h .= i("Duration") . ':';
            if ($openend) {
                $h .= "</label>";
            }
            $h .= "<select dojoType=\"dijit.form.Select\" id=\"length\" ";
            $h .= "onChange=\"selectLength();\">";
            $cdata['lengths'] = array_keys($lengths);
            foreach ($lengths as $id => $name) {
                if ($id == $duration / 60) {
                    $h .= "<option value=\"{$id}\" selected=\"selected\">{$name}</option>";
                } else {
                    $h .= "<option value=\"{$id}\">{$name}</option>";
                }
            }
            $h .= "</select>";
        }
        if ($openend) {
            if ($request['serverrequest'] && $request['end'] == '2038-01-01 00:00:00') {
                $h .= "<br><INPUT type=\"radio\" name=\"ending\" id=\"dateradio\" ";
                $h .= "onChange=\"resetEditResBtn();\">";
                $edate = '';
                $etime = '';
            } else {
                if (!$request['serverrequest'] && $durationmatch) {
                    $h .= "<br><INPUT type=\"radio\" name=\"ending\" id=\"dateradio\" ";
                    $h .= "onChange=\"resetEditResBtn();\">";
                } else {
                    $h .= "<br><INPUT type=\"radio\" name=\"ending\" id=\"dateradio\" ";
                    $h .= "checked onChange=\"resetEditResBtn();\">";
                }
                $tmp = explode(' ', $request['end']);
                $edate = $tmp[0];
                $etime = $tmp[1];
            }
            $h .= "<label for=\"dateradio\">";
            $h .= i("End:");
            $h .= "</label>";
            $h .= "<div type=\"text\" dojoType=\"dijit.form.DateTextBox\" ";
            $h .= "id=\"openenddate\" style=\"width: 78px\" value=\"{$edate}\" ";
            $h .= "onChange=\"selectEnding();\"></div>";
            $h .= "<div type=\"text\" dojoType=\"dijit.form.TimeTextBox\" ";
            $h .= "id=\"openendtime\" style=\"width: 78px\" value=\"T{$etime}\" ";
            $h .= "onChange=\"selectEnding();\"></div>";
            $h .= "<small>(" . date('T') . ")</small>";
        }
        $h .= "<br><br>";
        $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
        $data = array('status' => 'modify', 'html' => $h, 'requestid' => $requestid, 'cont' => $cont);
        sendJSON($data);
        return;
    }
    # check for max time being reached
    if ($request['forimaging'] && $maxtimes['total'] < 720) {
        $maxcheck = 720;
    } else {
        $maxcheck = $maxtimes['total'];
    }
    if (!$openend && $reslen >= $maxcheck) {
        $h = sprintf(i("You are only allowed to extend your reservation such that it has a total length of %s. "), minToHourMin($maxcheck));
        $h .= i("This reservation already meets that length. Therefore, you are not allowed to extend your reservation any further.");
        $h = preg_replace("/(.{1,60}([ \n]|\$))/", '\\1<br>', $h) . "<br>";
        sendJSON(array('status' => 'nomodify', 'html' => $h));
        return;
    }
    // if started, only allow end to be modified
    # check for following reservations
    $timeToNext = timeToNextReservation($request);
    # check for 30 minutes because need 15 minute buffer and min can
    # extend by is 15 min
    if ($timeToNext < 30) {
        $movedall = 1;
        $lockedall = 1;
        if (count($request['reservations']) > 1) {
            # get semaphore on each existing node in cluster so that nothing
            # can get moved to the nodes during this process
            $resources = getUserResources(array("imageAdmin", "imageCheckOut"));
            $tmp = array_keys($resources['image']);
            $semimageid = $tmp[0];
            $semrevid = getProductionRevisionid($semimageid);
            $checkend = unixToDatetime($unixend + 900);
            foreach ($request["reservations"] as $res) {
                if (!retryGetSemaphore($semimageid, $semrevid, $res['managementnodeid'], $res['computerid'], $request['start'], $checkend, $requestid)) {
                    $lockedall = 0;
                    break;
                }
            }
        }
        if ($lockedall) {
            foreach ($request["reservations"] as $res) {
                if (!moveReservationsOffComputer($res["computerid"], 1)) {
                    $movedall = 0;
                    break;
                }
            }
        }
        cleanSemaphore();
        if (!$request['serverrequest'] && (!$movedall || !$lockedall)) {
            $msg = i("The computer you are using has another reservation immediately following yours. Therefore, you cannot extend your reservation because it would overlap with the next one.");
            $h = preg_replace("/(.{1,60}( |\$))/", '\\1<br>', $msg) . "<br>";
            sendJSON(array('status' => 'nomodify', 'html' => $h));
            return;
        }
        $timeToNext = timeToNextReservation($request);
    }
    if ($timeToNext >= 15) {
        $timeToNext -= 15;
    }
    //if have time left to extend it, create an array of lengths based on maxextend that has a cap
    # so we don't run into another reservation and we can't extend past the totalmax
    $lengths = array();
    if ($request['forimaging'] && $maxtimes['total'] < 720) {
        # make sure at least 12 hours available for imaging reservations
        $maxtimes['total'] = 720;
    }
    if ($timeToNext == -1) {
        // there is no following reservation
        if ($reslen + 15 <= $maxtimes["total"] && 15 <= $maxtimes["extend"]) {
            $lengths["15"] = "15 " . i("minutes");
        }
        if ($reslen + 30 <= $maxtimes["total"] && 30 <= $maxtimes["extend"]) {
            $lengths["30"] = "30 " . i("minutes");
        }
        if ($reslen + 45 <= $maxtimes["total"] && 45 <= $maxtimes["extend"]) {
            $lengths["45"] = "45 " . i("minutes");
        }
        if ($reslen + 60 <= $maxtimes["total"] && 60 <= $maxtimes["extend"]) {
            $lengths["60"] = i("1 hour");
        }
        for ($i = 120; $reslen + $i <= $maxtimes["total"] && $i <= $maxtimes["extend"] && $i < 2880; $i += 120) {
            $lengths[$i] = $i / 60 . " " . i("hours");
        }
        for ($i = 2880; $reslen + $i <= $maxtimes["total"] && $i <= $maxtimes["extend"]; $i += 1440) {
            $lengths[$i] = $i / 1440 . " " . i("days");
        }
    } else {
        if ($timeToNext >= 15 && $reslen + 15 <= $maxtimes["total"] && 15 <= $maxtimes["extend"]) {
            $lengths["15"] = "15 " . i("minutes");
        }
        if ($timeToNext >= 30 && $reslen + 30 <= $maxtimes["total"] && 30 <= $maxtimes["extend"]) {
            $lengths["30"] = "30 " . i("minutes");
        }
        if ($timeToNext >= 45 && $reslen + 45 <= $maxtimes["total"] && 45 <= $maxtimes["extend"]) {
            $lengths["45"] = "45 " . i("minutes");
        }
        if ($timeToNext >= 60 && $reslen + 60 <= $maxtimes["total"] && 60 <= $maxtimes["extend"]) {
            $lengths["60"] = i("1 hour");
        }
        for ($i = 120; $i <= $timeToNext && $reslen + $i <= $maxtimes["total"] && $i <= $maxtimes["extend"] && $i < 2880; $i += 120) {
            $lengths[$i] = $i / 60 . " " . i("hours");
        }
        for ($i = 2880; $i <= $timeToNext && $reslen + $i <= $maxtimes["total"] && $i <= $maxtimes["extend"]; $i += 1440) {
            $lengths[$i] = $i / 1440 . " " . i("days");
        }
    }
    $cdata['lengths'] = array_keys($lengths);
    if ($timeToNext == -1 || $timeToNext >= $maxtimes['total']) {
        if ($openend) {
            if (!empty($lengths)) {
                $m = i("You can extend this reservation by a selected amount or change the end time to a specified date and time.");
                $h .= preg_replace("/(.{1,55}([ \n]|\$))/", '\\1<br>', $m) . "<br>";
            } else {
                $h .= i("Modify the end time for this reservation:") . "<br><br>";
            }
        } else {
            if ($request['forimaging'] && $maxtimes['total'] < 720) {
                $maxcheck = 720;
            } else {
                $maxcheck = $maxtimes['total'];
            }
            $m = sprintf(i("You can extend this reservation by up to %s but not exceeding %s for your total reservation time."), minToHourMin($maxtimes['extend']), minToHourMin($maxcheck));
            $h .= preg_replace("/(.{1,60}([ \n]|\$))/", '\\1<br>', $m) . "<br>";
        }
    } elseif (!$request['serverrequest']) {
        $m = sprintf(i("The computer you are using has another reservation following yours. Therefore, you can only extend this reservation for another %s."), prettyLength($timeToNext));
        $h .= preg_replace("/(.{1,60}( |\$))/", '\\1<br>', $m);
    }
    # extend by drop down
    # extend by specifying end time if $openend
    $noindefinite = 0;
    if ($openend) {
        if ($request['serverrequest']) {
            $cdata['allowindefiniteend'] = 1;
            $endchecked = 0;
            if ($request['end'] == '2038-01-01 00:00:00') {
                $h .= "<INPUT type=\"radio\" name=\"ending\" id=\"indefiniteradio\" ";
                $h .= "checked onChange=\"resetEditResBtn();\">";
                $h .= "<label for=\"indefiniteradio\">" . i("Indefinite Ending") . "</label>";
                $h .= "<br><INPUT type=\"radio\" name=\"ending\" id=\"dateradio\" ";
                $h .= "onChange=\"resetEditResBtn();\">";
            } else {
                $h .= "<INPUT type=\"radio\" name=\"ending\" id=\"indefiniteradio\" ";
                $h .= "onChange=\"resetEditResBtn();\">";
                $h .= "<label id=\"indefinitelabel\" for=\"indefiniteradio\">";
                $h .= i("Indefinite Ending") . "</label>";
                $h .= "<br><INPUT type=\"radio\" name=\"ending\" id=\"dateradio\" ";
                $h .= "checked onChange=\"resetEditResBtn();\">";
                $endchecked = 1;
            }
            $h .= "<label for=\"dateradio\">";
        } elseif (!empty($lengths)) {
            $h .= "<INPUT type=\"radio\" name=\"ending\" id=\"lengthradio\" ";
            $h .= "checked onChange=\"resetEditResBtn();\">";
            $h .= "<label for=\"lengthradio\">" . i("Extend reservation by:") . "</label>";
            $h .= "<select dojoType=\"dijit.form.Select\" id=\"length\" ";
            $h .= "onChange=\"selectLength();\" maxHeight=\"250\">";
            foreach ($lengths as $id => $name) {
                $h .= "<option value=\"{$id}\">{$name}</option>";
            }
            $h .= "</select>";
            $h .= "<br><INPUT type=\"radio\" name=\"ending\" id=\"dateradio\" ";
            $h .= "onChange=\"resetEditResBtn();\">";
            $h .= "<label for=\"dateradio\">";
        }
        if ($request['serverrequest']) {
            $h .= i("End:");
            if ($endchecked) {
                $tmp = explode(' ', $request['end']);
                $edate = $tmp[0];
                $etime = $tmp[1];
            } else {
                $edate = '';
                $etime = '';
            }
        } else {
            $h .= i("Change ending to:");
            $tmp = explode(' ', $request['end']);
            $edate = $tmp[0];
            $etime = $tmp[1];
        }
        if (!empty($lengths) || $request['serverrequest']) {
            $h .= "</label>";
        }
        $h .= "<div type=\"text\" dojoType=\"dijit.form.DateTextBox\" ";
        $h .= "id=\"openenddate\" style=\"width: 78px\" value=\"{$edate}\" ";
        $h .= "onChange=\"selectEnding();\"></div>";
        $h .= "<div type=\"text\" dojoType=\"dijit.form.TimeTextBox\" ";
        $h .= "id=\"openendtime\" style=\"width: 78px\" value=\"T{$etime}\" ";
        $h .= "onChange=\"selectEnding();\"></div>";
        $h .= "<small>(" . date('T') . ")</small>";
        $h .= "<INPUT type=\"hidden\" name=\"enddate\" id=\"enddate\">";
        if ($request['serverrequest'] && $timeToNext == 0) {
            $h .= "<br><br><font color=red>";
            $m = "<strong>" . i("NOTE:") . "</strong> ";
            $m .= i("Due to an upcoming reservation on the same computer, you cannot extend this reservation.");
            $h .= preg_replace("/(.{1,80}([ \n]|\$))/", '\\1<br>', $m);
            $h .= "</font>";
            $noindefinite = 1;
        } elseif ($timeToNext > -1) {
            $extend = $unixend + $timeToNext * 60;
            $extend = date('m/d/Y g:i A', $extend);
            $h .= "<br><br><font color=red>";
            $m = "<strong>" . i("NOTE:") . "</strong> ";
            $m .= sprintf(i("Due to an upcoming reservation on the same computer, you can only extend this reservation until %s."), $extend);
            $h .= preg_replace("/(.{1,80}([ \n]|\$))/", '\\1<br>', $m);
            $h .= "</font>";
            $cdata['maxextend'] = $extend;
            $noindefinite = 1;
        }
    } else {
        $h .= i("Extend reservation by:");
        $h .= "<select dojoType=\"dijit.form.Select\" id=\"length\">";
        foreach ($lengths as $id => $name) {
            $h .= "<option value=\"{$id}\">{$name}</option>";
        }
        $h .= "</select>";
    }
    $h .= "<br>";
    $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
    $data = array('status' => 'modify', 'html' => $h, 'requestid' => $requestid, 'cont' => $cont);
    if ($noindefinite) {
        $data['status'] = 'noindefinite';
    }
    sendJSON($data);
    return;
}
예제 #3
0
function printReserveItems($modifystart = 1, $day = NULL, $hour = NULL, $minute = NULL, $meridian = NULL, $length = 60, $oneline = 0, $nolength = 0)
{
    global $user;
    $enddate = processInputVar("enddate", ARG_STRING);
    $groupid = getUserGroupID('Specify End Time', 1);
    $members = getUserGroupMembers($groupid);
    if (array_key_exists($user['id'], $members)) {
        $openend = 1;
    } else {
        $openend = 0;
    }
    $days = array();
    $inputday = "";
    for ($cur = time(), $end = $cur + DAYSAHEAD * SECINDAY; $cur < $end; $cur += SECINDAY) {
        $tmp = getdate($cur);
        $index = $tmp["mon"] . "/" . $tmp["mday"] . "/" . $tmp["year"];
        $days[$index] = $tmp["weekday"];
        if ($tmp["weekday"] == $day) {
            $inputday = $index;
        }
    }
    if ($modifystart) {
        printSelectInput("day", $days, $inputday);
        print "&nbsp;At&nbsp;\n";
        $tmpArr = array();
        for ($i = 1; $i < 13; $i++) {
            $tmpArr[$i] = $i;
        }
        printSelectInput("hour", $tmpArr, $hour);
        $minutes = array("zero" => "00", "15" => "15", "30" => "30", "45" => "45");
        printSelectInput("minute", $minutes, $minute);
        printSelectInput("meridian", array("am" => "a.m.", "pm" => "p.m."), $meridian);
        print "<small>(Eastern Time Zone)</small>";
        //if(! $oneline)
        print "<br><br>";
        /*else
        		print "&nbsp;&nbsp;";*/
        if (!$nolength) {
            if ($openend) {
                print "&nbsp;&nbsp;&nbsp;<INPUT type=radio name=ending ";
                print "onclick='updateWaitTime(0);' value=length checked>";
            }
            print "Duration:&nbsp;\n";
        }
    } else {
        print "<INPUT type=hidden name=day value={$inputday}>\n";
        print "<INPUT type=hidden name=hour value={$hour}>\n";
        print "<INPUT type=hidden name=minute value={$minute}>\n";
        print "<INPUT type=hidden name=meridian value={$meridian}>\n";
    }
    // check for a "now" reservation that got 15 min added to it
    if ($length % 30) {
        $length -= 15;
    }
    // if ! $modifystart, we return at this point because we don't
    # know enough about the current reservation to determine how
    # long they can extend it for, the calling function would have
    # to determine that and print a length dropdown box
    if (!$modifystart) {
        return;
    }
    # create an array of usage times based on the user's max times
    $maxtimes = getUserMaxTimes("initialmaxtime");
    $lengths = array();
    if ($maxtimes["initial"] >= 30) {
        $lengths["30"] = "30 minutes";
    }
    if ($maxtimes["initial"] >= 60) {
        $lengths["60"] = "1 hour";
    }
    for ($i = 120; $i <= $maxtimes["initial"]; $i += 120) {
        $lengths[$i] = $i / 60 . " hours";
    }
    if ($nolength) {
        print "Reservation will be for 8 hours<br>\n";
    } else {
        printSelectInput("length", $lengths, $length, 0, 0, 'reqlength', "onChange='updateWaitTime(0);'");
        print "<br>\n";
        if ($openend) {
            print "&nbsp;&nbsp;&nbsp;<INPUT type=radio name=ending id=openend ";
            print "onclick='updateWaitTime(0);' value=date>Until\n";
            print "<INPUT type=text name=enddate size=20 value=\"{$enddate}\">(YYYY-MM-DD HH:MM:SS)\n";
            printSubmitErr(ENDDATEERR);
            print "<br>\n";
        }
    }
}
예제 #4
0
파일: groups.php 프로젝트: gw-acadtech/VCL
function editOrAddGroup($state)
{
    global $submitErr, $user, $mode, $viewmode;
    $usergroups = getUserGroups(1);
    if ($user['showallgroups']) {
        $affilusergroups = $usergroups;
    } else {
        $affilusergroups = getUserGroups(1, $user['affiliationid']);
    }
    $resourcegroups = getResourceGroups();
    $affils = getAffiliations();
    $resourcetypes = getTypes("resources");
    if ($submitErr) {
        $data = processGroupInput(0);
        $newuser = processInputVar("newuser", ARG_STRING);
        if ($mode == "submitEditGroup") {
            $id = $data["groupid"];
            if ($data["type"] == "resource") {
                list($grouptype, $junk) = explode('/', $resourcegroups[$id]["name"]);
                $ownerid = $resourcegroups[$id]["ownerid"];
            }
        } else {
            if ($data["type"] == "resource") {
                if ($state) {
                    $grouptype = $resourcetypes['resources'][$data['resourcetypeid']];
                } else {
                    list($grouptype, $junk) = explode('/', $resourcegroups[$data['groupid']]["name"]);
                }
                $ownerid = $data["ownergroup"];
            } else {
                $selectAffil = getContinuationVar('selectAffil');
                if (empty($selectAffil) && $user['showallgroups']) {
                    $selectAffil = 1;
                }
            }
        }
    } else {
        $newuser = processInputVar("newuser", ARG_STRING);
        $data["groupid"] = getContinuationVar("groupid");
        $data["type"] = getContinuationVar("type");
        $data["isowner"] = getContinuationVar("isowner");
        $id = $data["groupid"];
        if ($data["type"] == "user") {
            $data["name"] = $usergroups[$id]["name"];
            $data["affiliationid"] = $usergroups[$id]["groupaffiliationid"];
            $data["owner"] = $usergroups[$id]["owner"];
            $data["editgroupid"] = $usergroups[$id]["editgroupid"];
            $data["initialmax"] = $usergroups[$id]["initialmaxtime"];
            $data["totalmax"] = $usergroups[$id]["totalmaxtime"];
            $data["maxextend"] = $usergroups[$id]["maxextendtime"];
            $data["overlap"] = $usergroups[$id]["overlapResCount"];
            $tmp = explode('@', $data['name']);
            $data['name'] = $tmp[0];
            if ($user['showallgroups'] || array_key_exists(1, $tmp) && $tmp[1] != $user['affiliation']) {
                $selectAffil = 1;
            } else {
                $selectAffil = 0;
            }
        } else {
            list($grouptype, $data["name"]) = explode('/', $resourcegroups[$id]["name"]);
            $ownerid = $resourcegroups[$id]["ownerid"];
        }
    }
    $editusergroup = 0;
    if ($data['type'] != 'user') {
        print "<FORM action=\"" . BASEURL . SCRIPT . "#resources\" method=post>\n";
    } else {
        print "<FORM action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
    }
    print "<DIV align=center>\n";
    if ($state) {
        if ($data["type"] == "user") {
            print "<H2>Add User Group</H2>\n";
        } else {
            print "<H2>Add Resource Group</H2>\n";
        }
    } else {
        if ($data["type"] == "user") {
            print "<H2>Edit User Group</H2>\n";
            print "{$usergroups[$data['groupid']]['name']}<br>\n";
            $editusergroup = 1;
        } else {
            print "<H2>Edit Resource Group</H2>\n";
        }
    }
    if ($state && $data["type"] == "user" || $data["isowner"] || $data["type"] == "resource") {
        print "<TABLE>\n";
        if ($data["type"] == "resource") {
            print "  <TR>\n";
            print "    <TH align=right>Type:</TH>\n";
            print "    <TD>\n";
            if ($state && $submitErr) {
                $resourcetypeid = $data['resourcetypeid'];
            } else {
                $resourcetypeid = array_search($grouptype, $resourcetypes["resources"]);
            }
            if ($state) {
                printSelectInput("resourcetypeid", $resourcetypes["resources"], $resourcetypeid);
            } else {
                print "      {$grouptype}\n";
            }
            print "    </TD>\n";
            print "    <TD></TD>\n";
            print "  </TR>\n";
        }
        print "  <TR>\n";
        print "    <TH align=right>Name:</TH>\n";
        print "    <TD><INPUT type=text name=name value=\"{$data['name']}\" ";
        print "maxlength=30>";
        if ($data['type'] == 'user' && $selectAffil) {
            print "@";
            printSelectInput('affiliationid', $affils, $data['affiliationid']);
        }
        print "</TD>\n";
        print "    <TD>";
        printSubmitErr(GRPNAMEERR);
        print "</TD>\n";
        print "  </TR>\n";
        if ($data["type"] == "user") {
            print "  <TR>\n";
            print "    <TH align=right>Owner:</TH>\n";
            print "    <TD><INPUT type=text name=owner value=\"" . $data["owner"];
            print "\"></TD>\n";
            print "    <TD>";
            printSubmitErr(GRPOWNER);
            print "</TD>\n";
            print "  </TR>\n";
            print "  <TR>\n";
            print "    <TH align=right>Editable by:</TH>\n";
            print "    <TD>\n";
            if (!empty($data['editgroupid']) && !array_key_exists($data['editgroupid'], $affilusergroups)) {
                $affilusergroups[$data['editgroupid']] = array('name' => getUserGroupName($data['editgroupid'], 1));
                uasort($affilusergroups, "sortKeepIndex");
            }
            printSelectInput("editgroupid", $affilusergroups, $data["editgroupid"]);
            print "    </TD>\n";
            print "    <TD></TD>";
            print "  </TR>\n";
            print "  <TR>\n";
            print "    <TH align=right>Initial Max Time (minutes):</TH>\n";
            print "    <TD><INPUT type=text name=initialmax value=\"";
            print $data["initialmax"] . "\" maxlength=4></TD>\n";
            print "    <TD>";
            printSubmitErr(INITIALMAXERR);
            print "</TD>\n";
            print "  </TR>\n";
            print "  <TR>\n";
            print "    <TH align=right>Total Max Time (minutes):</TH>\n";
            print "    <TD><INPUT type=text name=totalmax value=\"";
            print $data["totalmax"] . "\" maxlength=4></TD>\n";
            print "    <TD>";
            printSubmitErr(TOTALMAXERR);
            print "</TD>\n";
            print "  </TR>\n";
            print "  <TR>\n";
            print "    <TH align=right>Max Extend Time (minutes):</TH>\n";
            print "    <TD><INPUT type=text name=maxextend value=\"";
            print $data["maxextend"] . "\" maxlength=4></TD>\n";
            print "    <TD>";
            printSubmitErr(MAXEXTENDERR);
            print "</TD>\n";
            print "  </TR>\n";
            if ($viewmode == ADMIN_DEVELOPER) {
                print "  <TR>\n";
                print "    <TH align=right>Max Overlapping Reservations:</TH>\n";
                print "    <TD><INPUT type=text name=overlap value=\"";
                print $data["overlap"] . "\" maxlength=4></TD>\n";
                print "    <TD>";
                printSubmitErr(MAXOVERLAPERR);
                print "</TD>\n";
                print "  </TR>\n";
            }
        } else {
            print "  <TR>\n";
            print "    <TH align=right>Owning User Group:</TH>\n";
            print "    <TD>\n";
            if (!array_key_exists($ownerid, $affilusergroups)) {
                $affilusergroups[$ownerid] = $usergroups[$ownerid];
                uasort($affilusergroups, "sortKeepIndex");
            }
            printSelectInput("ownergroup", $affilusergroups, $ownerid);
            print "    </TD>\n";
            print "    <TD></TD>\n";
            print "  </TR>\n";
        }
        print "</TABLE>\n";
        print "<TABLE>\n";
        print "  <TR valign=top>\n";
        print "    <TD>\n";
        if ($state) {
            $cdata = array('type' => $data['type'], 'isowner' => $data['isowner']);
            $cont = addContinuationsEntry('submitAddGroup', $cdata);
            print "      <INPUT type=hidden name=continuation value=\"{$cont}\">\n";
            print "      <INPUT type=submit value=\"Add Group\">\n";
        } else {
            $cdata = array('type' => $data['type'], 'groupid' => $data['groupid'], 'isowner' => $data['isowner']);
            if ($data['type'] == 'resource') {
                $cdata['resourcetypeid'] = $resourcetypeid;
            } else {
                $cdata['selectAffil'] = $selectAffil;
            }
            $cont = addContinuationsEntry('confirmEditGroup', $cdata);
            print "      <INPUT type=hidden name=continuation value=\"{$cont}\">\n";
            print "      <INPUT type=submit value=\"Confirm Changes\">\n";
        }
        print "      </FORM>\n";
        print "    </TD>\n";
        print "    <TD>\n";
        print "      <FORM action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        print "      <INPUT type=hidden name=mode value=viewGroups>\n";
        print "      <INPUT type=submit value=Cancel>\n";
        print "      </FORM>\n";
        print "    </TD>\n";
        print "  </TR>\n";
        print "</TABLE>\n";
    }
    if ($data["type"] != "user") {
        return;
    }
    if ($editusergroup) {
        print "<H3>Group Membership</H3>\n";
        if ($mode == "addGroupUser" && !($submitErr & IDNAMEERR)) {
            print "<font color=\"#008000\">{$newuser} successfully added to group";
            print "</font><br><br>\n";
        }
        if ($mode == "deleteGroupUser") {
            print "<font color=\"#008000\">{$newuser} successfully deleted from ";
            print "group</font><br><br>\n";
        }
        $groupmembers = getUserGroupMembers($data["groupid"]);
        print "<TABLE border=1>\n";
        print "  <TR>\n";
        print "  <FORM action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
        print "    <TD align=right><INPUT type=submit value=Add></TD>\n";
        print "    <TD><INPUT type=text name=newuser maxlength=80 size=40 ";
        if ($submitErr & IDNAMEERR) {
            print "value=\"{$newuser}\"></TD>\n";
        } else {
            print "></TD>\n";
        }
        if ($submitErr) {
            print "    <TD>\n";
            printSubmitErr(IDNAMEERR);
            print "    </TD>\n";
        }
        $cont = addContinuationsEntry('addGroupUser', $data);
        print "  <INPUT type=hidden name=continuation value=\"{$cont}\">\n";
        print "  </FORM>\n";
        print "  </TR>\n";
        foreach ($groupmembers as $id => $login) {
            print "  <TR>\n";
            print "    <TD>\n";
            print "      <FORM action=\"" . BASEURL . SCRIPT . "\" method=post>\n";
            print "      <INPUT type=submit value=Delete>\n";
            $data['userid'] = $id;
            $data['newuser'] = $login;
            $cont = addContinuationsEntry('deleteGroupUser', $data);
            print "      <INPUT type=hidden name=continuation value=\"{$cont}\">\n";
            print "      </FORM>\n";
            print "    </TD>\n";
            print "    <TD>{$login}</TD>\n";
            print "  </TR>\n";
        }
        print "</TABLE>\n";
    }
}
예제 #5
0
function jsonGetUserGroupMembers()
{
    global $user;
    $usergrpid = processInputVar('groupid', ARG_NUMERIC);
    $domid = processInputVar('domid', ARG_STRING);
    $query = "SELECT g.ownerid, " . "g.affiliationid, " . "g.custom, " . "g.courseroll, " . "g2.name AS editgroup, " . "g2.editusergroupid AS editgroupid " . "FROM usergroup g " . "LEFT JOIN usergroup g2 ON (g.editusergroupid = g2.id) " . "WHERE g.id = {$usergrpid}";
    $qh = doQuery($query, 101);
    if (!($grpdata = mysql_fetch_assoc($qh))) {
        # problem getting group members
        $msg = 'failed to fetch group members';
        $arr = array('members' => $msg, 'domid' => $domid);
        sendJSON($arr);
        return;
    }
    if ($grpdata['custom'] == 1 && $user['id'] != $grpdata['ownerid'] && !array_key_exists($grpdata['editgroupid'], $user['groups']) || ($grpdata['custom'] == 0 || $grpdata['courseroll'] == 1) && !checkUserHasPerm('Manage Federated User Groups (global)') && (!checkUserHasPerm('Manage Federated User Groups (affiliation only)') || $grpdata['affiliationid'] != $user['affiliationid'])) {
        # user doesn't have access to view membership
        $msg = '(not authorized to view membership)';
        $arr = array('members' => $msg, 'domid' => $domid);
        sendJSON($arr);
        return;
    }
    $grpmembers = getUserGroupMembers($usergrpid);
    $members = '';
    foreach ($grpmembers as $group) {
        $members .= "{$group}<br>";
    }
    if ($members == '') {
        $members = '(empty group)';
    }
    $arr = array('members' => $members, 'domid' => $domid);
    sendJSON($arr);
}
예제 #6
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;
}
예제 #7
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;
}