function display_problem()
{
    global $admin, $currentmessage, $defaultlang, $maxcodesize, $execoptions;
    if ($admin["mode"] == "Lockdown" && $_SESSION["tid"] == 0) {
        $_SESSION["message"] = $currentmessage;
        $_SESSION["message"][] = "Access Denied : The contest is currently in Lockdown Mode. Please try again later.";
        echo "<script>window.location='?display=faq';</script>";
        return;
    }
    if (isset($_GET["pid"]) && !empty($_GET["pid"])) {
        $pid = $_GET["pid"];
    } else {
        $pid = 0;
    }
    if ($_SESSION["status"] == "Admin") {
        $data = mysql_query("SELECT * FROM problems WHERE pid={$pid} ");
    } else {
        $data = mysql_query("SELECT * FROM problems WHERE status='Active' and pid={$pid}");
    }
    if ($pid != 0) {
        if (!is_resource($data) || mysql_num_rows($data) != 1) {
            $_SESSION["message"] = $currentmessage;
            $_SESSION["message"][] = "Problem Access Error : The problem you requested does not exist or is currently inactive.";
            $pid = 0;
        }
    }
    if ($pid == 0) {
        echo "<center>";
        //echo "<h2>Problems Index</h2>";
        if (($g = mysql_getdata("SELECT distinct pgroup FROM problems WHERE status='Active' ORDER BY pgroup")) != NULL) {
            $t = array();
            foreach ($g as $gn) {
                $t[] = $gn["pgroup"];
            }
            $g = $t;
            unset($t);
            if (in_array("", $g)) {
                unset($g[array_search("", $g)]);
                $g[] = "";
            }
            // make groups array.
            echo "<div class='filter'><b>Select Group<b> : <select style='width:150px;' id='category-select' onChange=\"\$('input#query').attr('value',''); problem_search(); if(this.value==0){ \$('span.group').slideDown(250); } else { for(i=1;i<=" . count($g) . ";i++){ if(this.value=='group'+i) \$('span#group'+i).slideDown(250); else \$('span#group'+i).slideUp(250); } }\"><option value=0>All Groups</option>";
            foreach ($g as $i => $gn) {
                echo "<option value='group" . ($i + 1) . "'>" . eregi_replace("^#[0-9]+ ", "", $gn == "" ? "Unclassified" : $gn) . "</option>";
            }
            echo "</select> <input placeholder='Enter Search Term Here' id='query' onKeyUp=\"\$('#category-select').val(0); \$('span.group').slideDown(250); problem_search();\" style='text-align:center;'> <input type='button' value='Clear' onClick=\"\$('input#query').attr('value',''); problem_search();\"></div>";
            if (($nac = mysql_getdata("SELECT distinct pid FROM runs WHERE tid={$_SESSION['tid']} AND result!='AC' AND access!='deleted'")) == NULL) {
                $nac = array();
            } else {
                $t = array();
                foreach ($nac as $sp) {
                    $t[] = $sp["pid"];
                }
                $nac = $t;
                unset($t);
            }
            if (($ac = mysql_getdata("SELECT distinct pid FROM runs WHERE tid={$_SESSION['tid']} AND result='AC' AND access!='deleted'")) == NULL) {
                $ac = array();
            } else {
                $t = array();
                foreach ($ac as $sp) {
                    $t[] = $sp["pid"];
                }
                $ac = $t;
                unset($t);
            }
            echo "<div id='probindex' class='probindex'>";
            echo "<div class='probheaders2' style='display:none;'><h2>Search Results</h2>";
            echo "<table><th>Problem ID</th><th>Problem Name</th><th>Problem Code</th><th>Problem Type</th><th>Score</th><th>Statistics</th></tr></table></div>";
            foreach ($g as $i => $gn) {
                echo "<span id='group" . ($i + 1) . "' class='group'><div class='probheaders1'><h2><a href='?display=submissions&pgr=" . urlencode($gn) . "'>Problem Group : " . eregi_replace("^#[0-9]+ ", "", $gn == "" ? "Unclassified" : $gn) . "</a></h2>";
                echo "<table><th>Problem ID</th><th>Problem Name</th><th>Problem Code</th><th>Problem Type</th><th>Score</th><th>Statistics</th></tr></table></div>";
                $data = mysql_query("SELECT * FROM problems WHERE status='Active' and pgroup='" . $gn . "' ORDER BY pid");
                while ($problem = mysql_fetch_array($data)) {
                    $t = mysql_query("SELECT (SELECT count(*) FROM runs WHERE pid={$problem['pid']} AND result='AC' AND access!='deleted') as ac, (SELECT count(*) FROM runs WHERE pid={$problem['pid']} AND access!='deleted') as tot");
                    if (is_resource($t) && mysql_num_rows($t) && ($t = mysql_fetch_array($t))) {
                        $statistics = "<a title='Accepted Solutions / Total Submissions' href='?display=submissions&pid={$problem['pid']}'>" . $t["ac"] . " / " . $t["tot"] . "</a>";
                    } else {
                        $statistics = "NA";
                    }
                    if ($_SESSION["tid"] < 1) {
                        $highlight = "NA";
                    } elseif (in_array($problem["pid"], $ac)) {
                        $highlight = "AC";
                    } elseif (in_array($problem["pid"], $nac)) {
                        $highlight = "NAC";
                    } else {
                        $highlight = "NA";
                    }
                    echo "<div class='problem'><table class='submission'><tr class='{$highlight}'><td><a href='?display=problem&pid={$problem['pid']}'>{$problem['pid']}</a></td><td><a href='?display=problem&pid={$problem['pid']}'>" . stripslashes($problem["name"]) . "</a></td><td><a href='?display=problem&pid={$problem['pid']}'>" . stripslashes($problem["code"]) . "</a></td>";
                    if ($admin["mode"] != "Active" || $_SESSION["status"] == "Admin") {
                        echo "<td><a href='#' onClick=\"\$('input#query').attr('value','" . $problem["type"] . "'); problem_search();\">" . stripslashes($problem["type"]) . "</td>";
                    } else {
                        echo "<td>NA</td>";
                    }
                    echo "<td><a href='?display=problem&pid={$problem['pid']}'>{$problem['score']}</a></td><td>{$statistics}</td></tr></table></div>";
                }
                echo "</span>";
            }
        }
        echo "</div>";
        return;
    }
    $data = mysql_fetch_array($data);
    $statement = stripslashes($data["statement"]);
    $statement = eregi_replace("\n", "<br>", $statement);
    if ($_SESSION["status"] == "Admin") {
        $statement2 = stripslashes($data["statement"]);
    }
    /* */
    $statement = eregi_replace("<image ?/?>", "<img src='data:image/jpeg;base64,{$data['image']}' />", $statement);
    $t = mysql_query("SELECT (SELECT count(*) FROM runs WHERE pid={$pid} AND result='AC' AND access!='deleted') as ac, (SELECT count(*) FROM runs WHERE pid={$pid} AND access!='deleted') as tot");
    if (is_resource($t) && mysql_num_rows($t) && ($t = mysql_fetch_array($t))) {
        $statistics = "<a title='Accepted Solutions / Total Submissions' href='?display=submissions&pid={$pid}'>" . $t["ac"] . "/" . $t["tot"] . "</a>";
    } else {
        $statistics = "NA";
    }
    $pgroup = eregi_replace("^#[0-9]+ ", "", $data["pgroup"]);
    echo "<center><h2>Problem : {$data['name']} (" . $pgroup . " Group)</h2><table width=100%>\r\n\t\t<tr><th>Problem ID</th><th>{$pid}</th><th>Input File Size</th><th>" . display_filesize(strlen($data["input"])) . "</th><th><a href='?display=submissions&pid={$pid}'>Submissions</a></th><th>{$statistics}</th></tr>\r\n\t\t<tr><th>Problem Code</th><th>{$data['code']}</th><th>Time Limit</th><th>{$data['timelimit']} sec</th><th>Points</th><th>{$data['score']}</th></tr>";
    if ($_SESSION["status"] == "Admin") {
        echo "<tr><th>Special Options</th><th colspan=3>" . $execoptions[$data["options"]] . "</th><th colspan=2><input type='button' value='" . ((isset($_GET["edit"]) and $_GET["edit"] == "0") ? "Reset" : "Edit") . " HTML Source' onClick=\"window.location=window.location.search.replace('&edit=0','')+'&edit=0';\"></th></tr>";
    }
    echo "<tr><td colspan=20 style='text-align:left;padding:20;'>";
    if ($_SESSION["status"] == "Admin" and isset($_GET["edit"]) and $_GET["edit"] == "0") {
        echo "<form method='post' action='?action=updateproblemhtml&pid={$pid}'><textarea name='statement' id='statement' class='code'>" . $statement2 . "</textarea><br><br><center><input type='submit' value='Update Problem Statement'> <input type='button' value='Cancel' onClick=\"window.location=window.location.search.replace('&edit=0','');\"></center></form>";
    } else {
        echo $statement;
    }
    echo "</td></tr><tr><td colspan=20 style='text-align:left;padding:20;'><b>Language(s) Allowed</b> : ";
    echo eregi_replace("Brain", "Brainf**k", eregi_replace(",", ", ", $data["languages"]));
    echo "</td></tr>";
    $languages = "";
    if (isset($data["languages"])) {
        foreach (explode(",", $data["languages"]) as $l) {
            if ($l == "Brain") {
                if ($l == $defaultlang) {
                    $languages .= "<option value='Brain' selected='selected'>Brainf**k</option>";
                } else {
                    $languages .= "<option value='Brain'>Brainf**k</option>";
                }
            } else {
                if ($l == $defaultlang) {
                    $languages .= "<option selected='selected'>" . $defaultlang . "</option>";
                } else {
                    $languages .= "<option>{$l}</option>";
                }
            }
        }
    }
    $data = mysql_query("SELECT * FROM clar WHERE access='Public' and clar.pid={$pid} ORDER BY time ASC");
    if (is_resource($data) && mysql_num_rows($data) > 0) {
        if (mysql_num_rows($data)) {
            echo "<tr><th colspan=20><a href='?display=clarifications'>Clarifications</a></th></tr><tr><td colspan=20 style='text-align:left;padding:20;'>";
            while ($temp = mysql_fetch_array($data)) {
                $teamname = mysql_query("SELECT teamname FROM teams WHERE tid=" . $temp["tid"]);
                if (is_resource($teamname) && mysql_num_rows($teamname) == 1) {
                    $teamname = mysql_fetch_array($teamname);
                    $teamname = $teamname["teamname"];
                } else {
                    $teamname = "Anonymous";
                }
                echo "<p><b><a href='?display=submissions&tid=" . $temp["tid"] . "'>" . filter($teamname) . "</a></b> : {$temp['query']}";
                if (!empty($temp["reply"])) {
                    echo "<br><i><b>Response</b> : {$temp['reply']}</i>";
                }
                echo "</p>";
            }
            echo "</td></tr>";
        }
    }
    echo "</table><br></center>";
    if ($_SESSION["tid"] == 0) {
        echo "<center>Please login to submit solutions.</center>";
    } else {
        if ($admin["mode"] != "Active" && $admin["mode"] != "Passive" && $_SESSION["status"] != "Admin") {
            echo "<center>You can not submit solutions at the moment as the contest is not running. Please try again later.</center>";
        } else {
            if ($admin["mode"] == "Passive" && $_SESSION["status"] != "Admin" && eregi("^CQM\\-[0-9]+\$", $pgroup)) {
                echo "<center>You can no longer submit solutions to this problem.</center>";
            } else {
                $placeholder = "Paste your code here, or select a file to upload.";
                $editcode = "";
                if (isset($_GET["edit"])) {
                    $rid = $_GET["edit"];
                    if (!is_numeric($rid)) {
                        $rid = 0;
                    }
                    $t = mysql_query("SELECT tid,language,code,access FROM runs WHERE rid={$rid} AND access!='deleted'");
                    if (is_resource($t) && mysql_num_rows($t) == 1) {
                        $run = mysql_fetch_array($t);
                        if ($_SESSION["tid"] == $run["tid"] || $run["access"] == "public" || $_SESSION["status"] == "Admin") {
                            $editcode = eregi_replace("<", "&lt;", $run["code"]);
                        }
                        if ($run["language"] == "Brain") {
                            $run["language"] = "Brainf**k";
                        }
                        $languages = str_replace(">{$run['language']}</option>", " selected='selected'>{$run['language']}</option>", str_replace(" selected='selected'", "", $languages));
                    }
                }
                global $extension, $codemirror;
                $extcompare = "";
                foreach ($extension as $lang => $ext) {
                    $extcompare .= "if(ext=='{$ext}'){ \$('select#code_lang').attr('value','" . $lang . "'); } ";
                }
                echo "<center><h2>Submit Solution : {$data['name']}</h2>\r\n\t\t\t<script>function code_validate(){ if(document.forms['submitcode'].code_file.value=='' && document.forms['submitcode'].code_text.value==''){ alert('Code file not specified and textarea empty. Cannot submit nothing.'); return false; } if(document.forms['submitcode'].code_lang.value=='Java' && document.forms['submitcode'].code_file.value=='' && document.forms['submitcode'].code_text.value!=''){ x = prompt('You are copy-pasting Java code here. Please enter the class name you have used so\\nthat the server can create a source file of the same name while evaluating your code :\\n '); if(!x) return false; else \$('input#code_name').val(x); } document.forms['submitcode'].code_text.value=addslashes(document.forms['submitcode'].code_text.value); return true; }</script>\r\n\t\t\t<form action='?action=submitcode' method='post' name='submitcode' enctype='multipart/form-data' onSubmit=\"return code_validate();\"><input type='hidden' name='code_pid' value='{$pid}'>\r\n\t\t\t<table width=100%><tr><th>Language</th><th><select id='code_lang' name='code_lang'>" . $languages . "</select></th><input type='hidden' name='MAX_FILE_SIZE' value='{$maxcodesize}' />";
                echo "<th>Code File</th><th><input type='file' name='code_file' style='width:200px;' onChange=\"if(this.value!=''){ filename = this.value.split('.'); ext = filename[filename.length-1]; {$extcompare} }\" /></th></tr>\r\n\t\t\t<tr><td colspan=20 style='text-align:left;'><textarea id='code_text' name='code_text' class='code' placeholder=\"{$placeholder}\" onChange=\"if(this.value!='') \$('select#code_mode').attr('value','Text');\">{$editcode}</textarea></td></tr></table>\r\n\t\t\t<table width=100%> <input type='hidden' name='code_name' id='code_name' value='code'>\r\n\t\t\t<tr><th><div class='small'>If you submit both File and Text (copy-pasted in the above textarea), the Text will be ignored.</div></th><th><input type='submit' value='Submit Code'></th></tr>\r\n\t\t\t</table></form></center>";
            }
        }
    }
}
function action_ajaxrefresh($type)
{
    global $admin, $fullresult, $ajaxlogout;
    if ($admin["mode"] == "Active" && isset($admin["endtime"])) {
        $json["ajax-contest-time"] = $admin["endtime"] - time();
    } else {
        $json["ajax-contest-time"] = -1;
    }
    $json["ajax-contest-status"] = $admin["mode"];
    if ($admin["lastjudge"] >= time() - 30) {
        $json["ajax-contest-judgement"] = "<a title='The Execution Protocol is active. Submissions will be judged as soon as they are the next in queue.'>Ongoing</a>";
    } else {
        $json["ajax-contest-judgement"] = "<a title='The Execution Protocol is currently not active. Submissions will be judged once it is initiated.'>Waiting</a>";
    }
    if ($_SESSION["tid"] == 0) {
        $ip = $_SERVER["REMOTE_ADDR"];
        $t = mysql_query("SELECT tid FROM teams WHERE (ip1='{$ip}' or ip2='{$ip}' or ip3='{$ip}')");
        $json["ajax-mysubmit"] = "<a href='?display=register'>New Team? Click here to Register.</a>";
    } else {
        if ($admin["mode"] == "Lockdown" && $_SESSION["status"] != "Admin") {
            $json["ajax-mysubmit"] = "<h3>My Submissions</h3><table><tr><td>Not Available</td></tr></table>";
        } else {
            $json["ajax-mysubmit"] = "<h3><a href='?display=submissions&tid={$_SESSION['tid']}'>My Submissions</a></h3>";
            $json["ajax-mysubmit"] .= "<table><th title='Run ID'>RID</th><th>Problem</th><th>Language</th><th>Result</th></tr>";
            if (isset($admin["mysublist"]) && $admin["mysublist"] >= 0) {
                $limit = $admin["mysublist"];
            } else {
                $limit = 5;
            }
            $data = mysql_query("SELECT * FROM problems,runs WHERE runs.tid='{$_SESSION['tid']}' AND problems.pid=runs.pid AND runs.access!='deleted' AND problems.status='Active' ORDER BY rid DESC LIMIT 0," . $limit);
            if (is_resource($data)) {
                while ($temp = mysql_fetch_array($data)) {
                    if ($_SESSION["status"] == "Admin") {
                        $t = mysql_query("SELECT name,code FROM problems WHERE pid={$temp['pid']}");
                    } else {
                        $t = mysql_query("SELECT name,code FROM problems WHERE pid={$temp['pid']} and status='Active'");
                    }
                    if (is_resource($t) && mysql_num_rows($t) == 1) {
                        $t = mysql_fetch_array($t);
                        $probname = $t['name'];
                        $probcode = $t['code'];
                    } else {
                        continue;
                    }
                    $result = $temp["result"];
                    if (isset($fullresult[$result])) {
                        $result = $fullresult[$result];
                    }
                    if ($temp["language"] == "Brain") {
                        $temp["language"] = "Brainf**k";
                    }
                    $json["ajax-mysubmit"] .= "<tr class='{$temp['result']}'><td><a href='?display=code&rid={$temp['rid']}' title='Link to Code'>{$temp['rid']}</a></td><td title=\"Link to Problem : {$probname}\"><a href='?display=problem&pid={$temp['pid']}'>{$probcode}</td><td>{$temp['language']}</td><td title='{$result}'>{$temp['result']}</td></tr>";
                }
            }
            $json["ajax-mysubmit"] .= "</table>";
        }
    }
    if ($admin["mode"] == "Lockdown" && $_SESSION["status"] != "Admin" || !isset($admin["cache-rankings"])) {
        $json["ajax-rankings"] = "<h3>Current Rankings</h3><table><tr><td>Not Available</td></tr></table>";
    } else {
        $json["ajax-rankings"] = $admin["cache-rankings"];
    }
    if ($admin["mode"] == "Lockdown" && $_SESSION["status"] != "Admin" || !isset($admin["cache-allsubmit"])) {
        $json["ajax-allsubmit"] = "<h3>All Submissions</h3><table><tr><td>Not Available</td></tr></table>";
    } else {
        $json["ajax-allsubmit"] = $admin["cache-allsubmit"];
    }
    if (!isset($admin["cache-problems"]) || $admin["cache-problems"] == "") {
        $admin["cache-problems"] = "<h3>Problems Index</h3><table><tr><td>Not Available</td></tr></table>";
    }
    if ($admin["mode"] == "Lockdown" && $_SESSION["status"] != "Admin") {
        $json["ajax-problem"] = "<h3>Problems Index</h3><table><tr><td>Not Available</td></tr></table>";
    } else {
        $json["ajax-problem"] = $admin["cache-problems"];
    }
    if ($_SESSION["tid"] != 0) {
        $tid = $_SESSION["tid"];
        $t = mysql_query("SELECT teamname,score FROM teams WHERE tid={$tid}");
        if (is_resource($t)) {
            $t = mysql_fetch_array($t);
        }
        $solvedn = mysql_query("SELECT count(distinct(runs.pid)) as n FROM runs,problems WHERE runs.tid='{$tid}' and runs.result='AC' and runs.pid=problems.pid and problems.status='Active'");
        if (is_resource($solvedn) && mysql_num_rows($solvedn) == 1) {
            $solvedn = mysql_fetch_array($solvedn);
            $solvedn = $solvedn["n"];
        } else {
            $solvedn = 0;
        }
        $json["ajax-account"] = "<h3>Team Name : <a href='?display=submissions&tid={$tid}'>{$t['teamname']}</a></h3>";
        $json["ajax-account"] .= "<table><tr><th>Score</th><th>Solved</th><th><a href='?display=account'>Account</a></th></tr>";
        $json["ajax-account"] .= "<tr><td>{$t['score']}</td><td>{$solvedn}</td><td><a href='?action=logout'>Logout</a></td></table>";
    }
    if ($admin["mode"] == "Lockdown" && $_SESSION["status"] != "Admin" || !isset($admin["cache-clarlatest"])) {
        $json["ajax-publicclar"] = "<h3><a href='?display=clarifications' title='Link to Clarifications Page'>Public Clarifications</a></h3><table><tr><td>Not Available</td></tr></table>";
    } else {
        $json["ajax-publicclar"] = "<h3><a href='?display=clarifications' title='Link to Clarifications Page'>Public Clarifications</a></h3>" . $admin["cache-clarlatest"];
    }
    if ($_SESSION["tid"] == 0) {
        $json["ajax-privateclar"] = "<h3><a href='?display=clarifications'>Private Clarifications</a></h3><table><tr><td>Not Available</td></tr></table>";
    } else {
        if (isset($admin["clarprivate"]) && $admin["clarprivate"] >= 0) {
            $limit = $admin["clarprivate"];
        } else {
            $limit = 2;
        }
        $json["ajax-privateclar"] = "<h3><a href='?display=clarifications' title='Link to Clarifications Page'>My Clarifications</a></h3>";
        if (($d = mysql_getdata("SELECT * FROM clar WHERE tid={$_SESSION['tid']} and access='Private' ORDER BY time DESC LIMIT 0,{$limit}")) != NULL) {
            $json["ajax-privateclar"] .= "<table>";
            if (count($d) == 0) {
                $json["ajax-privateclar"] .= "<tr><td>Not Available</td></tr>";
            } else {
                foreach ($d as $c) {
                    if ($c["pid"] == 0) {
                        $probname = "General";
                    } else {
                        $probname = mysql_getdata("SELECT name FROM problems WHERE status='Active' AND pid={$c['pid']}");
                        $probname = "<a href='?display=problem&pid={$c['pid']}'>" . $probname[0]["name"] . "</a>";
                    }
                    $json["ajax-privateclar"] .= "<tr><td style='text-align:left;'><b><a href='?display=submissions&tid={$_SESSION['tid']}'>{$_SESSION['teamname']}</a> ({$probname})</b> : {$c['query']}</td></tr>";
                    if (!empty($c["reply"])) {
                        $json["ajax-privateclar"] .= "<tr><td style='text-align:left;'><i><b>Judge's Response</b> : {$c['reply']}</i></td></tr>";
                    }
                }
            }
            $json["ajax-privateclar"] .= "</table>";
        } else {
            $json["ajax-privateclar"] .= "<table><tr><td>Not Available</td></tr></table>";
        }
    }
    $json["refresh"] = 0;
    if ($_SESSION["tid"] != 0) {
        $temp = mysql_query("SELECT status FROM teams WHERE tid={$_SESSION['tid']}");
        if (is_resource($temp) && mysql_num_rows($temp) == 1) {
            $temp = mysql_fetch_array($temp);
            if ($temp["status"] != "Normal" && $temp["status"] != "Admin") {
                if (isset($_GET["action"]) && $_GET["action"] == "ajaxrefresh") {
                    action_logout();
                }
                unset($_SESSION["message"][count($_SESSION["message"]) - 1]);
                $_SESSION["message"][] = "Access Denied : You have been logged out as your account is no longer Active.";
                $json["refresh"] = 1;
            }
        }
    }
    if ($type == 0 && $admin["ajaxrr"] == 0) {
        $json["refresh"] = 1;
    }
    if ($ajaxlogout == 1) {
        $json["refresh"] = 1;
    }
    $json["newclar"] = "";
    $data = mysql_query("SELECT * FROM clar WHERE (access='Public' or tid=" . $_SESSION["tid"] . ") and access!='Delete' and time>" . $_SESSION["time"]);
    if (is_resource($data) && mysql_num_rows($data)) {
        $json["newclar"] = array();
        while ($temp = mysql_fetch_array($data)) {
            if ($temp["pid"] == 0) {
                $prob = array("name" => "General");
            } else {
                $prob = mysql_fetch_array(mysql_query("SELECT name FROM problems WHERE pid=" . $temp["pid"]));
            }
            $team = mysql_fetch_array(mysql_query("SELECT teamname FROM teams WHERE tid=" . $temp["tid"]));
            $json["newclar"][] = $team["teamname"] . " (" . $prob["name"] . ") : " . unfilter($temp["query"]) . (!empty($temp["reply"]) ? "\nJudge`s Response : " . unfilter($temp["reply"]) : "");
        }
        $json["newclar"] = "Latest Clarification(s)\n\n" . implode($json["newclar"], "\n\n");
    }
    $json["newclar2"] = "";
    if ($_SESSION["status"] == "Admin") {
        $data = mysql_query("SELECT * FROM clar WHERE reply='' and time>" . $_SESSION["time"]);
        if (is_resource($data) && mysql_num_rows($data)) {
            $json["newclar2"] = array();
            while ($temp = mysql_fetch_array($data)) {
                if ($temp["pid"] == 0) {
                    $prob = array("name" => "General");
                } else {
                    $prob = mysql_fetch_array(mysql_query("SELECT name FROM problems WHERE pid=" . $temp["pid"]));
                }
                $team = mysql_fetch_array(mysql_query("SELECT teamname FROM teams WHERE tid=" . $temp["tid"]));
                $json["newclar2"][] = $team["teamname"] . " (" . $prob["name"] . ") : " . unfilter($temp["query"]);
            }
            $json["newclar2"] = "Clarification Request(s)\n\n" . implode($json["newclar2"], "\n\n");
        }
    }
    $_SESSION["time"] = time();
    return json_encode($json);
}
function display_submissions()
{
    global $admin, $fullresult, $currentmessage, $extension;
    if ($admin["mode"] == "Lockdown" && $_SESSION["status"] != "Admin") {
        $_SESSION["message"] = $currentmessage;
        $_SESSION["message"][] = "Access Denied : The contest is currently in Lockdown Mode. Please try again later.";
        echo "<script>window.location='?display=faq';</script>";
        return;
    }
    $urlargs = "display=submissions";
    foreach ($_GET as $key => $value) {
        if ($key != "display" && $key != "page") {
            $urlargs .= "&" . urlencode($key) . "=" . urlencode($value);
        }
    }
    $rejudge = "action=rejudge";
    $filter = array();
    $filters = array();
    if (isset($_GET["tid"]) && !empty($_GET["tid"]) && is_numeric($_GET["tid"])) {
        $t = mysql_query("SELECT * FROM teams WHERE tid=" . $_GET["tid"] . " and (status='Normal' or status='Admin')");
        if (is_resource($t) && mysql_num_rows($t)) {
            $filter["tid"] = $_GET["tid"];
            $teamdata = mysql_fetch_array($t);
            $filters[] = "<a href='?" . str_replace("&tid={$filter['tid']}", "", $urlargs) . "'>{$teamdata['teamname']}</a>";
            $rejudge .= "&tid={$filter['tid']}";
        }
    }
    if (isset($_GET["pid"]) && !empty($_GET["pid"]) && is_numeric($_GET["pid"])) {
        $t = mysql_query("SELECT * FROM problems WHERE pid=" . $_GET["pid"] . " and status" . ($_SESSION["status"] == "Admin" ? "!='Delete'" : "='Active'") . ";");
        if (is_resource($t) && mysql_num_rows($t)) {
            $filter["pid"] = $_GET["pid"];
            $probdata = mysql_fetch_array($t);
            $filters[] = "<a href='?" . str_replace("&pid={$filter['pid']}", "", $urlargs) . "'>{$probdata['name']}</a>";
            $rejudge .= "&pid={$filter['pid']}";
        }
    }
    if (isset($_GET["lan"]) && !empty($_GET["lan"]) && key_exists($_GET["lan"], $extension)) {
        $filter["language"] = $_GET["lan"];
        $filters[] = "<a href='?" . str_replace("&lan=" . urlencode($filter["language"]), "", $urlargs) . "'>" . ($filter["language"] == "Brain" ? "Brainf**k" : $filter["language"]) . "</a>";
        $rejudge .= "&lan=" . urlencode($_GET["lan"]);
    }
    if (isset($_GET["res"]) && !empty($_GET["res"]) && key_exists($_GET["res"], $fullresult)) {
        $filter["result"] = $_GET["res"];
        $filters[] = "<a href='?" . str_replace("&res={$filter['result']}", "", $urlargs) . "'>" . $fullresult[$filter["result"]] . "</a>";
        $rejudge .= "&res=" . urlencode($_GET["res"]);
    }
    $condition = "";
    foreach ($filter as $key => $value) {
        if ($key == "result" && $value == "NA") {
            $condition .= " AND (result='' OR result='...') ";
        } else {
            $condition .= "AND {$key}=" . (is_numeric($value) ? "{$value}" : "'{$value}'") . " ";
        }
    }
    // Problem Groups - Special Condition
    if (($g = mysql_getdata("SELECT distinct pgroup FROM problems WHERE status" . ($_SESSION["status"] == "Admin" ? "!='Delete'" : "='Active'") . " ORDER BY pgroup")) != NULL) {
        $t = array();
        foreach ($g as $gn) {
            $t[] = $gn["pgroup"];
        }
        $g = $t;
        unset($t);
    } else {
        $g = array();
    }
    if (isset($_GET["pgr"]) && !empty($_GET["pgr"]) && in_array($_GET["pgr"], $g)) {
        $t = mysql_query("SELECT * FROM problems WHERE pgroup='" . addslashes($_GET["pgr"]) . "' and status" . ($_SESSION["status"] == "Admin" ? "!='Delete'" : "='Active'") . "");
        if (is_resource($t) && mysql_num_rows($t)) {
            $filter["pgroup"] = $_GET["pgr"];
            $probdata = mysql_fetch_array($t);
            $filters[] = "<a href='?" . str_replace("&pgr=" . urlencode($filter["pgroup"]), "", $urlargs) . "'>" . filter(eregi_replace("^#[0-9]+ ", "", $filter["pgroup"])) . "</a>";
            $rejudge .= "&pgr={$filter['pgroup']}";
            $condition .= " AND pid in (SELECT pid FROM problems WHERE pgroup='{$filter['pgroup']}')";
        }
    }
    echo "<center>";
    if (count($filter)) {
        echo "<div class='filter'><b>Active Filter(s)</b> : " . implode($filters, " , ") . " (Click to Remove)</div>";
    } else {
        echo "<div class='filter'><b>Active Filter(s)</b> : None</div>";
    }
    if (isset($filter["tid"]) || isset($filter["pid"]) || !isset($filter["result"]) || !isset($filter["language"])) {
        echo "<br><h3>";
    }
    if (isset($filter["tid"])) {
        echo "<a onClick=\"\$('#team-information').slideToggle();\$('#problem-information').slideUp();\$('#submission-statistics').slideUp();\" title='Click here to show/hide team information.'>{$teamdata['teamname']} : Team Information</a>";
        if (isset($filter["pid"]) || !isset($filter["result"]) || !isset($filter["language"])) {
            echo " | ";
        }
    }
    if (isset($filter["pid"])) {
        echo "<a onClick=\"\$('#problem-information').slideToggle();\$('#team-information').slideUp();\$('#submission-statistics').slideUp();\" title='Click here to show/hide problem information.'>{$probdata['name']} : Problem Information</a>";
        if (!isset($filter["result"]) || !isset($filter["language"])) {
            echo " | ";
        }
    }
    if (!isset($filter["result"]) || !isset($filter["language"])) {
        echo "<a onClick=\"\$('#submission-statistics').slideToggle();\$('#problem-information').slideUp();\$('#team-information').slideUp();\" title='Click here to show/hide submission statistics.'>Submission Statistics</a>";
    }
    if (isset($filter["tid"]) || isset($filter["pid"]) || !isset($filter["result"]) || !isset($filter["language"])) {
        echo "</h3>";
    }
    if (isset($filter["tid"])) {
        $members = array();
        for ($i = 1; $i <= 3; $i++) {
            if (!empty($teamdata["name" . $i])) {
                $members[] = $teamdata["name" . $i];
            }
        }
        $members = implode($members, ", ");
        $data = mysql_query("SELECT distinct(runs.pid),problems.name,problems.code FROM runs,problems WHERE runs.tid='{$filter['tid']}' and runs.result='AC' and runs.pid=problems.pid and problems.status" . ($_SESSION["status"] == "Admin" ? "!='Delete'" : "='Active'") . " and runs.access!='deleted'");
        if (is_resource($data)) {
            $solvedn = mysql_num_rows($data);
            $solvedp = array();
            while ($temp = mysql_fetch_array($data)) {
                $solvedp[] = "<a href='?display=problem&pid={$temp['pid']}' title=\"{$temp['code']}\">{$temp['name']}</a>";
            }
            $solvedp = implode($solvedp, ", ");
        } else {
            $solvedn = 0;
            $solvedp = "";
        }
        echo "<div id='team-information' style='display:none;'>";
        echo "<table width=80%><tr><th>Team Members</th><td>{$members}</td></tr><tr><th>Score</th><td>{$teamdata['score']}</td></tr><tr><th>Problems Solved</th><td>{$solvedp} ({$solvedn})</td></tr>";
        echo "</table><br></div>";
    }
    if (isset($filter["pid"])) {
        echo "<div id='problem-information' style='display:none;'><table width=80%>\r\n\t\t\t<tr><th>Problem ID</th><td>{$probdata['pid']}</td><th>Problem Type</th><td>{$probdata['type']}</td><th>Time Limit</th><td>{$probdata['timelimit']} sec</td></tr>\r\n\t\t\t<tr><th>Problem Code</th><td>{$probdata['code']}</td><th>Input File Size</th><td>" . display_filesize(strlen($probdata["input"])) . "</td><th>Score</th><td>{$probdata['score']}</td></tr>";
        echo "</table><br>";
        echo "<a href='?display=problem&pid={$probdata['pid']}'>Link to Problem</a><br></div>";
    }
    if (!isset($filter["result"]) || !isset($filter["language"])) {
        echo "<div id='submission-statistics' style='display:none;'>";
    }
    if (!isset($filter["result"])) {
        $t1 = mysql_query("SELECT result,count(*) as cnt FROM runs WHERE access!='deleted' AND tid in (SELECT tid FROM teams WHERE status='Normal' OR status='Admin') AND pid in (SELECT pid FROM problems WHERE status" . ($_SESSION["status"] == "Admin" ? "!='Delete'" : "='Active'") . ") {$condition} group by result;");
        if (is_resource($t1)) {
            for ($info2 = array(); $t2 = mysql_fetch_array($t1);) {
                if ($t2["result"] == "") {
                    $t2["result"] = "...";
                }
                $info2[$t2["result"]] = $t2["cnt"];
            }
        }
        if (!isset($info2["..."])) {
            $info2["..."] = 0;
        }
        $info = array("TOT" => $info2["..."], "..." => $info2["..."]);
        foreach ($fullresult as $key => $value) {
            if (key_exists($key, $info2)) {
                $info["TOT"] += $info[$key] = $info2[$key];
            } else {
                $info[$key] = 0;
            }
        }
        if ($info != NULL) {
            echo "<table class='substat'><tr><th>Total Submissions</th>";
            foreach ($fullresult as $key => $value) {
                echo "<th><a href='?" . $urlargs . "&res={$key}'>" . $value . "</a></th>";
            }
            echo "<th>Unjudged Submissions</th></tr><tr><td>" . $info["TOT"] . "</td>";
            foreach ($fullresult as $key => $value) {
                echo "<td>" . $info[$key] . "</td>";
            }
            echo "<td>" . $info["..."] . "</td></tr></table><br>";
        }
    }
    if (!isset($filter["language"])) {
        $t1 = mysql_query("SELECT language,count(*) as cnt FROM runs WHERE access!='deleted' AND tid in (SELECT tid FROM teams WHERE status='Normal' OR status='Admin') AND pid in (SELECT pid FROM problems WHERE status" . ($_SESSION["status"] == "Admin" ? "!='Delete'" : "='Active'") . ") {$condition} group by language;");
        if (is_resource($t1)) {
            for ($info2 = array(); $t2 = mysql_fetch_array($t1);) {
                $info2[$t2["language"]] = $t2["cnt"];
            }
        }
        $info = array();
        foreach ($extension as $key => $value) {
            if (key_exists($key, $info2)) {
                $info[$key] = $info2[$key];
            } else {
                $info[$key] = 0;
            }
        }
        if ($info != NULL) {
            echo "<table class='substat'><tr>";
            foreach ($extension as $key => $value) {
                echo "<th><a href='?" . $urlargs . "&lan=" . urlencode($key) . "'>" . ($key == "Brain" ? "Brainf**k" : $key) . "</a></th>";
            }
            echo "</tr><tr>";
            foreach ($extension as $key => $value) {
                echo "<td>" . $info[$key] . "</td>";
            }
            echo "</tr></table><br>";
        }
    }
    if (!isset($filter["result"]) || !isset($filter["language"])) {
        echo "</div>";
    }
    echo "<h2>Submission Status</h2>";
    if ($_SESSION["status"] == "Admin") {
        if ($rejudge == "action=rejudge") {
            $rejudge .= "&all=1";
        }
        echo "<input type='button' value='Rejudge Selected Submissions' onClick=\"if(confirm('Are you sure you wish to rejudge all currently selected submissions?'))window.location='?{$rejudge}';\"><br><br>";
    }
    $total = mysql_query("SELECT count(*) as total FROM runs WHERE access!='deleted' AND tid in (SELECT tid FROM teams WHERE status='Normal' OR status='Admin') AND pid in (SELECT pid FROM problems WHERE status" . ($_SESSION["status"] == "Admin" ? "!='Delete'" : "='Active'") . ") {$condition} ORDER BY rid DESC");
    $total = mysql_fetch_array($total);
    $total = $total["total"];
    if (isset($admin["substatpage"]) && $admin["substatpage"] >= 0) {
        $perpage = $admin["substatpage"];
    } else {
        $perpage = 25;
    }
    $x = paginate($urlargs, $total, $perpage);
    $page = $x[0];
    $pagenav = $x[1];
    echo $pagenav . "<br><br>";
    echo "<table class='submission'><th>Run ID</th><th>Team</th><th>Problem</th><th>Language</th><th>Time</th><th>Result</th><th " . ($_SESSION["status"] == "Admin" ? "style='width:170px;'" : "") . ">Options</th></tr>";
    $data = mysql_query("SELECT * FROM runs WHERE access!='deleted' AND tid in (SELECT tid FROM teams WHERE status='Normal' OR status='Admin') AND pid in (SELECT pid FROM problems WHERE status" . ($_SESSION["status"] == "Admin" ? "!='Delete'" : "='Active'") . ") {$condition} ORDER BY rid DESC LIMIT " . ($page - 1) * $perpage . "," . $perpage);
    if (is_resource($data)) {
        $n = mysql_num_rows($data);
    }
    if (is_resource($data)) {
        for ($i = 0; $temp = mysql_fetch_array($data); $i++) {
            if ($i == $perpage) {
                break;
            }
            if ($temp["language"] == "Brain") {
                $temp["lan"] = "Brainf**k";
            } else {
                $temp["lan"] = $temp["language"];
            }
            $t = mysql_query("SELECT teamname FROM teams WHERE tid={$temp['tid']} and (status='Normal' or status='Admin')");
            if (is_resource($t) && mysql_num_rows($t) == 1) {
                $t = mysql_fetch_array($t);
                $teamname = $t['teamname'];
            } else {
                continue;
            }
            $t = mysql_query("SELECT name FROM problems WHERE pid={$temp['pid']} and status" . ($_SESSION["status"] == "Admin" ? "!='Delete'" : "='Active'") . ";");
            if (is_resource($t) && mysql_num_rows($t) == 1) {
                $t = mysql_fetch_array($t);
                $probname = $t['name'];
            } else {
                continue;
            }
            $fresult = $result = $temp["result"];
            if (isset($fullresult[$result])) {
                $fresult = $fullresult[$result];
            }
            $r = $result;
            if ($result == "") {
                $r = "NA";
                $fresult = "Queued";
            } elseif ($result == "...") {
                $r = "NA";
                $fresult = "Evaluating";
            } elseif ($result != "AC") {
                $result = "NAC";
            }
            if ($_SESSION["status"] == "Admin" || $_SESSION["tid"] == $temp["tid"] || $temp["access"] == "public") {
                echo "<tr class='{$result}'><td><a href='?display=code&rid={$temp['rid']}' title='Link to Code'>{$temp['rid']}</a></td><td><a href='?" . str_replace("&tid={$temp['tid']}", "", $urlargs) . "&tid={$temp['tid']}' title='Link to Team'>{$teamname}</td><td><a href='?" . str_replace("&pid={$temp['pid']}", "", $urlargs) . "&pid={$temp['pid']}' title='Link to Problem'>{$probname}</a></td><td><a href='?" . str_replace("&lan=" . urlencode($temp["language"]), "", $urlargs) . "&lan=" . urlencode($temp["language"]) . "' title='Link to {$temp['lan']} Submissions'>{$temp['lan']}</a></td><td>{$temp['time']}</td><td class='{$result}'><a href='?{$urlargs}&res={$r}'>{$fresult}</a></td>";
            } else {
                echo "<tr class='{$result}'><td>{$temp['rid']}</td><td><a href='?" . str_replace("&tid={$temp['tid']}", "", $urlargs) . "&tid={$temp['tid']}'>{$teamname}</td><td><a href='?" . str_replace("&pid={$temp['pid']}", "", $urlargs) . "&pid={$temp['pid']}'>{$probname}</a></td><td><a href='?" . str_replace("&lan=" . urlencode($temp["language"]), "", $urlargs) . "&lan=" . urlencode($temp["language"]) . "' title='Link to {$temp['lan']} Submissions'>{$temp['lan']}</a></td><td>{$temp['time']}</td><td class='{$result}'><a href='?{$urlargs}&res={$r}'>{$fresult}</a></td>";
            }
            if ($_SESSION["status"] == "Admin") {
                echo "<td><input type='button' value='Rejudge' onClick=\"window.location='?action=rejudge&rid={$temp['rid']}';\">";
                if ($temp["access"] == "private") {
                    echo "<input type='button' value='Private' title='Make this code Public (visible to all).' onClick=\"window.location='?action=makecodepublic&rid={$temp['rid']}';\">";
                } else {
                    echo "<input type='button' value='Public' title='Make this code Private (visible only to the team that submitted it).' onClick=\"window.location='?action=makecodeprivate&rid={$temp['rid']}';\">";
                }
                echo "<input type='button' value='Delete' onClick=\"if(confirm('Are you sure you wish to delete Run ID {$temp['rid']}?'))window.location='?action=makecodedeleted&rid={$temp['rid']}';\">";
                echo "</td>";
            } else {
                if ($_SESSION["status"] == "Admin" || $_SESSION["tid"] == $temp["tid"] || $temp["access"] == "public") {
                    echo "<td><input type='button' value='Code' onClick=\"window.location='?display=code&rid={$temp['rid']}';\"></td>";
                } else {
                    echo "<td></td>";
                }
            }
            echo "</tr>";
        }
    }
    echo "</table><br>";
    echo $pagenav . "</center>";
}