function newuserwelcome($options, $content)
{
    if (!is_user_logged_in()) {
        $ulog = wp_login_url(cscurl('homepage'));
        $uuse = cscurl('usage');
        return "<em>" . sprintf(__t('New around here? Read <a %1$s>Using this Website</a>. You can also <a %2$s>click here to create an account or log in</a>.'), "class='open-same-window' href='{$uuse}'", "class='open-same-window' href='{$ulog}'") . "</em><br/>";
    }
    return "";
}
function pyLinkHandler($options, $content)
{
    $code = softSafeDereference($options["code"]);
    $r = '';
    $r .= '<a href="' . cscurl('console') . "?consolecode=" . rawurlencode($code) . '" target="_blank">';
    $r .= $content;
    $r .= '</a>';
    return $r;
}
function send($problem_info, $from, $to, $student, $slug, $body, $noreply)
{
    global $wpdb, $current_user, $lang;
    $unanswered = getUserID() == $student ? 1 : 0;
    if (getUserID() != $student) {
        $wpdb->update($wpdb->prefix . 'pb_mail', array('unanswered' => 0), array('unanswered' => 1, 'ustudent' => $student, 'problem' => $slug));
    }
    if ($noreply != 'false') {
        // don't redirect
        return "#";
    }
    $insert_to = $to;
    if ($to == 0 && $lang != 'en') {
        $insert_to = getSoft(unserialize(CSCIRCLES_ASST_ID_MAP), $lang, $insert_to);
    }
    $wpdb->insert($wpdb->prefix . 'pb_mail', array('ufrom' => $from, 'uto' => $insert_to, 'ustudent' => $student, 'problem' => $slug, 'body' => $body, 'unanswered' => $unanswered), array('%d', '%d', '%d', '%s', '%s', '%d'));
    $mailref = $wpdb->insert_id;
    if (userIsAdmin() || userIsAssistant()) {
        $mFrom = '"' . __t("CS Circles Assistant") . '" <' . CSCIRCLES_BOUNCE_EMAIL . '>';
    } else {
        $mFrom = '"' . $current_user->user_login . '" <' . $current_user->user_email . '>';
    }
    $subject = __t('CS Circles') . ' - ' . __t('message about') . ' ' . $problem_info['publicname'];
    $contents = $body . "\n===\n";
    $contents .= __t("To send a reply message, please visit") . "\n";
    $contents .= cscurl('mail') . "?who={$student}&what={$slug}&which={$mailref}#m\n";
    $contents .= __t("Problem URL:") . " " . $problem_info['url'] . "\n";
    $contents .= "[" . __t("Sent by CS Circles") . " " . cscurl("homepage") . "]";
    if ($to == 0) {
        // same fallback as admin-options.php
        $to_emailaddr = get_option('cscircles_asst_email', get_userdata(1)->user_email);
        $tmp = getSoft(unserialize(CSCIRCLES_ASST_ID_MAP), $lang, -1);
        if ($lang != 'en' && $tmp != -1) {
            $to_emailaddr = get_user_by('id', $tmp)->user_email;
        }
    } else {
        $to_emailaddr = get_user_by('id', $to)->user_email;
    }
    //pyboxlog($mFrom . " " . $to_emailaddr . " " . $subject . " " . $contents);
    pb_mail($mFrom, $to_emailaddr, $subject, $contents);
    if (get_the_author_meta('pbnocc', getUserID()) != 'true') {
        $to_desc = $to == 0 ? "the CS Circles Assistant" : get_user_by('id', $to)->user_login;
        pb_mail($mFrom, $current_user->user_email, __t("SENT:") . " " . $subject, sprintf(__t("THIS IS A COPY of a message you sent to %s."), $to_desc) . "\n\n" . $contents);
    }
    return $mailref;
}
function pyBoxHead()
{
    echo "<script type='text/javascript'>\n";
    printJSTranslation();
    echo sprintf("var SUBMITURL = '%s';\n", USUBMIT);
    echo sprintf("var SETCOMPLETEDURL = '%s';\n", USETCOMPLETED);
    echo sprintf("var CONSOLEURL = '%s';\n", cscurl('console'));
    echo sprintf("var FILESURL = '%s';\n", UFILES);
    echo sprintf("var HISTORYURL = '%s';\n", UHISTORY);
    echo sprintf("var VISUALIZEURL = '%s';\n", cscurl('visualize'));
    echo sprintf("var MESSAGEURL = '%s';\n", UMESSAGE);
    echo sprintf("var MAILURL = '%s';\n", cscurl('mail'));
    echo sprintf("var DEFAULTTIMEOUTMS = '%s';\n", (WALLFACTOR * 1 + WALLBUFFER) * 1000);
    echo sprintf("var PB_LANG4 = '%s';\n", currLang4());
    echo "</script>\n";
    echo '<link type="text/css" rel="stylesheet" href="' . UPYBOXCSS . '" />' . "\n";
    echo '<script type="text/javascript" src="' . UPYBOXJS . '"></script>' . "\n";
    echo "<link rel='stylesheet' type='text/css' href='" . UPYBOX . "customizations-codemirror/codemirror-specific.css'>\n";
    // variant of codemirror.css
    echo "<link rel='stylesheet' type='text/css' href='" . UPYBOX . "customizations-codemirror/codemirror-extras.css'>\n";
    // added styling
    echo "<link rel='stylesheet' type='text/css' href='" . UPYBOX . "customizations-codemirror/textmate.css'>\n";
    // theme
    echo "<script type='text/javascript' src='" . UCODEMIRROR3 . "lib/codemirror.js'></script>\n";
    echo "<script type='text/javascript' src='" . UCODEMIRROR3 . "mode/python/python.js'></script>\n";
    echo "<script type='text/javascript' src='" . UFLEXIGRID . "js/flexigrid.js'></script>\n";
    echo '<link type="text/css" rel="stylesheet" href="' . UFLEXIGRID . 'css/flexigrid.css" />' . "\n";
    if (stripos($_SERVER["HTTP_USER_AGENT"], 'MSIE') !== FALSE) {
        echo '<style type="text/css"> li.pyscrambleLI {height: 26px;} </style>' . "\n";
    }
    if (stripos($_SERVER["HTTP_USER_AGENT"], 'FIREFOX') !== FALSE) {
        echo '<style type="text/css"> .pybox textarea {white-space: nowrap;} </style>' . "\n";
    }
    global $pyRenderCount;
    $pyRenderCount = 0;
    global $popupBoxen;
    $popupBoxen = "";
}
/************* preliminary stuff *************/
header("Content-type: text/plain; charset=utf8");
require_once "include-to-load-wp.php";
foreach ($_REQUEST as $k => $v) {
    $_REQUEST[$k] = stripslashes($v);
}
if (!array_key_exists('user_script', $_REQUEST)) {
    echo "Error, missing inputs";
    return;
}
if (!array_key_exists('raw_input_json', $_REQUEST)) {
    $_REQUEST['raw_input_json'] = '';
}
if (strlen(print_r($_REQUEST, TRUE)) > POSTLIMIT) {
    pyboxlog("action-optv3.php got too many bytes of data:" . strlen(print_r($_REQUEST, TRUE)));
    return sprintf(__t('Submitted data (program and/or test input) ' . 'too large. Reduce size or <a href = "%s">' . 'run at home</a>.'), cscurl('install'));
}
global $wpdb;
/************* check for a cached version *************/
$cached_result = NULL;
$basehash = md5($_REQUEST['user_script'] . "\t\t\t" . $_REQUEST['raw_input_json']) . '-viz';
$versionedhash = $basehash . VIZ_VERSION;
$dontCache = strstr($_REQUEST['user_script'], 'random') !== FALSE;
if (!$dontCache) {
    // don't cache if randomized
    $the_count = $wpdb->get_var($wpdb->prepare("SELECT count(1) FROM {$wpdb->prefix}pb_submissions\nWHERE hash LIKE %s LIMIT 4", $basehash . '%'));
    $cached_result = $wpdb->get_var($wpdb->prepare("SELECT result FROM {$wpdb->prefix}pb_submissions\nWHERE hash = %s AND result is NOT NULL LIMIT 1", $versionedhash));
    // if cached_result is NULL, we still have to compute it anyway
}
/************* do logging *************/
// save things to build up the cache count
function reselector(&$students, $cstudents)
{
    global $wpdb;
    $problem_table = $wpdb->prefix . "pb_problems";
    $problems = $wpdb->get_results("SELECT * FROM {$problem_table} WHERE facultative = 0 AND lang = '" . pll_current_language() . "' AND lesson IS NOT NULL ORDER BY lesson ASC, boxid ASC", ARRAY_A);
    $problemsByNumber = array();
    foreach ($problems as $prow) {
        $problemsByNumber[$prow['slug']] = $prow;
    }
    $gp = getSoft($_GET, "what", "");
    if ($gp != "" && $gp != "console" && !array_key_exists($gp, $problemsByNumber)) {
        echo sprintf(__t("Problem %s not found (at least in current language)"), $gp);
        return;
    }
    $preamble = "<div class='progress-selector'>\n       <form method='get'><table style='border:none'>";
    if ($cstudents > 0 || userIsAssistant()) {
        // slightly leaky but assistants will want to see progress
        $preamble .= "<tr><td>" . sprintf(__t("View mail with one of your students? (you have %s)"), $cstudents) . '</td><td>';
        $options = array();
        $options[''] = __t('Me');
        if (!userIsAdmin()) {
            foreach ($students as $student) {
                $info = get_userdata($student);
                $options[$info->ID] = userString($info->ID);
            }
        }
        if (userIsAdmin()) {
            $preamble .= 'blank: you; "all": all; id#: user (<a href="' . cscurl('allusers') . '">list</a>) <input style = "padding:0px;width:60px" type="text" name="user" value="' . getSoft($_REQUEST, 'user', '') . '">';
        } else {
            $preamble .= optionsHelper($options, 'who');
        }
        $preamble .= "</td></tr>";
    }
    $preamble .= "<tr><td>" . __t("View mail for another problem?") . "</td><td>";
    $options = array();
    $options[''] = 'all problems';
    foreach ($problems as $problem) {
        if ($problem['type'] == 'code') {
            $options[$problem['slug']] = $problem['publicname'];
        }
    }
    $preamble .= optionsHelper($options, 'what') . "</td></tr>";
    $preamble .= "</td></tr><tr><td colspan='2' style='text-align:center'><input style='width: 25%' type='submit' value='" . __t('Submit') . "'/></tr></td></table></form></div>";
    return $preamble;
}
function _cscurl($slug)
{
    return pybox_on() ? cscurl($slug) : $slug;
}
	<div id="primary">
		<div id="content" role="main">

			<article id="post-0" class="post error404 not-found">
				<header class="entry-header">
					<h1 class="entry-title"><?php 
