Пример #1
0
function imprimer($conn, $id, $titre, $photo)
{
    echo '
  <div class="col-md-3 col-sm-6 hero-feature">
    <div class="thumbnail">
      <img src="' . $photo . '" alt="">
      <div class="caption">
        <h3>' . utf8_decode($titre) . '</h3>
        <p>
        ';
    $res = louerpar($conn, $id);
    $nom = odbc_result($res, 1);
    $prenom = odbc_result($res, 2);
    if ($nom) {
        echo 'Appartement loué par : ' . $prenom . '  ' . $nom;
    } else {
        echo 'Appartement Libre';
        if (isAvailable($conn, $id)) {
            echo '<a class="btn btn-primary" href="proprietaire_fonction.php?a=0&id=' . $id . '" >Rendre Indisponible</a>';
        } else {
            echo '<a class="btn btn-primary" href="proprietaire_fonction.php?a=1&id=' . $id . '" >Rendre Disponible</a>';
        }
    }
    echo '
        </p>
      </div>
    </div>
  </div>
  ';
}
Пример #2
0
function transaksi()
{
    include "config.php";
    $conn = connect_database();
    if (userCheck($conn, $_POST['id'])) {
        $kodealat = mysqli_real_escape_string($conn, $_POST["kode-alat"]);
        $tanggal = date("Y-m-d", time());
        if (isset($_POST["tanggal-pinjam"])) {
            $tanggal = $_POST["tanggal-pinjam"];
        }
        if (!isAvailable($conn, $kodealat, $tanggal, $_POST["tanggal-kembali"])) {
            echo "Maaf, alat pada hari tersebut tidak dapat dipinjam </br>";
        } else {
            if (strcmp($_POST["jenis"], "peminjaman") == 0) {
                $sql = "INSERT INTO `peminjaman` (`id_user`, `id_alat`, `tanggal_rencana_pengembalian`) VALUES ('{$_POST['id']}','{$kodealat}','" . str_replace('T', ' ', $_POST["tanggal-kembali"]) . ":00')";
            } else {
                //booking
                $sql = "INSERT INTO `booking` (`id_user`, `id_alat`, `tanggal_rencana_peminjaman`, `tanggal_rencana_pengembalian`) VALUES ('{$_POST['id']}','{$kodealat}','" . str_replace('T', ' ', $_POST["tanggal-pinjam"]) . ":00','" . str_replace('T', ' ', $_POST["tanggal-kembali"]) . ":00')";
            }
            if (mysqli_query($conn, $sql)) {
                echo "Data anda berhasil disimpan</br>";
            } else {
                echo mysqli_error($conn);
            }
        }
    } else {
        //tidak ada user dengan id tersebut
        echo "Maaf, user dengan ID sekian belum terdaftar. Mohon daftarkan diri Anda terlebih dahulu!";
    }
    echo '<a href="../index.php"> Kembali ke halaman Transaksi</a>';
}
Пример #3
0
function AJsubmitEditRequest()
{
    global $user;
    $requestid = getContinuationVar('requestid');
    $openend = getContinuationVar('openend');
    $allownousercheck = getContinuationVar('nousercheck');
    $modifystart = getContinuationVar('modifystart');
    $startdays = getContinuationVar('startdays');
    $lengths = getContinuationVar('lengths');
    $maxextend = getContinuationVar('maxextend');
    $allowindefiniteend = getContinuationVar('allowindefiniteend');
    $request = getRequestInfo($requestid, 1);
    if (is_null($request)) {
        $cdata = getContinuationVar();
        $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
        sendJSON(array('status' => 'norequest', 'html' => i('The selected reservation no longer exists.') . '<br><br>', 'cont' => $cont));
        return;
    }
    if ($modifystart) {
        $day = processInputVar('day', ARG_NUMERIC, 0);
        if (!in_array($day, $startdays)) {
            $cdata = getContinuationVar();
            $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
            sendJSON(array('status' => 'error', 'errmsg' => i('Invalid start day submitted'), 'cont' => $cont));
            return;
        }
        $starttime = processInputVar('starttime', ARG_STRING);
        if (!preg_match('/^(([01][0-9])|(2[0-3]))([0-5][0-9])$/', $starttime, $matches)) {
            $cdata = getContinuationVar();
            $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
            sendJSON(array('status' => 'error', 'errmsg' => i("Invalid start time submitted"), 'cont' => $cont));
            return;
        }
        preg_match('/^([0-9]{4})([0-9]{2})([0-9]{2})$/', $day, $tmp);
        $startdt = "{$tmp[1]}-{$tmp[2]}-{$tmp[3]} {$matches[1]}:{$matches[4]}:00";
        $startts = datetimeToUnix($startdt);
    } else {
        $startdt = $request['start'];
        $startts = datetimeToUnix($startdt);
    }
    $endmode = processInputVar('endmode', ARG_STRING);
    if ($endmode == 'length') {
        $length = processInputVar('length', ARG_NUMERIC);
        if (!in_array($length, $lengths)) {
            $cdata = getContinuationVar();
            $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
            sendJSON(array('status' => 'error', 'errmsg' => i("Invalid duration submitted"), 'cont' => $cont));
            return;
        }
        if ($modifystart) {
            $endts = $startts + $length * 60;
        } else {
            $tmp = datetimeToUnix($request['end']);
            $endts = $tmp + $length * 60;
        }
        $enddt = unixToDatetime($endts);
    } elseif ($endmode == 'ending') {
        $ending = processInputVar('ending', ARG_NUMERIC);
        if (!preg_match('/^([0-9]{4})([0-9]{2})([0-9]{2})(([01][0-9])|(2[0-3]))([0-5][0-9])$/', $ending, $tmp) || !checkdate($tmp[2], $tmp[3], $tmp[1])) {
            $cdata = getContinuationVar();
            $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
            sendJSON(array('status' => 'error', 'errmsg' => i("Invalid end date/time submitted"), 'cont' => $cont));
            return;
        }
        $enddt = "{$tmp[1]}-{$tmp[2]}-{$tmp[3]} {$tmp[4]}:{$tmp[7]}:00";
        $endts = datetimeToUnix($enddt);
    } elseif ($allowindefiniteend && $endmode == 'indefinite') {
        $endts = datetimeToUnix('2038-01-01 00:00:00');
        $enddt = unixToDatetime($endts);
    } else {
        $cdata = getContinuationVar();
        $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
        sendJSON(array('status' => 'error', 'errmsg' => i("Invalid data submitted"), 'cont' => $cont));
        return;
    }
    $updategroups = 0;
    $updateservername = 0;
    if ($request['serverrequest']) {
        if ($user['showallgroups']) {
            $groups = getUserGroups(0);
        } else {
            $groups = getUserGroups(0, $user['affiliationid']);
        }
        $admingroupid = processInputVar('admingroupid', ARG_NUMERIC);
        $logingroupid = processInputVar('logingroupid', ARG_NUMERIC);
        if ($admingroupid != 0 && !array_key_exists($admingroupid, $groups) && $admingroupid != $request['admingroupid'] || $logingroupid != 0 && !array_key_exists($logingroupid, $groups) && $logingroupid != $request['logingroupid']) {
            $cdata = getContinuationVar();
            $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
            sendJSON(array('status' => 'error', 'errmsg' => i("Invalid user group submitted"), 'cont' => $cont));
            return;
        }
        $testadmingroupid = $admingroupid;
        if ($admingroupid == 0) {
            $testadmingroupid = '';
        }
        $testlogingroupid = $logingroupid;
        if ($logingroupid == 0) {
            $testlogingroupid = '';
        }
        if ($testadmingroupid != $request['admingroupid'] || $testlogingroupid != $request['logingroupid']) {
            $updategroups = 1;
        }
        $servername = processInputVar('servername', ARG_STRING);
        if (!preg_match('/^([-a-zA-Z0-9\\.\\(\\)_ ]){3,255}$/', $servername)) {
            $cdata = getContinuationVar();
            $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
            sendJSON(array('status' => 'error', 'errmsg' => i("The name can only contain letters, numbers, spaces, dashes(-), and periods(.) and can be from 3 to 255 characters long"), 'cont' => $cont));
            return;
        }
        if ($servername != $request['servername']) {
            $servername = mysql_real_escape_string($servername);
            $updateservername = 1;
        }
    }
    $h = '';
    $max = getMaxOverlap($user['id']);
    if (checkOverlap($startts, $endts, $max, $requestid)) {
        if ($max == 0) {
            $m = i("The time you requested overlaps with another reservation you currently have. You are only allowed to have a single reservation at any given time. Please select another time for the reservation.");
            $h .= preg_replace("/(.{1,60}([ \n]|\$))/", '\\1<br>', $m) . "<br>";
        } else {
            $m = sprintf(i("The time you requested overlaps with another reservation you currently have. You are allowed to have %s overlapping reservations at any given time. Please select another time for the reservation."), $max);
            $h .= preg_replace("/(.{1,60}([ \n]|\$))/", '\\1<br>', $m) . "<br>";
        }
        $cdata = getContinuationVar();
        $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
        sendJSON(array('status' => 'error', 'errmsg' => $h, 'cont' => $cont));
        return;
    }
    if ($request['serverrequest'] && (!empty($request['fixedIP']) || !empty($request['fixedMAC']))) {
        $ip = $request['fixedIP'];
        $mac = $request['fixedMAC'];
    } else {
        $ip = '';
        $mac = '';
    }
    $imageid = $request['reservations'][0]['imageid'];
    $images = getImages();
    $revisions = array();
    foreach ($request['reservations'] as $key => $res) {
        $revisions[$res['imageid']][$key] = $res['imagerevisionid'];
    }
    $rc = isAvailable($images, $imageid, $revisions, $startts, $endts, 1, $requestid, 0, 0, 0, $ip, $mac);
    $data = array();
    if ($rc < 1) {
        $cdata = array('now' => 0, 'start' => $startts, 'end' => $endts, 'server' => $allowindefiniteend, 'imageid' => $imageid, 'requestid' => $requestid);
        if (!$modifystart) {
            $cdata['extendonly'] = 1;
        }
        $sugcont = addContinuationsEntry('AJshowRequestSuggestedTimes', $cdata);
        if (array_key_exists('subimages', $images[$imageid]) && count($images[$imageid]['subimages'])) {
            $data['sugcont'] = 'cluster';
        } else {
            $data['sugcont'] = $sugcont;
        }
        addChangeLogEntry($request["logid"], NULL, $enddt, $startdt, NULL, NULL, 0);
    }
    if ($rc == -3) {
        $msgip = '';
        $msgmac = '';
        if (!empty($ip)) {
            $msgip = " ({$ip})";
        }
        if (!empty($mac)) {
            $msgmac = " ({$mac})";
        }
        $h .= sprintf(i("The reserved IP (%s) or MAC address (%s) conflicts with another reservation using the same IP or MAC address. Please select a different time to use the image."), $msgip, $msgmac);
        $h = preg_replace("/(.{1,60}([ \n]|\$))/", '\\1<br>', $h);
        $cdata = getContinuationVar();
        $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
        $data['status'] = 'conflict';
        $data['errmsg'] = $h;
        $data['cont'] = $cont;
        sendJSON($data);
        return;
    } elseif ($rc == -2) {
        $m = i("The time you requested overlaps with a maintenance window. Please select a different time to use the image.");
        $h .= preg_replace("/(.{1,60}([ \n]|\$))/", '\\1<br>', $m) . "<br>";
        $cdata = getContinuationVar();
        $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
        $data['status'] = 'conflict';
        $data['errmsg'] = $h;
        $data['cont'] = $cont;
        sendJSON($data);
        return;
    } elseif ($rc == -1) {
        $m = i("The reservation you are modifying is for an environment limited in the number of concurrent reservations that can be made. The time or duration you have requested overlaps with too many other reservations for the same image. Please select another time or duration for the reservation.");
        $h .= preg_replace("/(.{1,60}([ \n]|\$))/", '\\1<br>', $m) . "<br>";
        $cdata = getContinuationVar();
        $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
        $data['status'] = 'conflict';
        $data['errmsg'] = $h;
        $data['cont'] = $cont;
        sendJSON($data);
        return;
    } elseif ($rc > 0) {
        updateRequest($requestid);
        $serversets = array();
        $reqsets = array();
        if ($updategroups && $request['laststateid'] != 24) {
            if ($admingroupid == 0) {
                $admingroupid = 'NULL';
            }
            if ($logingroupid == 0) {
                $logingroupid = 'NULL';
            }
            $serversets[] = "admingroupid = {$admingroupid}";
            $serversets[] = "logingroupid = {$logingroupid}";
            addChangeLogEntryOther($request['logid'], "event:usergroups|admingroupid:{$admingroupid}|logingroupid:{$logingroupid}");
            $reqsets[] = "stateid = 29";
        }
        if ($updateservername) {
            $serversets[] = "name = '{$servername}'";
        }
        if ($allownousercheck) {
            $newnousercheck = processInputVar('newnousercheck', ARG_NUMERIC);
            if (($newnousercheck == 1 || $newnousercheck == 0) && $newnousercheck == $request['checkuser']) {
                $reqsets[] = "checkuser = (1 - checkuser)";
            }
        }
        if (count($serversets)) {
            $sets = implode(',', $serversets);
            $query = "UPDATE serverrequest " . "SET {$sets} " . "WHERE requestid = {$requestid}";
            doQuery($query);
        }
        if (count($reqsets)) {
            $sets = implode(',', $reqsets);
            $query = "UPDATE request " . "SET {$sets} " . "WHERE id = {$requestid}";
            doQuery($query);
        }
        sendJSON(array('status' => 'success'));
        cleanSemaphore();
        return;
    } else {
        $m = i("The time period you have requested is not available. Please select a different time.");
        $h .= preg_replace("/(.{1,55}([ \n]|\$))/", '\\1<br>', $m) . "<br>";
        $cdata = getContinuationVar();
        $cont = addContinuationsEntry('AJsubmitEditRequest', $cdata, SECINDAY, 1, 0);
        $data['status'] = 'conflict';
        $data['errmsg'] = $h;
        $data['cont'] = $cont;
        sendJSON($data);
    }
}
Пример #4
0
<?php

