Пример #1
0
function parseItem($blog, $item, $ts)
{
    if ($ts != 0 && $item->pubdate <= $ts) {
        logmsg('Zatrzymanie na wpisie: %s', StringUtils::removeAccents($item->title));
        return false;
    }
    logmsg('  - Parsowanie wpisu: %s', StringUtils::removeAccents($item->title));
    $post = new Post();
    $post->setBlog($blog);
    foreach ($item->tags as $name) {
        $tag = TagPeer::retriveByName($name, true);
        if ($post->addTag($tag)) {
            logmsg('    - Znaleziono tag: %s', $name);
        }
    }
    if ($post->hasTags()) {
        $shortened = $post->setFullContent($item->content);
        $post->setLink(htmlspecialchars($item->link));
        $post->setTitle($item->title);
        $post->setCreatedAt($item->pubdate);
        $post->setShortened($shortened);
        $post->save();
    } else {
        logmsg('    - Nie znaleziono tagow');
    }
    return true;
}
Пример #2
0
/** helper to output an error message. */
function err($string)
{
    // Annoying PHP: we need to import global variables here...
    global $title;
    require LIBWWWDIR . '/header.php';
    echo "<h2>Submit - error</h2>\n\n";
    echo '<div id="uploadstatus">';
    logmsg(LOG_WARNING, $string);
    echo '</div>';
    require LIBWWWDIR . '/footer.php';
    exit;
}
Пример #3
0
function delete_file_and_edit_agreement($var)
{
    $f = explode('_', $var);
    $fileid = $_POST['fileid_' . $f[1] . '_' . $f[2]];
    logmsg("deletefile {$var}; {$fileid}");
    save_agreement();
    $details = db_retrieve_file_details($fileid);
    $id = $_POST['0'];
    show_delete_file_form($fileid, $details[3], $details[4], array('ID' => $id));
    $aggr = db_retrieve_agreement_byID($id);
    addedit_agreement($aggr);
}
function minecraft_sigterm($signal)
{
    echo "terming\n";
    global $_STATE;
    logmsg("SIGTERM - stop");
    $_STATE['Running'] = false;
    fwrite($_STATE['Descriptors'][0], 'stop' . PHP_EOL);
    fflush($_STATE['Descriptors'][0]);
    if (isset($_CONFIG['Command_Pidfile']) && file_exists($_CONFIG['Command_Pidfile'])) {
        unlink($_CONFIG['Command_Pidfile']);
    }
}
Пример #5
0
/**
 * Wrapper around PHP setcookie function to automatically set some
 * DOMjudge specific defaults and check the return value.
 * - cookies are defined in a common path for all web interfaces
 */
function dj_setcookie($name, $value = null, $expire = 0, $path = null, $domain = null, $secure = false, $httponly = false)
{
    if (!isset($path)) {
        // KLUDGE: We want to find the DOMjudge base path, but this
        // information is not directly available as configuration, so
        // we extract it from the executed PHP script.
        $path = preg_replace('/(jury|public|team)\\/?$/', '', dirname($_SERVER['PHP_SELF']));
    }
    $ret = setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
    if ($ret !== true) {
        warning("Cookie '{$name}' not set properly.");
    }
    logmsg(LOG_DEBUG, "Cookie set: {$name}={$value}, expire={$expire}, path={$path}");
    return $ret;
}
Пример #6
0
function retrieve_filter_exchange()
{
    global $filter_url;
    logmsg("trsel: " . $_POST['travel_selection']);
    if (isset($_POST['travel_selection'])) {
        $filter_t = $_POST['travel_selection'];
    } else {
        $filter_t = $_GET['ft'];
    }
    if (strlen($filter_t) == 0) {
        $filter_t = $_POST['ft'];
    }
    if (strlen($filter_t) == 0) {
        $filter_t = db_get_first_travel();
    }
    $filter_url = '&ft=' . $filter_t;
    logmsg("ft: " . $filter_t);
    return $filter_t;
}
Пример #7
0
function process_fmfi_credits()
{
    global $userrole;
    if ($userrole === "admin") {
        print '<b>Travel FMFI courses</b><br /><br />';
        $filter_exchange = retrieve_filter_exchange();
        show_exchange_filter($filter_exchange);
        $tcdata = NULL;
        if (isset($_GET['act'])) {
            if ($_POST['Edit'] === 'edit') {
                $tcdata = db_fmfi_courses_for_an_exchange($filter_exchange, TRUE);
                edit_fmfi_travel_course($tcdata);
            } else {
                if ($_POST['Add'] === 'add') {
                    add_fmfi_travel_course($filter_exchange);
                } else {
                    if ($_POST['Save'] === 'save') {
                        save_fmfi_travel_course($filter_exchange);
                    } else {
                        if ($_POST['Remove'] === 'remove') {
                            $tcdata = db_fmfi_courses_for_an_exchange($filter_exchange, TRUE);
                            remove_record($tcdata);
                        } else {
                            if ($_POST['Remove'] === 'yes') {
                                yes_remove_fmfi_travel_courses();
                            }
                        }
                    }
                }
            }
        }
        logmsg("retr");
        if ($tcdata == NULL) {
            $tcdata = db_fmfi_courses_for_an_exchange($filter_exchange, TRUE);
        }
        logmsg("ieve {$filter_exchange}");
        $tcf = format_travel_fmfi_courses($tcdata);
        show_table(array('ID', 'FMFI course', 'Grade'), $tcf);
    } else {
        return;
    }
}
Пример #8
0
logmsg("Loading signals file: \"" . $_CONFIG['Signals'] . "\"");
logmsg("Working Directory: \"" . $_CONFIG['WorkingDirectory'] . "\"");
logmsg("");
for (;;) {
    // Start the command
    logmsg("Starting command");
    commandStart();
    // Block until it quits
    logmsg("Monitoring");
    commandMonitor();
    // Clean up descriptors and stuff
    logmsg("Died - Cleaning up");
    commandCleanup();
    // If we're shutting down, break out of the loop.
    if ($_STATE['Running'] == false) {
        logmsg("Saying goodnight - remember to tip your waitress!");
        break;
    }
}
if (isset($_CONFIG['Monitor_Pidfile'])) {
    unlink($_CONFIG['Monitor_Pidfile']);
}
/* Functions */
function logmsg($str)
{
    global $_CONFIG, $_STATE;
    $str = '[' . date('Y-m-d H:i:s') . '] ' . $str;
    if ($_CONFIG['Interactive'] == true) {
        echo $str . PHP_EOL;
    }
    if (!isset($_STATE['LogHandle'])) {
Пример #9
0
                     $arr = explode(':', $v);
                     $calendar_name = trim($arr[1]);
                     break;
                 }
             }
             $calendar_name = isset($calendar_name) ? $calendar_name : 'default';
             if (isset($_SERVER['PATH_INFO'])) {
                 preg_match("/\\/([ A-Za-z0-9.]*).ics/i", $_SERVER['PATH_INFO'], $matches);
                 $calendar_name = $matches[1];
             }
             // write to file
             if ($fp = fopen($calendar_path . $calendar_name . '.ics', 'w+')) {
                 fputs($fp, $data, strlen($data));
                 @fclose($fp);
             } else {
                 logmsg('couldnt open file ' . $calendar_path . $calendar_name . '.ics');
             }
         }
     }
     if ($_SERVER['REQUEST_METHOD'] == 'GET') {
         if (isset($_SERVER['PATH_INFO'])) {
             preg_match("/\\/([ A-Za-z0-9._]*).ics/i", $_SERVER['PATH_INFO'], $matches);
             $icsfile = $matches[1];
             // get calendar data
             if (file_exists($calendar_path . $icsfile . '.ics') && is_readable($calendar_path . $icsfile . '.ics') && is_file($calendar_path . $icsfile . '.ics')) {
                 echo file_get_contents($calendar_path . $icsfile . '.ics');
             } else {
             }
         }
     }
 }