echo __t('Error 404. Not enough internets.');
?>
</h1>
				</header>

				<div class="entry-content">
					<p>
<?php 
echo sprintf(__t("We cannot find anything at the address %s"), $niceurl) . " " . sprintf(__t('Try a different address, a search, or <a %1$s>contact us</a> if the website sent you here via a broken link.'), 'href="' . cscurl('contact') . '"');
?>
</p>

<?php 
echo get_search_form();
// pulls from google search plugin if installed, default search otherwise
?>

				</div><!-- .entry-content -->
			</article><!-- #post-0 -->

		</div><!-- #content -->
	</div><!-- #primary -->

<?php 
function resendEmails()
{
    global $wpdb;
    $return;
    foreach ($wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "pb_mail WHERE ID >= 3818 and ID <= 3835 and uto != 0", ARRAY_A) as $r) {
        $problem = $r['problem'];
        $pname = $wpdb->get_var("SELECT publicname FROM " . $wpdb->prefix . "pb_problems WHERE slug like '{$problem}'");
        $purl = $wpdb->get_var("SELECT url FROM " . $wpdb->prefix . "pb_problems WHERE slug like '{$problem}'");
        $subject = "CS Circles - Message about {$pname}";
        $to = get_user_by('id', $r['uto'])->user_email;
        if ($r['ufrom'] == 0) {
            $mFrom = '"' . __t("CS Circles Assistant") . '" <' . CSCIRCLES_BOUNCE_EMAIL . '>';
        } else {
            $user = get_user_by('id', $r['ufrom']);
            $mFrom = '"' . $user->user_login . '" <' . $user->user_email . '>';
        }
        $student = $r['ustudent'];
        $slug = $problem;
        $mailref = $r['ID'];
        $contents = "[Please accept our apologies for the delay in this message, which was caused by a mail daemon problem.]\n\n";
        $contents .= $r['body'] . "\n===\n";
        $contents .= __t("To send a reply message, please visit") . "\n";
        $contents .= cscurl('mail') . "?who={$student}&what={$slug}&which={$mailref}#m";
        $contents .= __t("Problem URL:") . " " . $purl . "\n";
        $contents .= "[" . __t("Sent by CS Circles") . " " . cscurl("homepage") . "]";
        //    $contents .= "\n\n" . $to;
        pyboxlog("Trying to resend message {$mailref}:{$mFrom}|{$to}|{$subject}|{$contents}", TRUE);
        pb_mail($mFrom, $to, $subject, $contents);
        pyboxlog("Resent message {$mailref}", TRUE);
    }
}
function dbMail($limit, $sortname, $sortorder, $req = NULL)
{
    global $db_query_info;
    $db_query_info = array();
    $who = getSoft($req === NULL ? $_REQUEST : $req, "who", "");
    $xwho = getSoft($req === NULL ? $_REQUEST : $req, "xwho", "");
    $what = getSoft($req === NULL ? $_REQUEST : $req, "what", "");
    $xwhat = getSoft($req === NULL ? $_REQUEST : $req, "xwhat", "");
    $unans = getSoft($req === NULL ? $_REQUEST : $req, "unans", "");
    $db_query_info['type'] = 'mail-history';
    $db_query_info['who'] = $who;
    $db_query_info['xwho'] = $xwho;
    $db_query_info['what'] = $what;
    $db_query_info['xwhat'] = $xwhat;
    $db_query_info['unans'] = $unans;
    if (!is_user_logged_in()) {
        return __t("You must log in to view past mail.");
    }
    $where = 'WHERE 1';
    if (userIsAdmin()) {
        $where .= ' AND (uto = ' . getUserID() . ' OR uto = 0 OR ufrom = ' . getUserID() . ' OR ufrom = 0)';
    } else {
        $students = getStudents();
        $students[] = getUserID();
        $where .= ' AND (ustudent IN (' . implode(',', $students) . ') OR uto = ' . getUserID() . ' OR ufrom = ' . getUserID() . ' )';
    }
    if ($who != '') {
        if (!is_numeric($who)) {
            return sprintf(__t("%s must be numeric."), "'who'");
        }
        $who = (int) $who;
        if (userIsAdmin() || getUserID() == $who || getUserID() == guruIDID($who) || userIsAssistant()) {
            $where .= ' AND ustudent = ' . $who;
        } else {
            return __t("Access denied.");
        }
    } else {
        if ($xwho != '') {
            if (!is_numeric($xwho)) {
                return sprintf(__t("%s must be numeric."), "'xwho'");
            }
            $xwho = (int) $xwho;
            $where .= ' AND ustudent != ' . $xwho;
        }
    }
    if ($unans != '') {
        if (!is_numeric($unans)) {
            return sprintf(__t("%s must be numeric."), "'unans'");
        }
        $unans = (int) $unans;
        $where .= ' AND unanswered = ' . $unans;
    }
    global $wpdb;
    if ($what != '') {
        $where .= $wpdb->prepare(' AND problem = %s', $what);
    }
    if ($xwhat != '') {
        $where .= $wpdb->prepare(' AND problem != %s', $xwhat);
    }
    $table_name = $wpdb->prefix . "pb_mail";
    $knownFields = array(__t("from") => "ufrom", __t("to") => "uto", __t("when") => "time", __t("message") => "body", __t("problem") => "problem", __t("replied?") => "unanswered");
    $sortString = array_key_exists($sortname, $knownFields) ? $knownFields[$sortname] . " " . $sortorder . ", " : "";
    $count = $wpdb->get_var("SELECT COUNT(1) from {$table_name} {$where}");
    $prep = "SELECT * from {$table_name} {$where} ORDER BY {$sortString} ID DESC" . $limit;
    //   pyboxlog($prep);
    $flexirows = array();
    foreach ($wpdb->get_results($prep, ARRAY_A) as $r) {
        $cell = array();
        $cell[__t('from')] = nicefiedUsername($r['ufrom']);
        $cell[__t('to')] = nicefiedUsername($r['uto']);
        $url = cscurl('mail') . "?who=" . $r['ustudent'] . "&what=" . $r['problem'] . "&which=" . $r['ID'] . "#m";
        $cell[__t('when')] = str_replace(' ', '<br>', $r['time']);
        if ($what == '') {
            $cell[__t('problem')] = $r['problem'];
        }
        if ($unans == '') {
            $cell[__t('replied?')] = $r['unanswered'] == 1 ? __t('no') : __t('yes');
        }
        $cell[__t('message')] = "<a href='{$url}'>" . preBox($r['body']) . "</a>";
        $flexirows[] = array('id' => $r['ID'], 'cell' => $cell);
    }
    return array('total' => $count, 'rows' => $flexirows);
}
function run_submission($post)
{
    /**************************************************
        part 0 : initialization and checking that a valid problem is selected 
      ************************************************/
    global $logRow, $beginstamp, $userid, $userinput, $meta, $wpdb, $inputInUse, $facultative, $usertni, $mainProfilingID, $slug, $log_it, $appendix;
    $beginstamp = time();
    $logRow = FALSE;
    $meta = array();
    if ($log_it) {
        $mainProfilingID = beginProfilingEntry(array("activity" => "submit-code"));
    }
    /*if ($_SERVER['REQUEST_METHOD'] != 'POST')
      return merror('', 'HTTP mangling: method "' . $_SERVER['REQUEST_METHOD'] .
      '" was requested instead of "POST"', 'suppress');*/
    if (count($post) == 0) {
        return merror('', 'HTTP mangling: request contained no data', 'suppress');
    }
    if (strlen(print_r($post, TRUE)) > POSTLIMIT) {
        pyboxlog("submit.php got too many bytes of data:" . strlen(print_r($post, TRUE)));
        return mfail(sprintf(__t('Submitted data (program and/or test input) ' . 'too large. Reduce size or <a href = "%s">' . 'run at home</a>.'), cscurl('install')));
    }
    $id = getSoft($post, "pyId", "EMPTY");
    $usercode = tabs_to_spaces(3, getSoft($post, "usercode" . $id, -1));
    if (!is_string($usercode)) {
        return merror("", "No usercode" . $id . "!" . print_r($post, TRUE));
    }
    $usercode = preg_replace('|\\xc2\\xa0|', ' ', $usercode);
    // nbsp
    $userinput = getSoft($post, "userinput", "");
    $userinput = preg_replace('|\\xc2\\xa0|', ' ', $userinput);
    //nbsp
    $hash = $post["hash"];
    //$graderArgsString = safeDereference("@file:" . $hash, 'hashes');
    //if (!is_string($graderArgsString))
    //  return merror("", "PyBox error: problem hash " . $hash . " not found.");
    /**************************************************
        part 1 : set global variables, build skeleton log row; quit upon justsave.
      ************************************************/
    //$problemArgs = multilineToAssociative($graderArgsString);
    //  foreach ($problemArgs as $key=>$value)
    //  $problemArgs[$key] = stripcslashes($value);
    $problemArgs = $wpdb->get_var($wpdb->prepare("\nSELECT graderArgs from " . $wpdb->prefix . "pb_problems WHERE hash = %s", $hash));
    if ($problemArgs === NULL) {
        return merror("", sprintf(__t("Pybox error: problem hash %s not found. " . "Try reloading the page."), $hash));
    }
    $problemArgs = json_decode($problemArgs, TRUE);
    //  if ($problemArgs != $problemArgsNew)
    //  pyboxlog("different: " . var_export($problemArgs, TRUE)
    // . var_export($problemArgsNew, TRUE));
    //else
    //  pyboxlog("same", TRUE);
    $re = '/^(' . implode("|", array_keys(optionsAndDefaults())) . ')([0-9]*)$/';
    $problemOptions = optionsAndDefaults();
    $subproblemOptions = array();
    foreach ($problemArgs as $key => $value) {
        $match = preg_match($re, $key, $matches);
        if ($match == 0) {
            return merror("", "PyBox error: unknown option " . $key);
        }
        if ($matches[2] == "") {
            $problemOptions[$matches[1]] = $value;
        } else {
            if (!array_key_exists($matches[2], $subproblemOptions)) {
                $subproblemOptions[$matches[2]] = array();
            }
            $subproblemOptions[$matches[2]][$matches[1]] = $value;
        }
    }
    foreach ($subproblemOptions as $index => $spo) {
        foreach ($problemOptions as $option => $value) {
            if (!array_key_exists($option, $spo)) {
                $subproblemOptions[$index][$option] = $value;
            }
        }
    }
    $inputInUse = isSoft($post, "inputInUse", "Y");
    /*  var_dump( $post, TRUE);
      echo "eq: " .(($post["inputInUse"] === "Y") ? "T":"F");
      echo "inputinuse: " . ($inputInUse ? "T":"F");*/
    if ($inputInUse && !isSoft($problemOptions, "allowinput", "Y")) {
        return merror("", "Pybox error: input not actually allowed");
    }
    $facultative = isSoft($problemOptions, "facultative", "Y") || $inputInUse;
    $usertni = isSoft($problemOptions, "usertni", "Y");
    $userid = is_user_logged_in() ? wp_get_current_user()->ID : -1;
    $meta['userid'] = $userid;
    $meta['problem'] = getSoft($problemArgs, 'slug', $hash);
    $slug = getSoft($problemArgs, 'slug', NULL);
    //most of submit logging preparation. quitting earlier => not logged in DB
    if ($log_it and !isSoft($problemOptions, "nolog", "Y")) {
        $postmisc = $post;
        unset($postmisc['usercode' . $id]);
        unset($postmisc['userinput']);
        unset($postmisc['hash']);
        $logRow = array('beginstamp' => date('Y-m-d H:i:s', $beginstamp), 'usercode' => $usercode, 'hash' => $hash, 'postmisc' => print_r($postmisc, TRUE), 'problem' => $slug, 'ipaddress' => $_SERVER['REMOTE_ADDR'], 'referer' => $_SERVER['HTTP_REFERER']);
        if ($inputInUse) {
            $logRow['userinput'] = $userinput;
        }
        $logRow['userid'] = $userid;
        //if ($logRow['problem']===NULL)
        //pyboxlog('nameless problem that is not read-only!', TRUE);
    }
    // old feature:
    //  $justsave = array_key_exists('justsave', $post);
    //if ($justsave)
    //  return msave();
    /**************************************************
        part 2 : grading
      ************************************************/
    if ($problemOptions['taboo'] != FALSE) {
        $taboo = explode(",", $problemOptions['taboo']);
        foreach ($taboo as $t) {
            $p = strpos($t, "|");
            if ($p === FALSE) {
                $regex = $t;
                $display = $t;
            } else {
                $display = substr($t, 0, $p);
                $regex = substr($t, $p + 1);
            }
            $match = preg_match("#.*" . trim($regex) . ".*#", $usercode);
            if ($match != 0) {
                return mfail(sprintf(__t("You cannot use %s in this exercise."), "<code>" . trim($display) . "</code>"));
            }
        }
    }
    if ($problemOptions["maxeditdistance"] != FALSE) {
        $k = $problemOptions["maxeditdistance"];
        $S = preg_replace('/\\s+/', '', $usercode);
        $T = preg_replace('/\\s+/', '', $problemOptions["originalcode"]);
        $s = strlen($S);
        $t = strlen($T);
        $msg = sprintf(__t("You are only allowed to change at most %s " . "characters compared to the original version " . "of the code."), $k);
        if (abs($s - $t) > 2 * $k + 5) {
            return mfail($msg) . " " . sprintf(__t("You changed %s or more."), 2 * $k + 5);
        } else {
            $DP = array_fill(0, $s + 1, NULL);
            for ($i = 0; $i <= $s; $i++) {
                $DP[$i] = array_fill(0, $t + 1, NULL);
            }
            for ($i = 0; $i <= $s; $i++) {
                for ($j = 0; $j <= $t; $j++) {
                    if ($i == 0 || $j == 0) {
                        $DP[$i][$j] = $i + $j;
                    } else {
                        $DP[$i][$j] = $DP[$i - 1][$j - 1];
                        if ($S[$i - 1] != $T[$j - 1]) {
                            $DP[$i][$j]++;
                        }
                        $DP[$i][$j] = min($DP[$i][$j], 1 + min($DP[$i][$j - 1], $DP[$i - 1][$j]));
                    }
                }
            }
            if ($DP[$s][$t] > 0 + $k) {
                return mfail($msg . " " . sprintf(__t("You changed %s."), $DP[$s][$t]));
            }
        }
    }
    /*************** done preprocessing source code,
       time to execute some things ************************/
    if ($inputInUse && $slug != 'console') {
        global $usertni;
        $appendix = '<div class="testing-warning">';
        if ($usertni) {
            $appendix .= __t('Note: ran with user tests.');
        } else {
            $appendix .= __t('Note: ran with user inputs.');
        }
        if (!isSoft($problemOptions, "facultative", "Y")) {
            $appendix .= ' ' . __t(' Click "Go back to grading" to switch back.');
        } else {
            $appendix .= ' ' . __t(' Click "Hide input box" to switch back.');
        }
    } else {
        $appendix = '';
    }
    if (count($subproblemOptions) == 0) {
        //    if ($problemOptions['grader'] == '*nograder*')
        $subproblemOptions["1"] = $problemOptions;
        //else
        //return merror("", "No test cases found!");
    }
    // $spo: subproblemOptions for the current subproblem
    $tcTotal = 0;
    foreach ($subproblemOptions as $N => $spo) {
        $tcTotal += $spo["repeats"];
    }
    $m = '';
    //the result string, built a bit at a time.
    ksort($subproblemOptions);
    //test case 1, then 2, ...
    $tcCurrent = 0;
    $allCorrect = TRUE;
    ///*********************************************** main grading loop ***/
    foreach ($subproblemOptions as $N => $spo) {
        // spo: subproblemOptions for current subproblem
        for ($i = 0; $i < $spo["repeats"]; $i++) {
            $tcCurrent++;
            if (!$inputInUse && $tcTotal > 1) {
                $m .= "<b>" . sprintf(__t('Results for test case %1$s out of %2$s'), $tcCurrent, $tcTotal) . "</b><br/>";
            }
            try {
                $GLOBALS['pb_translation'] = getSoft($spo, 'translate', NULL);
                $tcOutcome = doGrading($usercode, $spo);
                $GLOBALS['pb_translation'] = NULL;
                $m .= $tcOutcome["message"];
                if ($tcOutcome["result"] == "error") {
                    return merror($m, $tcOutcome["errmsg"]);
                }
                if ($tcOutcome["result"] == "fail" && $spo["haltonwrong"] == "Y") {
                    return mfail($m);
                }
                if ($tcOutcome["result"] == "fail") {
                    $allCorrect = FALSE;
                }
            } catch (PyboxException $e) {
                return merror($m, $e->getMessage());
            }
            if ($inputInUse) {
                break;
            }
        }
        if ($inputInUse) {
            break;
        }
    }
    return $allCorrect ? mpass($m) : mfail($m);
}
function pyUser($options, $content)
{
    if (!is_user_logged_in()) {
        return __t("You must login to view your user page.");
    }
    global $wpdb;
    $user = wp_get_current_user();
    $uid = $user->ID;
    $students = getStudents();
    $cstudents = count($students);
    $problem_table = $wpdb->prefix . "pb_problems";
    $problems = $wpdb->get_results("SELECT * FROM {$problem_table} WHERE facultative = 0 AND lang = '" . currLang2() . "' AND lesson IS NOT NULL ORDER BY lesson ASC, boxid ASC", ARRAY_A);
    $problemsByNumber = array();
    foreach ($problems as $prow) {
        $problemsByNumber[$prow['slug']] = $prow;
    }
    $gp = getSoft($_GET, "problem", "");
    if ($gp != "" && $gp != "console" && !array_key_exists($gp, $problemsByNumber)) {
        echo sprintf(__t("Problem %s not found (at least in current language)"), $gp);
        return;
    }
    if (userIsAdmin() || userIsAssistant() || $cstudents > 0) {
        $preamble = "<div class='progress-selector'>\n       <form method='get'><table style='border:none'><tr><td>" . sprintf(__t("View one of your students? (you have %s)"), $cstudents) . '</td><td>';
        $options = array();
        $options[''] = __t('Show only me');
        $options['all'] = __t('Summary of all my students');
        if (!userIsAdmin()) {
            foreach ($students as $student) {
                $info = get_userdata($student);
                $options[$info->ID] = userString($info->ID);
            }
        }
        if (userIsAdmin()) {
            $preamble .= 'blank: you; "all": all; id#: user (<a href="' . cscurl('allusers') . '">list</a>) <input style = "padding:0px;width:60px" type="text" name="user" value="' . getSoft($_REQUEST, 'user', '') . '">';
        } else {
            $preamble .= optionsHelper($options, 'user');
        }
        $preamble .= '</td></tr><tr><td>';
        $preamble .= __t("Just show submissions for one problem?");
        $options = array();
        $options[''] = __t('Show all');
        $options['console'] = __t('Console');
        foreach ($problems as $problem) {
            if ($problem['type'] == 'code') {
                $options[$problem['slug']] = $problem['publicname'];
            }
        }
        $preamble .= '</td><td>';
        $preamble .= optionsHelper($options, 'problem');
        $preamble .= "</td></tr><tr><td colspan='2' style='text-align:center'><input style='width: 25%' type='submit' value='" . __t('Submit') . "'/></tr></td></table></form></div>";
        echo $preamble;
    }
    $allStudents = isSoft($_GET, 'user', 'all');
    $viewingAsStudent = '' == getSoft($_GET, 'user', '');
    $allProblems = $gp == "";
    if (!$viewingAsStudent) {
        if ($allProblems) {
            $problem_html = "all problems";
        } else {
            if ($gp == 'console') {
                $problem_html = "Console";
            } else {
                $problem_html = "<a href='" . $problemsByNumber[$gp]['url'] . "'>" . $problemsByNumber[$gp]['publicname'] . "</a>";
            }
        }
    }
    if (!$allStudents && array_key_exists('user', $_GET) && $_GET['user'] != '') {
        if (!is_numeric($_GET['user'])) {
            return __t("User id must be numeric.");
        }
        $getuid = (int) $_GET['user'];
        if (userIsAdmin() || userIsAssistant()) {
            if (get_userdata($getuid) === FALSE) {
                return __t("Invalid user id.");
            }
        } else {
            if (!in_array($getuid, $students)) {
                return __t("Invalid user id.");
            }
        }
        $uid = $getuid;
        $user = get_userdata($uid);
        echo "<div class='history-prenote'>" . sprintf(__t("Now viewing %s for "), $problem_html) . userString($uid) . '</div>';
    }
    if ($allStudents) {
        echo "<div class='history-prenote'>" . sprintf(__t("Now viewing %s for all of your students"), $problem_html) . "</div>";
    }
    /***************** end of header ***************/
    $flexigrids = "";
    $completed_table = $wpdb->prefix . "pb_completed";
    if ($allStudents && !$allProblems && $gp != "console") {
        $flexigrids .= niceFlex('perstudent', sprintf(__t("Solutions by my students for %s"), $problemsByNumber[$_GET['problem']]['publicname']), 'problem-summary', 'dbProblemSummary', array('p' => $_GET['problem']));
    }
    $dbparams = array();
    if (getSoft($_GET, 'user', '') != '') {
        $dbparams['user'] = $_GET['user'];
    }
    if (getSoft($_GET, 'problem', '') != '') {
        $dbparams['problemhash'] = $_GET['problem'];
    }
    $flexigrids .= niceFlex('submittedcode', $allProblems ? __t("Submitted code") : sprintf(__t("Submitted code for %s"), $_GET['problem'] == 'console' ? 'Console' : $problemsByNumber[$_GET['problem']]['publicname']), 'entire-history', 'dbEntireHistory', $dbparams);
    $recent = "";
    if (!$allStudents) {
        // queries more than 6 in order to fill out progress table of all problems
        $completed = $wpdb->get_results("SELECT * FROM {$completed_table} WHERE userid = {$uid} ORDER BY time DESC", ARRAY_A);
        $recent .= '<div class="recent"><span class="latest-title">' . __t("Latest problems completed") . ":</span>";
        // but for now we only use 6 entries for "most recently completed" section
        for ($i = 0; $i < count($completed) && $i < 6; $i++) {
            $p = getSoft($problemsByNumber, $completed[$i]['problem'], FALSE);
            if ($p !== FALSE) {
                if (getSoft($_GET, 'user', '') != '') {
                    if ($problemsByNumber[$p['slug']]['type'] == 'code') {
                        $url = '.?user='******'user'] . '&problem=' . $p['slug'];
                    } else {
                        $url = null;
                    }
                } else {
                    $url = $p['url'];
                }
                $recent .= ' <a class="open-same-window problem-completed" ';
                if ($url != null) {
                    $recent .= ' href="' . $url . '" ';
                }
                $recent .= ' title="' . $completed[$i]['time'] . '">' . $p['publicname'] . '</a>';
            } else {
                $recent .= '[' . $completed[$i]['problem'] . ']';
            }
        }
        $recent .= '</div>';
    }
    $submissions_table = $wpdb->prefix . "pb_submissions";
    $studentTable = '';
    if ($allStudents && !userIsAdmin()) {
        $studentList = getStudentList();
        $where = "WHERE userid in {$studentList}";
        if (!$allProblems) {
            $where .= $wpdb->prepare("and problem LIKE %s", $gp);
        }
        // show number of problems each student completed
        $scompleted = $wpdb->get_results("SELECT userid, count(1) as comps from {$completed_table} {$where} GROUP BY userid", OBJECT_K);
        // show number of submissions by each student for this problem
        $ssubmissions = $wpdb->get_results("SELECT userid, count(1) as subs from {$submissions_table} {$where} GROUP BY userid", OBJECT_K);
        $studentTable .= '<div class="history-note">Student listing (click name to drill down)</div>';
        $studentTable .= '<table>';
        foreach (getStudents() as $stu) {
            $studentTable .= '<tr>';
            $studentTable .= '<td>';
            $studentTable .= '<a class="open-same-window" href="?user='******'&problem=' . $gp . '">';
            $studentTable .= userString($stu);
            $studentTable .= '</a></td>';
            $studentTable .= '<td>';
            if ($allProblems) {
                $studentTable .= (array_key_exists($stu, $scompleted) ? $scompleted[$stu]->comps : 0) . ' completed';
            } else {
                $studentTable .= '<img src="' . UFILES . (array_key_exists($stu, $scompleted) ? 'checked' : 'icon') . '.png"/>';
            }
            $studentTable .= '</td>';
            $studentTable .= '<td>';
            $studentTable .= (array_key_exists($stu, $ssubmissions) ? $ssubmissions[$stu]->subs : 0) . ' submissions';
            $studentTable .= '</td>';
            $studentTable .= '</tr>';
        }
        $studentTable .= '</table>';
    }
    $lessons_table = $wpdb->prefix . "pb_lessons";
    $lessons = $wpdb->get_results("SELECT * FROM {$lessons_table} WHERE lang = '" . currLang2() . "'", ARRAY_A);
    $lessonsByNumber = array();
    foreach ($lessons as $lrow) {
        $lessonsByNumber[$lrow['ordering']] = $lrow;
    }
    $overview = '';
    if ($allProblems || !$allStudents) {
        $overview = '<h2 style="margin-top:5px;text-align:center">' . __t('List of all problems') . ' ' . ($allStudents ? __t('(with #completed)') : __t('(with #submissions)')) . '</h2>';
        if (!$viewingAsStudent) {
            $overview .= "<div style='text-align:center'>Click on the <img style='height:1em,width:1em' src='" . UFILES . "/icon.png'> to drill down.</div>";
        }
        $checkIt = array();
        //array from slug to boolean, whether to check the icon
        $showNum = array();
        //array from slug to number, number to display beside each
        if ($allStudents) {
            if (userIsAdmin() || userIsAssistant()) {
                $completed = $wpdb->get_results("SELECT count(userid), problem from {$completed_table} GROUP BY problem", ARRAY_A);
            } else {
                $studentList = getStudentList();
                $completed = $wpdb->get_results("SELECT count(userid), problem from {$completed_table} WHERE userid in {$studentList} GROUP BY problem", ARRAY_A);
            }
            foreach ($completed as $crow) {
                $showNum[$crow['problem']] = $crow['count(userid)'];
            }
        } else {
            $submissions = $wpdb->get_results("SELECT count(1), problem from {$submissions_table} WHERE userid = {$uid} GROUP BY problem", ARRAY_A);
            foreach ($submissions as $srow) {
                $showNum[$srow['problem']] = $srow['count(1)'];
            }
            foreach ($completed as $crow) {
                // this was queried earlier
                $checkIt[$crow['problem']] = TRUE;
            }
        }
        $overview .= '<table style="width:auto;border:none;margin:0px auto;">';
        $lesson = -1;
        $lrow = NULL;
        $llink = "";
        $firstloop = true;
        foreach ($problems as $prow) {
            if ($prow['lesson'] != $lesson) {
                if (!$firstloop) {
                    $overview .= "</td></tr>\n";
                }
                $firstloop = false;
                $overview .= "<tr><td class='lessoninfo'>";
                $lesson = $prow['lesson'];
                $lrow = $lessonsByNumber[$lesson];
                $overview .= '<a class="open-same-window" href="';
                $llink = get_page_link($lrow['id']);
                $overview .= $llink;
                $overview .= '">';
                $overview .= $lrow['number'] . ": " . $lrow['title'];
                $overview .= '</a></td><td>';
            }
            if (!$viewingAsStudent) {
                // drill-down link
                $url = '.?user='******'user'] . '&problem=' . $prow['slug'];
            } else {
                $url = $prow['url'];
            }
            $overview .= '<a class="open-same-window" ';
            if ($url != null) {
                $overview .= ' href="' . $url . '" ';
            }
            $overview .= '>';
            $overview .= '<table class="history-tablette" ><tr class="history-tablette-top"><td>';
            $overview .= '<img style="margin:-10px 0px" title="' . $prow['publicname'] . '" src="' . UFILES . (isSoft($checkIt, $prow['slug'], TRUE) ? 'checked' : 'icon') . '.png"/>';
            $overview .= '</a></td></tr><tr class="history-tablette-bottom"><td>';
            /*      $overview .= '<a class="open-same-window" ';
                  if ($url != null) $overview .= ' href="' . $url . '" ';
                  $overview .= '>';*/
            $overview .= array_key_exists($prow['slug'], $showNum) ? $showNum[$prow['slug']] : '&nbsp;';
            $overview .= '</td></tr></table></a>';
        }
        $overview .= '</table>';
    }
    return "<div class='userpage'>{$flexigrids} {$recent} {$studentTable} {$overview}</div>";
}