/*
 *  Copyright (c) Codiad & Kent Safranski (codiad.com), distributed
 *  as-is and without warranty under the MIT License. See 
 *  [root]/license.txt for more. This information must remain intact.
 */
require_once '../../config.php';
//////////////////////////////////////////////////////////////////
// Verify Session or Key
//////////////////////////////////////////////////////////////////
checkSession();
//////////////////////////////////////////////////////////////////
// Check system() command
//////////////////////////////////////////////////////////////////
if (!isAvailable('system')) {
    exit('<script>parent.message.error("System Command Not Supported")</script>');
}
//////////////////////////////////////////////////////////////////
// Run Download
//////////////////////////////////////////////////////////////////
if ($_GET['type'] == 'directory' || $_GET['type'] == 'root') {
    // Create tarball
    $filename = explode("/", $_GET['path']);
    $filename = array_pop($filename) . "-" . date('Y.m.d') . ".tar.gz";
    $targetPath = DATA . '/';
    $dir = WORKSPACE . $_GET['path'];
    # Execute the tar command and save file
    system("tar -pczf " . $targetPath . "/" . $filename . " " . $dir);
    $download_file = $targetPath . $filename;
} else {
Пример #5
0
switch ($method) {
    case 'addUser':
        // registers the provided username
        if ($username && addUser($username, $password)) {
            // Send a 201 (created) to indicate the creation was successful
            http_response_code(201);
            $responseData['message'] = 'created';
        } else {
            // send a 409 (conflict) to indicate there was a problem (usually a race condition on the username)
            http_response_code(409);
            $responseData['message'] = 'conflict';
        }
        break;
    case 'isAvailable':
        // checks to see if the username is available
        if ($username && isAvailable($username)) {
            // send a 200 (ok) to indicate it's available
            http_response_code(200);
            $responseData['message'] = 'ok';
        } else {
            // send a 409 (conflict) to indicate it's already in use
            http_response_code(409);
            $responseData['message'] = 'conflict';
        }
        break;
    case 'login':
        // log the user in if it's valid
        // Rotate the session
        session_regenerate_id(true);
        if ($username) {
            $userId = checkLogin($username, $password);
Пример #6
0
// = START CHECKS =
// ================
$values[] = array('desc' => 'PHP version >= 5.3.0', 'res' => version_compare(PHP_VERSION, '5.3.0') >= 0);
$values[] = array('desc' => 'PHP version < 7.0.0', 'res' => version_compare(PHP_VERSION, '7.0.0') < 0);
$values[] = array('desc' => 'Default Time Zone set', 'res' => !empty(ini_get('date.timezone')));
$values[] = array('desc' => 'mcrypt module installed', 'res' => extension_loaded('mcrypt'));
$values[] = array('desc' => 'simplexml module installed', 'res' => extension_loaded('simplexml'));
$values[] = array('desc' => 'zlib module installed', 'res' => extension_loaded('zlib'));
$values[] = array('desc' => 'json module installed', 'res' => extension_loaded('json'));
//$values[] = array('desc' => 'mhash module installed', 'res' => extension_loaded('mhash'));
$values[] = array('desc' => 'xmlwriter module installed', 'res' => extension_loaded('xmlwriter'));
$values[] = array('desc' => 'mbstring module installed', 'res' => extension_loaded('mbstring'));
$values[] = array('desc' => 'pdo module installed', 'res' => extension_loaded('pdo'));
$values[] = array('desc' => 'pdo_mysql installed', '', 'res' => extension_loaded('pdo_mysql'));
$values[] = array('desc' => 'gettext installed', 'res' => function_exists('gettext'));
$values[] = array('desc' => 'shell_exec function enabled', 'res' => isAvailable('shell_exec'));
$values[] = array('desc' => 'curl function enabled', 'res' => function_exists('curl_version'));
$values[] = array('desc' => 'Magic Quotes disabled', 'res' => !get_magic_quotes_gpc());
$values[] = array('desc' => 'Apache MOD Rewrite enabled', 'res' => checkRewrite());
// =============
// = FUNCTIONS =
// =============
function checkRewrite()
{
    foreach ($_SERVER as $k => $v) {
        if ($k == 'XXX_REWRITE_XXX') {
            return true;
        }
        if ($k == 'REDIRECT_XXX_REWRITE_XXX') {
            return true;
        }
Пример #7
0
function submitEditRequest()
{
    global $user, $submitErr, $viewmode, $mode;
    $data = getContinuationVar();
    $request = getRequestInfo($data["requestid"]);
    print "<H2>Modify Reservation</H2>\n";
    $hour = $data["hour"];
    if ($data["hour"] == 12) {
        if ($data["meridian"] == "am") {
            $hour = 0;
        }
    } elseif ($data["meridian"] == "pm") {
        $hour = $data["hour"] + 12;
    }
    $tmp = explode('/', $data["day"]);
    $start = mktime($hour, $data["minute"], "0", $tmp[0], $tmp[1], $tmp[2]);
    if ($data['openend'] && $data['ending'] == 'date') {
        $end = datetimeToUnix($data['enddate']);
    } else {
        if (datetimeToUnix($request["start"]) < datetimeToUnix($request["daterequested"])) {
            $end = $start + $data["length"] * 60 + 900;
        } else {
            $end = $start + $data["length"] * 60;
        }
    }
    // get semaphore lock
    if (!semLock()) {
        abort(3);
    }
    $max = getMaxOverlap($user['id']);
    if (checkOverlap($start, $end, $max, $data["requestid"])) {
        if ($max == 0) {
            print "<font color=\"#ff0000\">The time you requested overlaps with ";
            print "another reservation you currently have.  You are only allowed ";
            print "to have a single reservation at any given time. Please select ";
            print "another time to use the application.</font><br><br>\n";
        } else {
            print "<font color=\"#ff0000\">The time you requested overlaps with ";
            print "another reservation you currently have.  You are allowed ";
            print "to have {$max} overlapping reservations at any given time. ";
            print "Please select another time to use the application.</font><br>";
            print "<br>\n";
        }
        $submitErr = 1;
        editRequest();
        return;
    }
    $rc = isAvailable(getImages(), $data["imageid"], $start, $end, $data["os"], $data["requestid"]);
    if ($rc == -1) {
        print "You have requested an environment that is limited in the number ";
        print "of concurrent reservations that can be made. No further ";
        print "reservations for the environment can be made for the time you ";
        print "have selected. Please select another time to use the ";
        print "environment.<br>";
        addChangeLogEntry($request["logid"], NULL, unixToDatetime($end), unixToDatetime($start), NULL, NULL, 0);
    } elseif ($rc > 0) {
        updateRequest($data["requestid"]);
        if ($data["started"]) {
            if ($data['openend'] && $data['ending'] == 'date') {
                print "Your request to change the ending of your reservation for <b>";
                print "{$data["prettyimage"]}</b> to {$data['enddate']} ";
                print "has been accepted.<br><br>\n";
            } else {
                $remaining = ($end - time()) / 60;
                print "Your request to extend your reservation for <b>";
                print "{$data["prettyimage"]}</b> by " . prettyLength($data["extend"]);
                print " has been accepted.<br><br>\n";
                print "You now have " . prettyLength($remaining) . " remaining for ";
                print "your reservation<br>\n";
            }
        } else {
            print "Your request to use <b>" . $data["prettyimage"] . "</b> on ";
            if (datetimeToUnix($request["start"]) < datetimeToUnix($request["daterequested"])) {
                print prettyDatetime($request["daterequested"]);
            } else {
                print prettyDatetime($start);
            }
            if ($data['openend'] && $data['ending'] == 'date') {
                print " until " . prettyDatetime($end);
            } else {
                print " for " . prettyLength($data["length"]);
            }
            print " has been accepted.<br>\n";
        }
    } else {
        $cdata = array('imageid' => $data['imageid'], 'length' => $data['length'], 'requestid' => $data['requestid']);
        $cont = addContinuationsEntry('selectTimeTable', $cdata);
        print "The time you have requested is not available. You may ";
        print "<a href=\"" . BASEURL . SCRIPT . "?continuation={$cont}\">";
        print "view a timetable</a> of free and reserved times to find ";
        print "a time that will work for you.<br>\n";
        addChangeLogEntry($request["logid"], NULL, unixToDatetime($end), unixToDatetime($start), NULL, NULL, 0);
    }
}
Пример #8
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;
}
Пример #9
0
<?php

session_start();
define(ROOT, $_SERVER['DOCUMENT_ROOT']);
include_once ROOT . "/functions/database_management.php";
//TODO: Reemplazar por $_SESSION['username']
switch ($_POST["functionCalled"]) {
    case "hasCompleted":
        echo 'ret=' . var_export(hasCompleted($_POST["eventName"], $_POST["username"], $_POST["puzzle"]), true);
        break;
    case "complete":
        echo complete($_POST["eventName"], $_POST["username"], $_POST["puzzle"]);
        break;
    case "isAvailable":
        echo 'ret=' . var_export(isAvailable($_POST["eventName"], $_POST["username"], $_POST["object"]), true);
        break;
    case "hasObject":
        echo 'ret=' . var_export(hasObject($_POST["eventName"], $_POST["username"], $_POST["object"]), true);
        break;
    case "usedObject":
        echo 'ret=' . var_export(usedObject($_POST["eventName"], $_POST["username"], $_POST["object"]), true);
        break;
    case "releaseObject":
        releaseObject($_POST["eventName"], $_POST["username"], $_POST["object"]);
        break;
    case "getObject":
        getObject($_POST["eventName"], $_POST["username"], $_POST["object"]);
        break;
    case "useObject":
        useObject($_POST["eventName"], $_POST["username"], $_POST["object"]);
        break;
Пример #10
0
function submitCreateImage()
{
    global $submitErr, $user, $viewmode, $HTMLheader, $printedHTMLheader, $mode;
    if ($mode == 'submitCreateTestProd') {
        $data = getContinuationVar();
        $data["revisionid"] = processInputVar("revisionid", ARG_MULTINUMERIC);
        # TODO check for valid revisionid
    } else {
        $data = processRequestInput(0);
        $data['length'] = getContinuationVar('length');
    }
    $showrevisions = 0;
    $subimages = 0;
    $images = getImages();
    $revcount = count($images[$data['imageid']]['imagerevision']);
    if ($revcount > 1) {
        $showrevisions = 1;
    }
    if ($images[$data['imageid']]['imagemetaid'] != NULL && count($images[$data['imageid']]['subimages'])) {
        $subimages = 1;
        foreach ($images[$data['imageid']]['subimages'] as $subimage) {
            $revcount = count($images[$subimage]['imagerevision']);
            if ($revcount > 1) {
                $showrevisions = 1;
            }
        }
    }
    if ($data["time"] == "now") {
        $nowArr = getdate();
        if ($nowArr["minutes"] == 0) {
            $subtract = 0;
            $add = 0;
        } elseif ($nowArr["minutes"] < 15) {
            $subtract = $nowArr["minutes"] * 60;
            $add = 900;
        } elseif ($nowArr["minutes"] < 30) {
            $subtract = ($nowArr["minutes"] - 15) * 60;
            $add = 900;
        } elseif ($nowArr["minutes"] < 45) {
            $subtract = ($nowArr["minutes"] - 30) * 60;
            $add = 900;
        } elseif ($nowArr["minutes"] < 60) {
            $subtract = ($nowArr["minutes"] - 45) * 60;
            $add = 900;
        }
        $start = time() - $subtract;
        $start -= $start % 60;
        $nowfuture = "now";
    } else {
        $add = 0;
        $hour = $data["hour"];
        if ($data["hour"] == 12) {
            if ($data["meridian"] == "am") {
                $hour = 0;
            }
        } elseif ($data["meridian"] == "pm") {
            $hour = $data["hour"] + 12;
        }
        $tmp = explode('/', $data["day"]);
        $start = mktime($hour, $data["minute"], "0", $tmp[0], $tmp[1], $tmp[2]);
        if ($start < time()) {
            print $HTMLheader;
            print "<H2>Create / Update an Image</H2>\n";
            print "<font color=\"#ff0000\">The time you requested is in the past.";
            print " Please select \"Now\" or use a time in the future.</font><br>\n";
            $submitErr = 1;
            createSelectImage();
            return;
        }
        $nowfuture = "future";
    }
    // FIXME hard code length to 8 hours
    $data["length"] = 480;
    $end = $start + $data["length"] * 60 + $add;
    // get semaphore lock
    if (!semLock()) {
        abort(3);
    }
    $max = getMaxOverlap($user['id']);
    if (checkOverlap($start, $end, $max)) {
        $printedHTMLheader = 1;
        print $HTMLheader;
        print "<H2>New Reservation</H2>\n";
        if ($max == 0) {
            print "<font color=\"#ff0000\">The time you requested overlaps with ";
            print "another reservation you currently have.  You are only allowed ";
            print "to have a single reservation at any given time. Please select ";
            print "another time to use the application. If you are finished with ";
            print "an active reservation, click \"Current Reservations\", ";
            print "then click the \"End\" button of your active reservation.";
            print "</font><br><br>\n";
        } else {
            print "<font color=\"#ff0000\">The time you requested overlaps with ";
            print "another reservation you currently have.  You are allowed ";
            print "to have {$max} overlapping reservations at any given time. ";
            print "Please select another time to use the application. If you are ";
            print "finished with an active reservation, click \"Current ";
            print "Reservations\", then click the \"End\" button of your active ";
            print "reservation.</font><br><br>\n";
        }
        $submitErr = 1;
        createSelectImage();
        return;
    }
    // if user is owner of the image and there is a test revision of the image
    #   available, ask user if production or test image desired
    if ($mode != "submitCreateTestProd" && $showrevisions && $images[$data["imageid"]]["ownerid"] == $user["id"]) {
        $printedHTMLheader = 1;
        print $HTMLheader;
        print "<H2>New Reservation</H2>\n";
        if ($subimages) {
            print "This is a cluster environment. At least one image in the ";
            print "cluster has more than one revision available. Please select ";
            print "the revision you desire for each image listed below:<br>\n";
        } else {
            print "There are multiple revisions of this environment available.  Please ";
            print "select the revision you would like to check out:<br>\n";
        }
        print "<FORM action=\"" . BASEURL . SCRIPT . "\" method=post><br>\n";
        if (!array_key_exists('subimages', $images[$data['imageid']])) {
            $images[$data['imageid']]['subimages'] = array();
        }
        array_unshift($images[$data['imageid']]['subimages'], $data['imageid']);
        foreach ($images[$data['imageid']]['subimages'] as $subimage) {
            print "{$images[$subimage]['prettyname']}:<br>\n";
            print "<table summary=\"lists revisions of the selected environment, one must be selected to continue\">\n";
            print "  <TR>\n";
            print "    <TD></TD>\n";
            print "    <TH>Revision</TH>\n";
            print "    <TH>Creator</TH>\n";
            print "    <TH>Created</TH>\n";
            print "    <TH>Currently in Production</TH>\n";
            print "  </TR>\n";
            foreach ($images[$subimage]['imagerevision'] as $revision) {
                print "  <TR>\n";
                if (array_key_exists($subimage, $data['revisionid']) && $data['revisionid'][$subimage] == $revision['id']) {
                    print "    <TD align=center><INPUT type=radio name=revisionid[{$subimage}] value={$revision['id']} checked></TD>\n";
                } elseif ($revision['production']) {
                    print "    <TD align=center><INPUT type=radio name=revisionid[{$subimage}] value={$revision['id']} checked></TD>\n";
                } else {
                    print "    <TD align=center><INPUT type=radio name=revisionid[{$subimage}] value={$revision['id']}></TD>\n";
                }
                print "    <TD align=center>{$revision['revision']}</TD>\n";
                print "    <TD align=center>{$revision['user']}</TD>\n";
                print "    <TD align=center>{$revision['prettydate']}</TD>\n";
                if ($revision['production']) {
                    print "    <TD align=center>Yes</TD>\n";
                } else {
                    print "    <TD align=center>No</TD>\n";
                }
                print "  </TR>\n";
            }
            print "</TABLE>\n";
        }
        addContinuationsEntry('submitCreateImage', array(), SECINDAY, 1, 0);
        // we add this continuation back
        //   so the currently displayed
        //   page can be reloaded
        $cont = addContinuationsEntry('submitCreateTestProd', $data);
        print "<br><INPUT type=hidden name=continuation value=\"{$cont}\">\n";
        print "<INPUT type=submit value=Submit>\n";
        print "</FORM>\n";
        return;
    }
    $rc = isAvailable($images, $data["imageid"], $start, $end, $data["os"], 0, 0, 0, 1);
    if ($rc == -1) {
        $printedHTMLheader = 1;
        print $HTMLheader;
        print "<H2>Create / Update an Image</H2>\n";
        print "You have requested an environment that is limited in the number ";
        print "of concurrent reservations that can be made. No further ";
        print "reservations for the environment can be made for the time you ";
        print "have selected. Please select another time to use the ";
        print "environment.<br>";
    } elseif ($rc > 0) {
        $requestid = addRequest(1, $data['revisionid']);
        if ($data["time"] == "now") {
            header("Location: " . BASEURL . SCRIPT . "?mode=viewRequests");
            dbDisconnect();
            exit;
        } else {
            $time = prettyLength($data["length"]);
            if ($data["minute"] == 0) {
                $data["minute"] = "00";
            }
            $printedHTMLheader = 1;
            print $HTMLheader;
            print "<H2>Create / Update an Image</H2>\n";
            print "Your request to use <b>" . $images[$data["imageid"]]["prettyname"];
            print "</b> on " . prettyDatetime($start) . " for {$time} has been ";
            print "accepted.<br><br>\n";
            print "When your reservation time has been reached, the ";
            print "<b>Current Reservations</b> page will give you more ";
            print "information on connecting to the reserved computer. If you ";
            print "would like to modify your reservation, you can do that from ";
            print "the <b>Current Reservations</b> page as well.<br>\n";
        }
    } else {
        $printedHTMLheader = 1;
        print $HTMLheader;
        $cdata = array('imageid' => $data['imageid'], 'length' => $data['length']);
        $cont = addContinuationsEntry('selectTimeTable', $cdata);
        print "<H2>Create / Update an Image</H2>\n";
        print "The reservation you have requested is not available. You may ";
        print "<a href=\"" . BASEURL . SCRIPT . "?continuation={$cont}\">";
        print "view a timetable</a> of free and reserved times to find ";
        print "a time that will work for you.<br>\n";
        #addLogEntry($nowfuture, unixToDatetime($start),
        #            unixToDatetime($end), 0, $data["imageid"]);
    }
}
Пример #11
0
<?php

if (isset($_POST['kirim'])) {
    $tanggal = date("Y-m-d", time());
    if (isAvailable($conn, $_POST['id'], $tanggal, $_POST['estimasi'])) {
        tambahPerbaikan();
    } else {
        echo "<script> window.open('../perbaikan.php', '_self') </script>";
    }
} else {
    if (isset($_POST['update'])) {
        pengembalian();
    }
}
function isAvailable($conn, $kodealat, $tanggalmulai, $tanggalselesai)
{
    $available = true;
    $waktumulai = intval(substr($tanggalmulai, 0, 4)) * 365 + intval(substr($tanggalmulai, 5, 2)) * 30 + intval(substr($tanggalmulai, 8, 2));
    $waktuselesai = intval(substr($tanggalselesai, 0, 4)) * 365 + intval(substr($tanggalselesai, 5, 2)) * 30 + intval(substr($tanggalselesai, 8, 2));
    if ($available) {
        $results = mysqli_query($conn, "SELECT * FROM peminjaman WHERE id_alat = '{$kodealat}' AND tanggal_pengembalian IS NULL");
        if (mysqli_num_rows($results) > 0) {
            foreach ($results as $result) {
                $mulai = intval(substr($result['tanggal_peminjaman'], 0, 4)) * 365 + intval(substr($result['tanggal_peminjaman'], 5, 2)) * 30 + intval(substr($result['tanggal_peminjaman'], 8, 2));
                $selesai = intval(substr($result['tanggal_rencana_pengembalian'], 0, 4)) * 365 + intval(substr($result['tanggal_rencana_pengembalian'], 5, 2)) * 30 + intval(substr($result['tanggal_rencana_pengembalian'], 8, 2));
                if ($waktumulai < $mulai and $waktuselesai < $mulai or $waktumulai > $selesai and $waktuselesai > $selesai) {
                    //nothing
                } else {
                    $available = false;
                }
            }
Пример #12
0
function acquirePlayer($userID, $leagueID, $playerID, $activeOrBench, $position, $transactionID)
{
    $season = getSeason();
    //$check = selectCount("v_current_rosters", " WHERE playerID = \"$playerID\" and leagueID = $leagueID and  userID = $userID");
    //if ($check > 0)
    //	return "Error: Player is on another roster.";
    if (!okToTransact($transactionID)) {
        return getReturnCode(0, "This transaction has already been completed. Please do not use the refresh button.");
    }
    $check = isAvailable($playerID, $leagueID);
    debug("DoAcquire: Check returned {$check}");
    $r = array();
    if ($check > 0) {
        // 0 is available
        $r["status"] = 0;
        $r["msg"] = "Error: Player is on another roster or his team is currently playing.";
        return $r;
    }
    debug("DoAcquire : Getting Roster Counts");
    $rosterCount = selectCount("fch_rosters", " Where userID = {$userID} and leagueID = {$leagueID} and season = \"{$season}\" and releaseDate is  null and position = \"{$position}\" and statusCode = \"{$activeOrBench}\"");
    $limit = getPositionLimit($position, $activeOrBench, $leagueID);
    debug("Roster Slot calc: {$rosterCount} >= {$limit}");
    if ($rosterCount >= $limit) {
        debug("no slots, returning failure");
        $r["status"] = 0;
        $r["msg"] = "Your " . getDisplayRosterName($activeOrBench) . " is full at this position.";
        return $r;
    }
    debug("passed validation, inserting");
    $sql = <<<SQL

\tINSERT INTO  fanta66_joomla.fch_rosters (
\t\tid ,
\t\tleagueID ,
\t\tuserID ,
\t\tplayerID,
\t\tseason,
\t\tstatusCode,
\t\tposition,
\t\tacquireDate

\t\t)
\t\tVALUES (
\t\t\tNULL ,  {$leagueID},  {$userID}, "{$playerID}", "{$season}", "{$activeOrBench}", "{$position}", DATE_ADD(CURRENT_TIMESTAMP, INTERVAL +3 HOUR)
\t\t);
\t\t
SQL;
    //debug($sql);
    $rosterID = executeGenericInsertSQL($sql);
    $sql = <<<SQL

\tINSERT INTO  fanta66_joomla.fch_roster_transaction (
\t\tid ,
\t\tleagueID ,
\t\tuserID ,
\t\tplayerID,
\t\tseason,
\t\ttransactionDate,
\t\ttransactionType

\t\t)
\t\tVALUES (
\t\t\tNULL ,  {$leagueID},  {$userID}, "{$playerID}", "{$season}", DATE_ADD(CURRENT_TIMESTAMP, INTERVAL +3 HOUR), "Acquired"
\t\t);
\t\t
SQL;
    debug("acquirePlayer: " . $sql);
    $rosterOK = executeGenericInsertSQL($sql);
    $r["status"] = 1;
    $r["msg"] = "Your transaction was successful.";
    $r["id"] = $rosterID;
    setTransactionComplete($transactionID);
    return $r;
}
Пример #13
0
    $str = "";
    foreach ($_GET as $key => $value) {
        if ($key == "nick" || $key == "ip" || $key == "type" || $key == "score" || $key == "flag") {
            $str = $str . $value;
        }
    }
    if (strcmp(md5($str), $_GET['key']) != 0) {
        die('HACK!!!');
    }
}
checkGETkey();
switch ($type) {
    case 'IS_AVAILABLE':
        $data['available'] = isAvailable();
        break;
    case 'INSERT':
        if (isAvailable()) {
            insert();
        } else {
            update();
        }
        break;
    case 'LIST_BEST':
        listBest();
        break;
    case 'LIST_LAST':
        listLast();
        break;
}
print $_GET['callback'] . '(' . json_encode($data) . ')';
mysql_close();
Пример #14
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;
}
Пример #15
0
function moveReservationsOffComputer($compid = 0, $count = 0)
{
    global $requestInfo, $user;
    $resInfo = array();
    $checkstart = unixToDatetime(time() + 180);
    if ($compid == 0) {
        $resources = getUserResources(array("imageAdmin", "imageCheckOut"), array("available"), 0, 0);
        $computers = implode("','", array_keys($resources["computer"]));
        $computers = "'{$computers}'";
        $query = "SELECT DISTINCT COUNT(rs.id) AS reservations, " . "rs.computerid " . "FROM reservation rs, " . "request rq " . "WHERE rq.start > '{$checkstart}' AND " . "rs.computerid IN ({$computers}) " . "GROUP BY computerid " . "ORDER BY reservations " . "LIMIT 1";
        $qh = doQuery($query, 101);
        if ($row = mysql_fetch_assoc($qh)) {
            $compid = $row["computerid"];
        } else {
            return -1;
        }
    }
    # get all reservation info for $compid
    $query = "SELECT rs.id, " . "rs.requestid, " . "rs.imageid, " . "rq.logid, " . "rq.userid, " . "rq.start, " . "rq.end " . "FROM reservation rs, " . "request rq " . "WHERE rs.computerid = {$compid} AND " . "rs.requestid = rq.id AND " . "rq.start > '{$checkstart}' AND " . "rq.stateid NOT IN (1, 5, 11, 12) " . "ORDER BY rq.start";
    if ($count) {
        $query .= " LIMIT {$count}";
    }
    $qh = doQuery($query, 101);
    while ($row = mysql_fetch_assoc($qh)) {
        $resInfo[$row["id"]] = $row;
    }
    if (!count($resInfo)) {
        return -1;
    }
    $images = getImages();
    $allmovable = 1;
    foreach ($resInfo as $res) {
        $rc = isAvailable($images, $res["imageid"], datetimeToUnix($res["start"]), datetimeToUnix($res["end"]), "dummy", 0, $res["userid"]);
        if ($rc < 1) {
            $allmovable = 0;
            break;
        }
    }
    if (!$allmovable) {
        return 0;
    }
    foreach ($resInfo as $res) {
        $rc = isAvailable($images, $res["imageid"], datetimeToUnix($res["start"]), datetimeToUnix($res["end"]), "dummy", 0, $res["userid"]);
        if ($rc > 0) {
            $newcompid = array_shift($requestInfo["computers"]);
            # get mgmt node for computer
            $mgmtnodeid = findManagementNode($newcompid, $res['start'], 'future');
            # update mgmt node and computer in reservation table
            $query = "UPDATE reservation " . "SET computerid = {$newcompid}, " . "managementnodeid = {$mgmtnodeid} " . "WHERE id = {$res["id"]}";
            doQuery($query, 101);
            # add changelog entry
            addChangeLogEntry($res['logid'], NULL, NULL, NULL, $newcompid);
            # update sublog entry
            $query = "UPDATE sublog " . "SET computerid = {$newcompid} " . "WHERE logid = {$res['logid']} AND " . "computerid = {$compid}";
            doQuery($query, 101);
        } else {
            return 0;
        }
    }
    return 1;
}
Пример #16
0
// Run Download
//////////////////////////////////////////////////////////////////
if (isset($_GET['type']) && ($_GET['type'] == 'directory' || $_GET['type'] == 'root')) {
    // Create tarball
    $filename = explode("/", $_GET['path']);
    //$filename = array_pop($filename) . "-" . date('Y.m.d') . ".tar.gz";
    $filename = array_pop($filename) . "-" . date('Y.m.d');
    $targetPath = DATA . '/';
    $dir = WORKSPACE . '/' . $_GET['path'];
    if (!is_dir($dir)) {
        exit('<script>parent.codiad.message.error("Directory not found.")</script>');
    }
    //////////////////////////////////////////////////////////////////
    // Check system() command and a non windows OS
    //////////////////////////////////////////////////////////////////
    if (isAvailable('system') && stripos(PHP_OS, 'win') === false) {
        # Execute the tar command and save file
        $filename .= '.tar.gz';
        system("tar -pczf " . escapeshellarg($targetPath . $filename) . " -C " . escapeshellarg(WORKSPACE) . " " . escapeshellarg($_GET['path']));
        $download_file = $targetPath . $filename;
    } elseif (extension_loaded('zip')) {
        //Check if zip-Extension is availiable
        //build zipfile
        require_once 'class.dirzip.php';
        $filename .= '.zip';
        $download_file = $targetPath . $filename;
        DirZip::zipDir($dir, $targetPath . $filename);
    } else {
        exit('<script>parent.codiad.message.error("Could not pack the folder, zip-extension missing")</script>');
    }
} else {
Пример #17
0
function handleExtras($mcId, $userId, $toDistribute = 0)
{
    global $urlRequestRoot, $sourceFolder, $templateFolder, $cmsFolder, $moduleFolder;
    $checkPNG = "{$urlRequestRoot}/{$cmsFolder}/{$moduleFolder}/oc/images/check.png";
    $wrongPNG = "{$urlRequestRoot}/{$cmsFolder}/{$moduleFolder}/oc/images/dialog-error.png";
    $processPNG = "{$urlRequestRoot}/{$cmsFolder}/{$moduleFolder}/oc/images/dialog-information.png";
    $processIMG = "<img src=\"{$processPNG}\" />";
    $checkIMG = "<img src=\"{$checkPNG}\" />";
    $wrongIMG = "<img src=\"{$wrongPNG}\" />";
    if (!(isset($_SESSION['availability_extra']) && $_SESSION['availability_extra'] == 1)) {
        echo "You are not eligible to distribute Extras<br/>";
        return;
    }
    if (!isAvailable($mcId, 'Extra')) {
        echo "Extras Not Available. {$wrongIMG}<br/><hr/>";
        return;
    }
    if ($toDistribute == 0) {
        echo "Distribute Extra to " . $userId . ". {$processIMG}<br/><hr/>";
        return "true";
    }
    $updateQuery = "UPDATE `oc_form_reg` SET `oc_extra_distributed`='Yes' , `updated_time` = NOW()\n                           WHERE `oc_roll_no`={$userId} AND `page_moduleComponentId`={$mcId}";
    if (mysql_query($updateQuery)) {
        echo "Confirmed: Distribute Extra to " . $userId . ". {$processIMG}<br/><hr/>";
    } else {
        echo "There is a error in Extra(s) Distribution.Contact System Administrator.Do not Distribute Extra(s). {$wrongIMG}<br/><hr/>";
    }
    return;
}