Пример #10
0
function retrieve_first_checked_record($data)
{
    foreach ($data as $r) {
        if (isset($_POST[$r[0]])) {
            return $r;
        }
    }
    logmsg("no item checked");
    return NULL;
}
Пример #11
0
                @fclose($dataout);
            } else {
                logmsg('could not open file ' . $calendar_path . $calendar_name . '.ics');
            }
        } else {
            logmsg('PUT ERROR - No data supplied.');
        }
        break;
    case 'GET':
        if (isset($_SERVER['PATH_INFO'])) {
            preg_match("/\\/([ A-Za-z0-9._]*).ics/i", $_SERVER['PATH_INFO'], $matches);
            $icsfile = urldecode($matches[1]);
            // get calendar data
            if (file_exists($calendar_path . $icsfile . '.ics') && is_readable($calendar_path . $icsfile . '.ics') && is_file($calendar_path . $icsfile . '.ics')) {
                echo file_get_contents($calendar_path . $icsfile . '.ics');
                logmsg('downloaded calendar ' . $icsfile);
            }
        }
}
if (defined('PHPICALENDAR_LOG_PUBLISHING') && PHPICALENDAR_LOG_PUBLISHING == 1) {
    fclose($logfile);
}
header('HTTP/1.1 200 OK');
exit;
// for logging
function logmsg($str)
{
    global $logfile;
    if (defined('PHPICALENDAR_LOG_PUBLISHING') && PHPICALENDAR_LOG_PUBLISHING == 1) {
        if ($_SERVER['PHP_AUTH_USER']) {
            $user = $_SERVER['PHP_AUTH_USER'];
Пример #12
0
/**
 * Log a warning at level LOG_WARNING.
 */
function warning($string)
{
    logmsg(LOG_WARNING, "warning: {$string}");
}
Пример #13
0
/**
 * Zapise do logu, ktery je definovan v globalnim nastaveni.
 * @deprecated pouzijte radeji metodu logmsg($message, $level)
 * @param string $message Zprava, ktera se ma vypsat do logu
 * @param int $level level logu - PEAR_LOG_EMERG, PEAR_LOG_ALERT, PEAR_LOG_CRIT, PEAR_LOG_ERR,
 * PEAR_LOG_WARNING, PEAR_LOG_NOTICE, PEAR_LOG_INFO, PEAR_LOG_DEBUG
 * PEAR_LOG_DEBUG je defaultni
 */
function err_log($message, $level = PEAR_LOG_DEBUG)
{
    logmsg($message, $level);
}
Пример #14
0
function save_student()
{
    $id = $_POST['0'];
    $firstname = htmlspecialchars($_POST['1']);
    $middlename = htmlspecialchars($_POST['2']);
    $lastname = htmlspecialchars($_POST['3']);
    $born = htmlspecialchars($_POST['4']);
    $studentID = htmlspecialchars($_POST['5']);
    $gender = $_POST['6'];
    $citizenship = $_POST['7'];
    $email = htmlspecialchars($_POST['8']);
    $year = htmlspecialchars($_POST['10']);
    logmsg("year: {$year}");
    db_save_student($id, $firstname, $middlename, $lastname, $born, $studentID, $gender, $citizenship, $email, $year);
}
Пример #15
0
 private function execute($query)
 {
     $query = trim($query);
     list($micros, $secs) = explode(' ', microtime());
     $res = @mysqli_query($this->_connection, $query);
     list($micros2, $secs2) = explode(' ', microtime());
     $elapsed_ms = round(1000 * ($secs2 - $secs + ($micros2 - $micros)));
     if (DEBUG & DEBUG_SQL) {
         global $DEBUG_NUM_QUERIES;
         $DEBUG_NUM_QUERIES++;
         if (isset($_SERVER['REMOTE_ADDR'])) {
             if (defined('DOMJUDGE_API_VERSION')) {
                 logmsg(LOG_DEBUG, "SQL: {$this->database}: {$query} ({$elapsed_ms}ms)\n");
             } else {
                 printf("<p>SQL: {$this->database}: <kbd>%s</kbd> ({$elapsed_ms}ms)</p>\n", specialchars($query));
             }
         } else {
             printf("SQL: {$this->database}: %s ({$elapsed_ms}ms)\n", $query);
         }
     }
     if ($res) {
         return $res;
     }
     if (DEBUG) {
         $backtrace = debug_backtrace();
         $callsite = ' file: ' . $backtrace[2]['file'] . ', ' . ' line: ' . $backtrace[2]['line'] . ', ';
     } else {
         $callsite = '';
     }
     // switch error message depending on errornr.
     switch (mysqli_errno($this->_connection)) {
         case 1062:
             // duplicate key
             throw new UnexpectedValueException("Item with this key already" . " exists.\n" . $callsite . mysqli_error($this->_connection));
         case 1217:
             // foreign key constraint
             throw new UnexpectedValueException("This operation would have" . " brought the database in an inconsistent state,\n" . $callsite . mysqli_error($this->_connection));
         case 2006:
             // MySQL server has gone away
             throw new RuntimeException("MySQL server has gone away");
         default:
             throw new RuntimeException("SQL error, " . $callsite . "Error#" . mysqli_errno($this->_connection) . ": " . mysqli_error($this->_connection) . ", query: '{$query}'");
     }
 }
Пример #16
0
         echo "Updated Portlet Group Permissions for the template user";
     }
     break;
 case "portlet_user_perm":
     $user = get_input('user');
     $portlets = get_input('portlets');
     $pieces = explode(",", $portlets);
     foreach ($pieces as $portlet) {
         $header = str_replace("_", " ", $portlet);
         $value = preg_replace('/.*=(.*)/', '$1', $portlet);
         $header = preg_replace('/(.*)=.*/', '$1', $header);
         $group = getgroup($user);
         if ($header !== "Assign Permissions") {
             // Button name comes through because it's an "input" type
             if ($value == 'true') {
                 logmsg("---\nHeader = {$header}\nValue = {$value}");
                 $sql = "UPDATE ui_layout SET group_access='{$group}' WHERE header='{$header}' and userid=(SELECT id FROM users WHERE username='******')";
                 $result = perform_query($sql, $dbLink, $_SERVER['PHP_SELF']);
                 // logmsg("MySQL Affected Rows = " .mysql_affected_rows() . "\n");
                 if (mysql_affected_rows() != 1) {
                     // User doesn't have an entry (they are probably a new user who hasn't logged in yet)
                     // so we need to insert permissions for them.
                     $sql = "REPLACE INTO ui_layout (userid, pagename, col, header, group_access, content) SELECT (SELECT id FROM users WHERE username='******'),(SELECT DISTINCT pagename from ui_layout where header='{$header}' AND userid=0), (SELECT DISTINCT col from ui_layout where header='{$header}' AND userid=0), '{$header}', '{$group}', (SELECT DISTINCT content from ui_layout where header='{$header}' and userid=0)";
                     perform_query($sql, $dbLink, $_SERVER['PHP_SELF']);
                 }
             } else {
                 $sql = "DELETE FROM ui_layout WHERE group_access='{$group}' AND header='{$header}' and userid=(SELECT id FROM users WHERE username='******')";
                 // echo "Removed $header access for $user<br>";
                 $result = perform_query($sql, $dbLink, $_SERVER['PHP_SELF']);
             }
         }
Пример #17
0
function judge($row)
{
    global $EXITCODES, $myhost, $options, $workdirpath;
    // Set configuration variables for called programs
    putenv('USE_CHROOT=' . (USE_CHROOT ? '1' : ''));
    putenv('SCRIPTTIMELIMIT=' . dbconfig_get_rest('script_timelimit'));
    putenv('SCRIPTMEMLIMIT=' . dbconfig_get_rest('script_memory_limit'));
    putenv('SCRIPTFILELIMIT=' . dbconfig_get_rest('script_filesize_limit'));
    putenv('MEMLIMIT=' . $row['memlimit']);
    putenv('FILELIMIT=' . $row['outputlimit']);
    putenv('PROCLIMIT=' . dbconfig_get_rest('process_limit'));
    $cpuset_opt = "";
    if (isset($options['daemonid'])) {
        $cpuset_opt = "-n {$options['daemonid']}";
    }
    // create workdir for judging
    $workdir = "{$workdirpath}/c{$row['cid']}-s{$row['submitid']}-j{$row['judgingid']}";
    logmsg(LOG_INFO, "Working directory: {$workdir}");
    // If a database gets reset without removing the judging
    // directories, we might hit an old directory: rename it.
    if (file_exists($workdir)) {
        $oldworkdir = $workdir . '-old-' . getmypid() . '-' . strftime('%Y-%m-%d_%H:%M');
        if (!rename($workdir, $oldworkdir)) {
            error("Could not rename stale working directory to '{$oldworkdir}'");
        }
        @chmod($oldworkdir, 0700);
        warning("Found stale working directory; renamed to '{$oldworkdir}'");
    }
    system("mkdir -p '{$workdir}/compile'", $retval);
    if ($retval != 0) {
        error("Could not create '{$workdir}/compile'");
    }
    // Make sure the workdir is accessible for the domjudge-run user.
    // Will be revoked again after this run finished.
    chmod($workdir, 0755);
    if (!chdir($workdir)) {
        error("Could not chdir to '{$workdir}'");
    }
    // Get the source code from the DB and store in local file(s)
    $sources = request('submission_files', 'GET', 'id=' . urlencode($row['submitid']));
    $sources = dj_json_decode($sources);
    $files = array();
    foreach ($sources as $source) {
        $srcfile = "{$workdir}/compile/{$source['filename']}";
        $files[] = "'{$source['filename']}'";
        if (file_put_contents($srcfile, base64_decode($source['content'])) === FALSE) {
            error("Could not create {$srcfile}");
        }
    }
    if (empty($row['compile_script'])) {
        error("No compile script specified for language " . $row['langid'] . ".");
    }
    $execrunpath = fetch_executable($workdirpath, $row['compile_script'], $row['compile_script_md5sum']);
    // Compile the program.
    system(LIBJUDGEDIR . "/compile.sh {$cpuset_opt} '{$execrunpath}' '{$workdir}' " . implode(' ', $files), $retval);
    // what does the exitcode mean?
    if (!isset($EXITCODES[$retval])) {
        alert('error');
        error("Unknown exitcode from compile.sh for s{$row['submitid']}: {$retval}");
    }
    $compile_success = $EXITCODES[$retval] != 'compiler-error';
    // pop the compilation result back into the judging table
    request('judgings/' . urlencode($row['judgingid']), 'PUT', 'judgehost=' . urlencode($myhost) . '&compile_success=' . $compile_success . '&output_compile=' . rest_encode_file($workdir . '/compile.out'));
    // compile error: our job here is done
    if (!$compile_success) {
        // revoke readablity for domjudge-run user to this workdir
        chmod($workdir, 0700);
        logmsg(LOG_NOTICE, "Judging s{$row['submitid']}/j{$row['judgingid']}: compile error");
        return;
    }
    // Optionally create chroot environment
    if (USE_CHROOT && CHROOT_SCRIPT) {
        logmsg(LOG_INFO, "executing chroot script: '" . CHROOT_SCRIPT . " start'");
        system(LIBJUDGEDIR . '/' . CHROOT_SCRIPT . ' start', $retval);
        if ($retval != 0) {
            error("chroot script exited with exitcode {$retval}");
        }
    }
    $totalcases = 0;
    while (TRUE) {
        // get the next testcase
        $testcase = request('testcases', 'GET', 'judgingid=' . urlencode($row['judgingid']));
        $tc = dj_json_decode($testcase);
        // empty means: no more testcases for this judging.
        if (empty($tc)) {
            break;
        }
        $totalcases++;
        logmsg(LOG_DEBUG, "Running testcase {$tc['rank']}...");
        $testcasedir = $workdir . "/testcase" . sprintf('%03d', $tc['rank']);
        // Get both in- and output files, only if we didn't have them already.
        $tcfile = array();
        $fetched = array();
        foreach (array('input', 'output') as $inout) {
            $tcfile[$inout] = "{$workdirpath}/testcase/testcase.{$tc['probid']}.{$tc['rank']}." . $tc['md5sum_' . $inout] . "." . substr($inout, 0, -3);
            if (!file_exists($tcfile[$inout])) {
                $content = request('testcase_files', 'GET', 'testcaseid=' . urlencode($tc['testcaseid']) . '&' . $inout);
                $content = base64_decode(dj_json_decode($content));
                if (file_put_contents($tcfile[$inout] . ".new", $content) === FALSE) {
                    error("Could not create {$tcfile[$inout]}.new");
                }
                unset($content);
                if (md5_file("{$tcfile[$inout]}.new") === $tc['md5sum_' . $inout]) {
                    rename("{$tcfile[$inout]}.new", $tcfile[$inout]);
                } else {
                    error("File corrupted during download.");
                }
                $fetched[] = $inout;
            }
            // sanity check (NOTE: performance impact is negligible with 5
            // testcases and total 3.3 MB of data)
            if (md5_file($tcfile[$inout]) !== $tc['md5sum_' . $inout]) {
                error("File corrupted: md5sum mismatch: " . $tcfile[$inout]);
            }
        }
        // Only log downloading input and/or output testdata once.
        if (count($fetched) > 0) {
            logmsg(LOG_INFO, "Fetched new " . implode($fetched, ',') . " testcase {$tc['rank']} for problem p{$tc['probid']}");
        }
        // Copy program with all possible additional files to testcase
        // dir. Use hardlinks to preserve space with big executables.
        $programdir = $testcasedir . '/execdir';
        system("mkdir -p '{$programdir}'", $retval);
        if ($retval != 0) {
            error("Could not create directory '{$programdir}'");
        }
        system("cp -PR '{$workdir}'/compile/* '{$programdir}'", $retval);
        if ($retval != 0) {
            error("Could not copy program to '{$programdir}'");
        }
        // do the actual test-run
        $hardtimelimit = $row['maxruntime'] + overshoot_time($row['maxruntime'], dbconfig_get_rest('timelimit_overshoot'));
        $compare_runpath = fetch_executable($workdirpath, $row['compare'], $row['compare_md5sum']);
        $run_runpath = fetch_executable($workdirpath, $row['run'], $row['run_md5sum']);
        system(LIBJUDGEDIR . "/testcase_run.sh {$cpuset_opt} {$tcfile['input']} {$tcfile['output']} " . "{$row['maxruntime']}:{$hardtimelimit} '{$testcasedir}' " . "'{$run_runpath}' '{$compare_runpath}' '{$row['compare_args']}'", $retval);
        // what does the exitcode mean?
        if (!isset($EXITCODES[$retval])) {
            alert('error');
            error("Unknown exitcode from testcase_run.sh for s{$row['submitid']}, " . "testcase {$tc['rank']}: {$retval}");
        }
        $result = $EXITCODES[$retval];
        // Try to read metadata from file
        $runtime = NULL;
        if (is_readable($testcasedir . '/program.meta')) {
            $metadata = spyc_load_file($testcasedir . '/program.meta');
            if (isset($metadata['time-used'])) {
                $runtime = @$metadata[$metadata['time-used']];
            }
        }
        request('judging_runs', 'POST', 'judgingid=' . urlencode($row['judgingid']) . '&testcaseid=' . urlencode($tc['testcaseid']) . '&runresult=' . urlencode($result) . '&runtime=' . urlencode($runtime) . '&judgehost=' . urlencode($myhost) . '&output_run=' . rest_encode_file($testcasedir . '/program.out', FALSE) . '&output_error=' . rest_encode_file($testcasedir . '/program.err') . '&output_system=' . rest_encode_file($testcasedir . '/system.out') . '&output_diff=' . rest_encode_file($testcasedir . '/feedback/judgemessage.txt'));
        logmsg(LOG_DEBUG, "Testcase {$tc['rank']} done, result: " . $result);
    }
    // end: for each testcase
    // revoke readablity for domjudge-run user to this workdir
    chmod($workdir, 0700);
    // Optionally destroy chroot environment
    if (USE_CHROOT && CHROOT_SCRIPT) {
        logmsg(LOG_INFO, "executing chroot script: '" . CHROOT_SCRIPT . " stop'");
        system(LIBJUDGEDIR . '/' . CHROOT_SCRIPT . ' stop', $retval);
        if ($retval != 0) {
            error("chroot script exited with exitcode {$retval}");
        }
    }
    // Sanity check: need to have had at least one testcase
    if ($totalcases == 0) {
        logmsg(LOG_WARNING, "No testcases judged for s{$row['submitid']}/j{$row['judgingid']}!");
    }
    // done!
    logmsg(LOG_NOTICE, "Judging s{$row['submitid']}/j{$row['judgingid']} finished");
}
Пример #18
0
function db_delete_files($ids)
{
    global $link;
    mysqli_set_charset($link, "utf8");
    $stm = $link->stmt_init();
    $stm->prepare('DELETE FROM FILES WHERE ID=?');
    foreach ($ids as $id) {
        logmsg("del file " . $id);
        $stm->bind_param('i', $id);
        $stm->execute();
        db_append_to_log('FILES', $id, 'remove', 'file removed', $id);
    }
    $stm->close();
    if (count($ids) > 0) {
        recycle_files($ids);
    }
}
Пример #19
0
/**
 * Judging_Runs
 */
function judging_runs_POST($args)
{
    global $DB, $api;
    checkargs($args, array('judgingid', 'testcaseid', 'runresult', 'runtime', 'output_run', 'output_diff', 'output_error', 'output_system', 'judgehost'));
    $results_remap = dbconfig_get('results_remap');
    $results_prio = dbconfig_get('results_prio');
    if (array_key_exists($args['runresult'], $results_remap)) {
        logmsg(LOG_INFO, "Testcase {$args['testcaseid']} remapping result " . $args['runresult'] . " -> " . $results_remap[$args['runresult']]);
        $args['runresult'] = $results_remap[$args['runresult']];
    }
    $DB->q('INSERT INTO judging_run (judgingid, testcaseid, runresult,
	        runtime, output_run, output_diff, output_error, output_system)
	        VALUES (%i, %i, %s, %f, %s, %s, %s, %s)', $args['judgingid'], $args['testcaseid'], $args['runresult'], $args['runtime'], base64_decode($args['output_run']), base64_decode($args['output_diff']), base64_decode($args['output_error']), base64_decode($args['output_system']));
    // result of this judging_run has been stored. now check whether
    // we're done or if more testcases need to be judged.
    $probid = $DB->q('VALUE SELECT probid FROM testcase
	                  WHERE testcaseid = %i', $args['testcaseid']);
    $runresults = $DB->q('COLUMN SELECT runresult
	                      FROM judging_run LEFT JOIN testcase USING(testcaseid)
	                      WHERE judgingid = %i ORDER BY rank', $args['judgingid']);
    $numtestcases = $DB->q('VALUE SELECT count(*) FROM testcase WHERE probid = %i', $probid);
    $allresults = array_pad($runresults, $numtestcases, null);
    $before = $DB->q('VALUE SELECT result FROM judging WHERE judgingid = %i', $args['judgingid']);
    if (($result = getFinalResult($allresults, $results_prio)) !== NULL) {
        // Lookup global lazy evaluation of results setting and
        // possible problem specific override.
        $lazy_eval = dbconfig_get('lazy_eval_results', true);
        $prob_lazy = $DB->q('MAYBEVALUE SELECT cp.lazy_eval_results
		                     FROM judging j
		                     LEFT JOIN submission s USING(submitid)
		                     LEFT JOIN contestproblem cp ON (cp.cid=j.cid AND cp.probid=s.probid)
		                     WHERE judgingid = %i', $args['judgingid']);
        if (isset($prob_lazy)) {
            $lazy_eval = (bool) $prob_lazy;
        }
        if (count($runresults) == $numtestcases || $lazy_eval) {
            // NOTE: setting endtime here determines in testcases_GET
            // whether a next testcase will be handed out.
            $DB->q('UPDATE judging SET result = %s, endtime = %s
			        WHERE judgingid = %i', $result, now(), $args['judgingid']);
        } else {
            $DB->q('UPDATE judging SET result = %s
			        WHERE judgingid = %i', $result, $args['judgingid']);
        }
        // Only update if the current result is different from what we
        // had before. This should only happen when the old result was
        // NULL.
        if ($before !== $result) {
            if ($before !== NULL) {
                error('internal bug: the evaluated result changed during judging');
            }
            $row = $DB->q('TUPLE SELECT s.cid, s.teamid, s.probid, s.langid, s.submitid
			               FROM judging
			               LEFT JOIN submission s USING(submitid)
			               WHERE judgingid = %i', $args['judgingid']);
            calcScoreRow($row['cid'], $row['teamid'], $row['probid']);
            // We call alert here before possible validation. Note
            // that this means that these alert messages should be
            // treated as confidential information.
            alert($result === 'correct' ? 'accept' : 'reject', "submission {$row['submitid']}, judging {$args['judgingid']}: {$result}");
            // log to event table if no verification required
            // (case of verification required is handled in www/jury/verify.php)
            if (!dbconfig_get('verification_required', 0)) {
                $DB->q('INSERT INTO event (eventtime, cid, teamid, langid, probid,
				        submitid, judgingid, description)
				        VALUES(%s, %i, %i, %s, %i, %i, %i, "problem judged")', now(), $row['cid'], $row['teamid'], $row['langid'], $row['probid'], $row['submitid'], $args['judgingid']);
                if ($result == 'correct') {
                    // prevent duplicate balloons in case of multiple correct submissions
                    $numcorrect = $DB->q('VALUE SELECT count(submitid)
					                      FROM balloon
					                      LEFT JOIN submission USING(submitid)
					                      WHERE valid = 1 AND probid = %i
					                      AND teamid = %i AND cid = %i', $row['probid'], $row['teamid'], $row['cid']);
                    if ($numcorrect == 0) {
                        $balloons_enabled = (bool) $DB->q("VALUE SELECT process_balloons\n\t\t\t\t\t\t                                  FROM contest WHERE cid = %i", $row['cid']);
                        if ($balloons_enabled) {
                            $DB->q('INSERT INTO balloon (submitid) VALUES(%i)', $row['submitid']);
                        }
                    }
                }
            }
            auditlog('judging', $args['judgingid'], 'judged', $result, $args['judgehost']);
        }
    }
    $DB->q('UPDATE judgehost SET polltime = %s WHERE hostname = %s', now(), $args['judgehost']);
    return '';
}
Пример #20
0
function saveParticipants($participants)
{
    global $participants_file_path;
    global $sites;
    // list of sites allow for this user
    // create a list of sites to save
    $sitesToSave = array();
    foreach ($participants as $key => $participant) {
        // if this participant contains a site key and
        // the site name is not already in sitesToSave and
        // the site name is in the list of allowed sites
        if (isset($participant['site']) && !in_array($participant['site'], $sitesToSave) && in_array($participant['site'], $sites)) {
            $sitesToSave[] = $participant['site'];
            // append the site name to sitesToSave
        }
    }
    for ($i = 0; $i < count($sitesToSave); $i++) {
        $participants_file = $participants_file_path . $sites[$i] . "/participants.json";
        // create a list of events for this site
        $d = array();
        foreach ($participants as $key => &$participant) {
            // if this participant contains a site key and
            // the site name is the same as the current site
            if (isset($participant['site']) && $participant['site'] == $sitesToSave[$i]) {
                unset($participant['site']);
                // remove the site key
                $d[] = $participant;
            }
        }
        // parse permissions
        if (!file_exists($participants_file)) {
            echo 'error: participants file ' . $participants_file . ' does not exist';
            return;
        }
        if (!is_writable($participants_file)) {
            echo 'error: cannot write participants file (' . $participants_file . ')';
            return;
        }
        // lets sort the participants alphabetically first
        //sort($participants);
        //echo ("{ \"message\": \"save these values: " . join($participants) . "\"}");
        // be more careful here, we need to write first to a new file, make sure that this
        // works and copy the result over to the pw_file
        $testfn = $participants_file . '_test';
        file_put_contents($testfn, json_encode($participants, JSON_PRETTY_PRINT));
        if (filesize($testfn) > 0) {
            // seems to have worked, now rename this file to pw_file
            rename($testfn, $participants_file);
        } else {
            logmsg("Error: could not write file to " . $testfn);
            syslog(LOG_EMERG, 'error: could not write file into ' . $testfn);
        }
    }
}
Пример #21
0
function show_edit_form($column_labels, $data, $column_types, $selectdata)
{
    global $filter_url, $selected_year;
    $menuitem = $_GET['m'];
    $sort_url = determine_sort_url();
    if (strlen($selected_year) > 0) {
        $yr = '&y=' . $selected_year;
    } else {
        $yr = '';
    }
    print '<form method="post" action="index.php?m=' . $menuitem . $sort_url . $yr . '&act' . $filter_url . '" enctype="multipart/form-data">';
    print '<table><thead><tr><th colspan="2">Edit the record</td></tr></thead><tbody><tr>';
    $cnt = 0;
    $sel = 0;
    foreach ($column_labels as $label) {
        print "<tr><td>{$label}</td><td>";
        if ($column_types[$cnt] === 'RDONLY') {
            print '<input name="' . $cnt . '" type="hidden" value="' . $data[$cnt] . '" />' . $data[$cnt];
        } else {
            if ($column_types[$cnt] === '*') {
                print '<select name="' . $cnt . '">' . "\n";
                $selopt = $data[$cnt];
                if (is_array($selopt)) {
                    $selopt = $selopt[0];
                }
                logmsg("selopt={$selopt}");
                foreach ($selectdata[$sel] as $option) {
                    print '  <option value="' . $option[0] . '"';
                    if ($option[0] == $selopt) {
                        print ' selected';
                    }
                    print '>' . $option[1] . "</option>\n";
                }
                print "</select>\n";
                $sel++;
            } else {
                if ($column_types[$cnt] === '+') {
                    $selopt = $data[$cnt];
                    $selcnt = 0;
                    $selection = '<br />add: <select name="' . $cnt . '">' . "\n";
                    $seloptids = array();
                    foreach ($selopt as $opt) {
                        $seloptids[] = $opt[0];
                    }
                    foreach ($selectdata[$sel] as $option) {
                        if (in_array($option[0], $seloptids)) {
                            if ($selcnt > 0) {
                                print '<br />';
                            }
                            print $option[1];
                            print '<input type="hidden" name="listid_' . $cnt . '_' . $selcnt . '" value="' . $option[0] . '" />' . "\n";
                            $itemname = 'deletelist_' . $cnt . '_' . $selcnt;
                            print '<input type="image" src="images/recyclebin.gif" alt="delete item" title="delete item" name="' . $itemname . '" id="' . $itemname . '" />' . "\n";
                            $selcnt++;
                        } else {
                            $selection = $selection . ' <option value="' . $option[0] . '">' . $option[1] . "</option>\n";
                        }
                    }
                    if ($selcnt == 0) {
                        print "none";
                    }
                    print $selection;
                    print '</select> <input type="submit" name="AddOption" value="add" />';
                    $sel++;
                } else {
                    if ($column_types[$cnt] === 'files') {
                        $filecnt = 0;
                        print_r($data);
                        foreach ($data[$cnt] as $file) {
                            print $file[2] . ': ' . $file[1] . "\n";
                            $itemname = 'deletefile_' . $cnt . '_' . $filecnt;
                            print '<input type="hidden" name="fileid_' . $cnt . '_' . $filecnt . '" value="' . $file[0] . '" />' . "\n";
                            $filecnt++;
                            print '<input type="image" src="images/recyclebin.gif" alt="recycle file" title="recycle file" name="' . $itemname . '" id="' . $itemname . '" /><br />' . "\n";
                        }
                        print 'add: <input type="text" size="40" name="desc' . $cnt . '" value="enter file description" /><br />';
                        print "\n";
                        print '<input type="file" name="filename' . $cnt . '" id="filename' . $cnt . '" /> <input type="submit" name="upload' . $cnt . '" value="Upload" />';
                        print "\n";
                    } else {
                        if ($column_types[$cnt] === 'checkbox') {
                            print '<input name="' . $cnt . '" type="checkbox"';
                            if (count($data) > 0) {
                                if ($data[$cnt] > 0) {
                                    print ' checked';
                                }
                            }
                            print ' />';
                        } else {
                            $size = "";
                            $dptr = 0;
                            while (ctype_digit($column_types[$cnt][$dptr])) {
                                $size = $size . $column_types[$cnt][$dptr++];
                            }
                            $ctype = substr($column_types[$cnt], $dptr);
                            if (count($size) === 0) {
                                $size = 30;
                            }
                            print '<input name="' . $cnt . '" type="' . $ctype . '" size="' . $size . '"';
                            if (count($data) > 0) {
                                print ' value="' . $data[$cnt] . '"';
                            }
                            print ' />';
                        }
                    }
                }
            }
        }
        print "</td></tr>\n";
        $cnt++;
    }
    print '</tbody></table><br />';
    print "\n";
    print '<input type="submit" name="Save" value="save" /> ';
    print '<input type="submit" name="Cancel" value="cancel" /></form>';
    print "\n";
}
Пример #22
0
 /**
  * slouzi pro nakesovani odpovedi dotazu typu SELECT pokud nekolik modulu na strance vola backend se stejnymi parametry
  * soucasne promazava cache po stanovenem limitu a umoznuje sdileni odpovedi vice aplikacnimi servery
  * @param string $query SQL dotaz SELECT ktery se ma vykonat
  * @param string $Benchmarked je-li vyplneno, bude zalogovan banchmark test do err_log a text bude pouzit jako identifikator ve vypisu logu
  * @param int $maxold pocet minut jak muze byt vysledek stary, jinak dojde k jeho aktualizaci (default 0) 0=cache off
  * @return array $out["rows"] ... radky s vysledky s omezenim limit, $out["count"] ... pocet nalezenych vysedku bez omezeni limitu
  */
 public function query($query, $params = array(), $benchMarked = "", $maxOld = 0)
 {
     if (!is_array($params)) {
         $params = array($params);
     }
     $time_start = microtime(true);
     $isCache = $maxOld > 0 && !$this->isUpdate($query);
     $actualPDO = $this->getPDO($query, $isCache);
     $connectionInfo = $actualPDO === $this->pdoMaster ? $this->masterHost . "/" . $this->masterDBName . " (master)" : ($connectionInfo = $this->slaveHost . "/" . $this->slaveDBName . " (slave)");
     if ($isCache) {
         // vypocteme id dotazu pro cache
         $checksum = sprintf("%u\n", crc32($query . print_r_log($params)));
         // zjistime zda uz takovy dotaz neprobehl a zda neni po expiraci
         $stmt = $actualPDO->prepare("SELECT *,TIMESTAMPDIFF(MINUTE,created,NOW()) AS oldmin FROM cache_sql WHERE sql_hash=?");
         $stmt->execute(array($checksum));
         $cache = $stmt->fetch();
         $isCache = $stmt->rowCount() > 0 && $cache['oldmin'] < $maxOld;
     }
     //znovu se ptam na stejnou podminku, protoze se mohla mezitim zmenit
     if ($isCache) {
         $out = unserialize($cache['result']);
     } else {
         // neprobehl nebo vyexpiroval - provedeme dotaz a vysledek ulozime do cache
         $stmt = $actualPDO->prepare($query);
         $stmt->setFetchMode(PDO::FETCH_ASSOC);
         $success = $stmt->execute($params);
         $errorInfo = $stmt->errorInfo();
         $out['errorCode'] = $errorInfo[0];
         $out['errorText'] = $errorInfo[2];
         $out["rows"] = $stmt->fetchAll();
         $out["lastInsertId"] = $actualPDO->lastInsertId();
         $out["affectedRows"] = $stmt->rowCount();
         if (!SQLEngine::isError($out)) {
             $out['errorText'] = "";
             $rs1 = $actualPDO->query("SELECT FOUND_ROWS() as pocet")->fetch();
             $out['count'] = $rs1['pocet'];
             //pokud nezafunguje found_rows a vrati 0-1 radku, tak pro jistotu si vezmu pocet z vracenych radku
             if ($out['count'] + 0 < 2) {
                 $out['count'] = count($out["rows"]);
             }
         } else {
             logmsg("SQLERROR:" . self::getErrorCode($out) . ":" . self::getErrorText($out) . "\n" . $query . "\n" . print_r_log($params), PEAR_LOG_CRIT);
         }
         if ($maxOld > 0) {
             // ulozime vysledek do cache pokud nepresahuje limitni delku mediumtext 2^24
             $serial = serialize($out);
             if (strlen($serial) < pow(2, 24) && strlen($serial) > 0) {
                 $sql = "REPLACE cache_sql SET sql_hash=?, result=?";
                 $stmt = $actualPDO->prepare($sql);
                 $stmt->execute(array($checksum, $serial));
             }
         }
     }
     $time_end = microtime(true);
     $time = $time_end - $time_start;
     global $conf;
     if ($conf["enableProfiler"]) {
         $stmt = $actualPDO->prepare("select count(*) as pocet from inzerat");
         $stmt->setFetchMode(PDO::FETCH_ASSOC);
         $success = $stmt->execute(array());
         $rs1 = $stmt->fetch();
         $profilerInsert = "INSERT INTO profiler_data (request_id, request_uri, startSql, stopSql, query, params, pocetInzeratu, callStack) VALUES (?, ?, ?, ?, ?, ?, ?, ?);";
         $e = new Exception();
         $profileParams = array($_SERVER["REQUEST_TIME"], $_SERVER["REQUEST_URI"], $time_start, $time_end, $query, serialize($params), $rs1["pocet"], $e->getTraceAsString());
         $stmt = $this->getPDOMaster()->prepare($profilerInsert);
         $stmt->execute($profileParams);
     }
     logmsg("BENCHMARK {$benchMarked} STOP for connection " . $connectionInfo . " " . round($time, 3) . "\n" . print_r_log($query) . "\n" . print_r_log($params), PEAR_LOG_DEBUG);
     return $out;
 }
Пример #23
0
</style>
</head>
<body style="font-family: Arial, Helvetica, sans-serif;">
<table width="1200px"><tbody><tr><td><img src="images/logo_uk.jpg" width="150px" /></td>
<td style=" text-align: center; "><b>UNIVERZITA KOMENSKÉHO V BRATISLAVE</b><br />
       Fakulta matematiky, fyziky a informatiky<br />
       Mlynská dolina, 84148 Bratislava<br />
       Študijné oddelenie<br />
       tel.: 02/65427086, 65426720, fax: 02/65425882</td>
<td style=" text-align: right; "><img src="images/logo_fmfi.jpg" width="150px" /></td></tr></tbody></table><br />
<table width="1200px"><tbody><tr><td>Meno studenta: 
<?php 
    $tv = db_retrieve_travel_byID($id, TRUE);
    $id_student = $tv[5];
    $id_program = $tv[6];
    logmsg("s: {$id_student} p: {$id_program}");
    $stsp = db_retrieve_study_prog_and_student_details($id_program, $id_student);
    $agr = db_retrieve_agreement_byID($tv[2]);
    $courses = $tv[14];
    print $stsp[1];
    print '</td><td>Ročník a štúdijný program: ';
    print $tv[1] . ' - ' . $stsp[0];
    print '</td></tr><tr><td>Partnerská univerzita: ';
    print $agr[1][1] . ' (' . $agr[1][2] . ')';
    print '</td><td>Obdobie: ';
    if ($tv[3] !== '0000-00-00') {
        print $tv[3];
    } else {
        print 'neznámy termín nástupu';
    }
    print ' - ';
Пример #24
0
/**
 * This function takes a (set of) temporary file(s) of a submission,
 * validates it and puts it into the database. Additionally it
 * moves it to a backup storage.
 */
function submit_solution($team, $prob, $contest, $lang, $files, $filenames, $origsubmitid = NULL)
{
    global $DB;
    if (empty($team)) {
        error("No value for Team.");
    }
    if (empty($prob)) {
        error("No value for Problem.");
    }
    if (empty($contest)) {
        error("No value for Contest.");
    }
    if (empty($lang)) {
        error("No value for Language.");
    }
    if (!is_array($files) || count($files) == 0) {
        error("No files specified.");
    }
    if (count($files) > dbconfig_get('sourcefiles_limit', 100)) {
        error("Tried to submit more than the allowed number of source files.");
    }
    if (!is_array($filenames) || count($filenames) != count($files)) {
        error("Nonmatching (number of) filenames specified.");
    }
    if (count($filenames) != count(array_unique($filenames))) {
        error("Duplicate filenames detected.");
    }
    $sourcesize = dbconfig_get('sourcesize_limit');
    // If no contest has started yet, refuse submissions.
    $now = now();
    $contestdata = $DB->q('MAYBETUPLE SELECT starttime,endtime FROM contest WHERE cid = %i', $contest);
    if (!isset($contestdata)) {
        error("Contest c{$contest} not found.");
    }
    if (difftime($contestdata['starttime'], $now) > 0) {
        error("The contest is closed, no submissions accepted. [c{$contest}]");
    }
    // Check 2: valid parameters?
    if (!($langid = $DB->q('MAYBEVALUE SELECT langid FROM language
	                        WHERE langid = %s AND allow_submit = 1', $lang))) {
        error("Language '{$lang}' not found in database or not submittable.");
    }
    if (!($teamid = $DB->q('MAYBEVALUE SELECT teamid FROM team
	                        WHERE teamid = %i AND enabled = 1', $team))) {
        error("Team '{$team}' not found in database or not enabled.");
    }
    $probdata = $DB->q('MAYBETUPLE SELECT probid, points FROM problem
	                    INNER JOIN contestproblem USING (probid)
	                    WHERE probid = %s AND cid = %i AND allow_submit = 1', $prob, $contest);
    if (empty($probdata)) {
        error("Problem p{$prob} not found in database or not submittable [c{$contest}].");
    } else {
        $points = $probdata['points'];
        $probid = $probdata['probid'];
    }
    // Reindex arrays numerically to allow simultaneously iterating
    // over both $files and $filenames.
    $files = array_values($files);
    $filenames = array_values($filenames);
    $totalsize = 0;
    for ($i = 0; $i < count($files); $i++) {
        if (!is_readable($files[$i])) {
            error("File '" . $files[$i] . "' not found (or not readable).");
        }
        if (!preg_match(FILENAME_REGEX, $filenames[$i])) {
            error("Illegal filename '" . $filenames[$i] . "'.");
        }
        $totalsize += filesize($files[$i]);
    }
    if ($totalsize > $sourcesize * 1024) {
        error("Submission file(s) are larger than {$sourcesize} kB.");
    }
    logmsg(LOG_INFO, "input verified");
    // Insert submission into the database
    $id = $DB->q('RETURNID INSERT INTO submission
	              (cid, teamid, probid, langid, submittime, origsubmitid)
	              VALUES (%i, %i, %i, %s, %s, %i)', $contest, $teamid, $probid, $langid, $now, $origsubmitid);
    for ($rank = 0; $rank < count($files); $rank++) {
        $DB->q('INSERT INTO submission_file
		        (submitid, filename, rank, sourcecode) VALUES (%i, %s, %i, %s)', $id, $filenames[$rank], $rank, getFileContents($files[$rank], false));
    }
    // Recalculate scoreboard cache for pending submissions
    calcScoreRow($contest, $teamid, $probid);
    // Log to event table
    $DB->q('INSERT INTO event (eventtime, cid, teamid, langid, probid, submitid, description)
	        VALUES(%s, %i, %i, %s, %i, %i, "problem submitted")', now(), $contest, $teamid, $langid, $probid, $id);
    if (is_writable(SUBMITDIR)) {
        // Copy the submission to SUBMITDIR for safe-keeping
        for ($rank = 0; $rank < count($files); $rank++) {
            $fdata = array('cid' => $contest, 'submitid' => $id, 'teamid' => $teamid, 'probid' => $probid, 'langid' => $langid, 'rank' => $rank, 'filename' => $filenames[$rank]);
            $tofile = SUBMITDIR . '/' . getSourceFilename($fdata);
            if (!@copy($files[$rank], $tofile)) {
                warning("Could not copy '" . $files[$rank] . "' to '" . $tofile . "'");
            }
        }
    } else {
        logmsg(LOG_DEBUG, "SUBMITDIR not writable, skipping");
    }
    if (difftime($contestdata['endtime'], $now) <= 0) {
        logmsg(LOG_INFO, "The contest is closed, submission stored but not processed. [c{$contest}]");
    }
    return $id;
}