-
Notifications
You must be signed in to change notification settings - Fork 0
/
grader.php.bak
280 lines (240 loc) · 8.24 KB
/
grader.php.bak
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
<?php
define('TEST_DATA_DIR', '../test-data');
define('SOLUTIONS_DIR', '../solutions');
define('IDEONE_USER', 'hhsprogramming');
define('IDEONE_PASSWORD', 'hhsprog4ming');
define('RESULTS_DB', '../problem-results.json');
// enabled languages
// TODO: read from db
$langs = array(
10 => array("name" => "Java", "ext" => "java"),
116 => array("name" => "Python 3", "ext" => "py"),
44 => array("name" => "C++", "ext" => "cpp")
);
// prints out grading result as HTML
function showResult($result, $description = "", $error = false) {
$color = $error ? "red" : "green";
echo "<div style=\"color: $color\">$result<br /><small>$description</small></div>";
}
// stores grading results in db
function storeResult($prob, $email, $lang, $correct, $err_msg = "", $time = NULL, $mem = NULL) {
$results = json_decode(file_get_contents(RESULTS_DB), true);
if (!isset($results[$prob])) $results[$prob] = array();
$result = array("lang" => $lang,
"correct" => $correct,
"timestamp" => date("c"));
if (!empty($err_msg)) $result["err_msg"] = $err_msg;
if (!is_null($time)) $result["time"] = $time;
if (!is_null($mem)) $result["mem"] = $mem;
$results[$prob][$email] = $result;
file_put_contents(RESULTS_DB, json_encode($results, JSON_PRETTY_PRINT));
}
// returns any previous grading result from db
function getResult($prob, $email) {
$results = json_decode(file_get_contents(RESULTS_DB), true);
if (empty($results[$prob])) return false;
if (isset($results[$prob][$email])) return $results[$prob][$email];
return false;
}
// grade submission if AJAX
if ($_SERVER["PHP_SELF"] === "/grader.php") {
if (empty($_POST['user']) || empty($_POST['problem'])
|| empty($_POST['lang']) || empty($_FILES['file'])
|| !$_FILES['file']['size']) {
die();
}
$user = $_POST['user']; // submitter
$prob = $_POST['problem']; // problem name
$lang = intval($_POST['lang']); // source code language
$uploaded = $_FILES['file']['tmp_name']; // uploaded file path
// check that test data exists for problem
if (!file_exists(TEST_DATA_DIR."/$prob.in")
|| !file_exists(TEST_DATA_DIR."/$prob.out")
|| !is_dir(SOLUTIONS_DIR)) {
die("Missing test data for problem $prob.");
}
// store solution in filesystem
$contents = file_get_contents($uploaded);
if (!file_exists(SOLUTIONS_DIR."/$prob")) {
mkdir(SOLUTIONS_DIR."/$prob");
}
move_uploaded_file($uploaded, SOLUTIONS_DIR."/$prob/$user.{$langs[$lang]["ext"]}");
// replace class name for Java
if ($lang === 10) {
$contents = str_replace($prob, "Main", $contents, $count);
if ($count === 0) {
storeResult($prob, $user, $lang, false, 'Class name is incorrect.');
showResult("Class name is incorrect.", "", true);
die();
}
}
// ideone API (http://ideone.com/files/ideone-api.pdf)
try {
$client = new SoapClient('http://ideone.com/api/1/service.wsdl');
} catch (Exception $e) {
die("SOAP fault: ".$e->getMessage());
}
// upload source code to ideone
try {
$result = $client->__soapCall('createSubmission',
array('user' => IDEONE_USER,
'pass' => IDEONE_PASSWORD,
'sourceCode' => $contents,
'language' => $lang,
'input' => file_get_contents(TEST_DATA_DIR."/$prob.in"),
'run' => true,
'private' => true));
} catch (SoapFault $e) {
die("SOAP fault: ".$e->getMessage());
}
if ($result['error'] !== 'OK') { // Ideone API error
die('Ideone error: '.$result['error']);
}
$link = $result['link'];
// poll for submission result
do {
try {
$result = $client->__soapCall('getSubmissionStatus',
array('user' => IDEONE_USER,
'pass' => IDEONE_PASSWORD,
'link' => $link));
} catch (SoapFault $e) {
die("SOAP fault: ".$e->getMessage());
}
if ($result['error'] !== 'OK') { // Ideone API error
die('Ideone error: '.$result['error']);
}
if ($result['status'] !== 0) { // wait 3 seconds before trying
sleep(3); // trying again
}
} while ($result['status'] !== 0); // not finished running
// handle runtime/compilation errors
if ($result['result'] === 11) {
storeResult($prob, $user, $lang, false, 'Compilation error.');
showResult("Result: Compilation error.", "", true);
die();
} elseif ($result['result'] === 12) {
storeResult($prob, $user, $lang, false, 'Runtime error.');
showResult("Result: Runtime error.", "", true);
die();
} elseif ($result['result'] === 13) {
storeResult($prob, $user, $lang, false, 'Time limit (5s) exceeded.');
showResult("Result: Time limit (5s) exceeded.", "", true);
die();
} elseif ($result['result'] === 19) {
storeResult($prob, $user, $lang, false, 'Illegal system call');
showResult("Result: Illegal system call", "", true);
die();
} elseif ($result['result'] === 20) {
showResult("Ideone internal error. Please try again later.", "", true);
die();
} elseif ($result['result'] !== 15) { // status is not success
storeResult($prob, $user, $lang, false, 'Unknown error.');
showResult("Result: Unknown error.", "", true);
die();
}
// check if output is correct
try {
$result = $client->__soapCall('getSubmissionDetails',
array('user' => IDEONE_USER,
'pass' => IDEONE_PASSWORD,
'link' => $link,
'withSourceCode' => false,
'withInput' => false,
'withOutput' => true,
'withStderr' => false,
'withCmpinfo' => false));
} catch (SoapFault $e) {
die("SOAP fault: ".$e->getMessage());
}
if ($result['error'] !== 'OK') { // Ideone API error
die('Ideone error: '.$result['error']);
}
if (trim($result['output']) === trim(file_get_contents(TEST_DATA_DIR."/$prob.out"))) {
storeResult($prob, $user, $lang, true, '', $result['time'], $result['memory']);
showResult("Result: Correct.",
'Runtime: '.$result['time'].'s, Memory Usage: '
.round($result['memory'] / 1000, 2).' KB');
// echo '<span style="color: green">Result: Correct.<h4>Runtime: '.$result['time'].'s.</h4>'
// .'<h4>Memory Usage: '.round($result['memory'] / 1000, 2).' KB</h4></span>';
} else {
storeResult($prob, $user, $lang, false, 'Incorrect output.');
showResult("Result: Incorrect output.", "", true);
}
// show submission form if included
} else {
$prob = $_GET["problem"];
if (empty($prob)) return;
if (isset($_SESSION["user"])) {
?>
<h3>Submit your solution (<?php echo $prob; ?>.<span id="ext">java</span>):</h3>
<form id="grader" action="/grader.php" enctype="multipart/form-data">
<label>Language: <select name="lang" id="lang">
<?php
foreach ($langs as $id => $lang) {
echo <<<EOT
<option value="$id">{$lang["name"]}</option>
EOT;
}
?>
</select></label>
<input type="file" name="file" id="file" accept=".java" required="" />
<input type="submit" value="Submit" class="btn" />
<input type="hidden" name="user" value="<?php echo $_SESSION["user"]["email"]; ?>" />
<input type="hidden" name="problem" value="<?php echo $prob; ?>" /><br />
<small>Powered by <a href="http://ideone.com">ideone.com</a></small>
</form>
<div id="result"></div>
<?php
if ($result = getResult($prob, $_SESSION["user"]["email"])) {
?>
<br />
<h3>Previous submission results</h3>
<?php
$msg = $result['correct'] ? 'Correct' : $result['err_msg'];
$stats = $result['correct'] ? "Runtime: {$result['time']}s, "
.'Memory Usage: '.round($result['mem'] / 1000, 2).' KB' : "";
showResult("Result: $msg", $stats, !$result['correct']);
}
?>
<script type="text/javascript">
var exts = {
<?php
$comma = "";
foreach ($langs as $id => $lang) {
$comma = ",";
echo <<<EOT
$id: "{$lang["ext"]}"$comma
EOT;
}
?>
};
document.getElementById("lang").onchange = function () {
var ext = exts[this.options[this.selectedIndex].value];
document.getElementById("ext").innerHTML = ext;
document.getElementById("file").accept = "." + ext;
};
document.getElementById("grader").onsubmit = function (e) {
e.preventDefault();
document.getElementById("result").innerHTML = "<br />Loading...";
var xhr = new XMLHttpRequest();
xhr.onload = function () {
// clears file upload field
var file = document.getElementById("file");
file.parentNode.insertBefore(file.cloneNode(), file);
file.parentNode.removeChild(file);
document.getElementById("result").innerHTML = "<br />" + this.response;
};
xhr.open("POST", "/grader.php");
xhr.send(new FormData(this));
};
</script>
<?php
// not logged in
} else {
?>
<br />You must be <a href="/login/">logged in</a> to submit a solution.
<?php
}
}
?>