forked from drlippman/IMathAS
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblems.php
More file actions
440 lines (387 loc) · 17.2 KB
/
problems.php
File metadata and controls
440 lines (387 loc) · 17.2 KB
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
<?php
require_once "init_without_validate.php";
require_once 'assess2/AssessStandalone.php';
require_once "filter/math/ASCIIMath2TeX.php";
global $allowedmacros;
$allowedmacros[] = "showplot_with_functions";
$GLOBALS['hide-sronly'] = true;
$_SESSION['graphdisp'] = 1;
$_SESSION['userprefs']['drawentry'] = 1;
/**
* Parses graph settings and function definitions from a set of inputs.
*
* NOTE: This function assumes the existence of helper functions:
* - listtoarray($string): Converts a comma-separated string to an array.
* - makepretty($string): Cleans up an equation string.
* - evalbasic($string): Evaluates a basic mathematical string into a number.
*
* @param array|string $funcs The function(s) to parse.
* @return array The structured $graph_settings array.
*/
function showplot_with_functions($funcs) { //optional arguments: $xmin,$xmax,$ymin,$ymax,labels,grid,width,height
// --- 1. CONFIGURATION SETUP ---
if (!is_array($funcs)) {
settype($funcs,"array");
}
$settings = array(-5,5,-5,5,1,1,200,200);
for ($i = 1; $i < func_num_args(); $i++) {
$v = func_get_arg($i);
if ($v === null) { $v = 0; }
if (!is_scalar($v)) {
// In a real application, this should throw an exception or return an error
echo 'Invalid input '.($i+1).' to showplot';
} else {
$settings[$i-1] = $v;
}
}
// Parse special syntax for axes
$fqonlyx = false; $fqonlyy = false;
if (strpos($settings[0],'0:')!==false) {
$fqonlyx = true;
$settings[0] = substr($settings[0],2);
}
if (strpos($settings[2],'0:')!==false) {
$fqonlyy = true;
$settings[2] = substr($settings[2],2);
}
// Check for auto-scaling flags but defer calculation
$yminauto = false;
if (substr($settings[2],0,4)=='auto') {
$yminauto = true;
$settings[2] = (strpos($settings[2],':')!==false) ? explode(':',$settings[2])[1] : -5;
}
$ymaxauto = false;
if (substr($settings[3],0,4)=='auto') {
$ymaxauto = true;
$settings[3] = (strpos($settings[3],':')!==false) ? explode(':',$settings[3])[1] : 5;
}
// Assign final config values
$winxmin = is_numeric($settings[0])?$settings[0]:-5;
$winxmax = is_numeric($settings[1])?$settings[1]:5;
$ymin = is_numeric($settings[2])?$settings[2]:-5;
$ymax = is_numeric($settings[3])?$settings[3]:5;
$plotwidth = is_numeric($settings[6])?$settings[6]:200;
$plotheight = is_numeric($settings[7])?$settings[7]:200;
$noyaxis = false; $noxaxis = false;
if (is_numeric($ymin) && is_numeric($ymax) && $ymin==0 && $ymax==0) {
$noyaxis = true;
}
// Parse labels and grid settings
if (strpos($settings[4],':')) {
$lbl = explode(':',$settings[4]);
$lbl[0] = evalbasic($lbl[0], true, true);
$lbl[1] = evalbasic($lbl[1], true, true);
if ($lbl[0] == 0) $noxaxis = true;
if ($lbl[1] == 0) $noyaxis = true;
} else {
$settings[4] = evalbasic($settings[4], true, true);
$lbl = [];
}
if (strpos($settings[5],':')) {
$grid = explode(':', str_replace(array('(',')'),'',$settings[5]));
foreach ($grid as $i=>$v) { $grid[$i] = evalbasic($v, true, true); }
} else {
$settings[5] = evalbasic($settings[5], true, true);
$grid = [];
}
// --- 2. INITIALIZE GRAPH SETTINGS ARRAY ---
$graph_settings = [
'view_window' => [
'xmin' => $winxmin,
'xmax' => $winxmax,
'ymin' => $ymin,
'ymax' => $ymax
],
'is_ymin_auto' => $yminauto,
'is_ymax_auto' => $ymaxauto,
'canvas_size' => [
'width' => $plotwidth,
'height' => $plotheight
],
'axes_config' => [
'x_tick_interval' => isset($lbl[0]) ? $lbl[0] : (is_numeric($settings[4]) ? $settings[4] : 1),
'y_tick_interval' => isset($lbl[1]) ? $lbl[1] : (is_numeric($settings[4]) ? $settings[4] : 1),
'show_x_axis' => !$noxaxis,
'show_y_axis' => !$noyaxis,
'first_quadrant_x_only' => $fqonlyx,
'first_quadrant_y_only' => $fqonlyy,
'show_tick_labels' => !(isset($lbl[2]) && $lbl[2] == 'off')
],
'grid_config' => [
'x_interval' => isset($grid[0]) && is_numeric($grid[0]) ? $grid[0] : (is_numeric($settings[5]) ? $settings[5] : 0),
'y_interval' => isset($grid[1]) && is_numeric($grid[1]) ? $grid[1] : (is_numeric($settings[5]) ? $settings[5] : 0)
],
'functions' => [] // This will be populated below
];
// --- 3. PARSE ALL INPUT FUNCTIONS ---
foreach ($funcs as $function) {
if ($function=='') { continue;}
$function = str_replace('\\,','&x44;', $function);
$function = listtoarray($function);
if (!isset($function[0]) || $function[0]==='') { continue; }
if ($function[0][0] == 'y') {
$function[0] = preg_replace('/^\s*y\s*=?/', '', $function[0]);
if ($function[0]==='') { continue; }
}
$current_function = [];
if ($function[0]=='dot') {
$current_function = [
'type' => 'dot',
'x' => $function[1],
'y' => $function[2],
'style' => isset($function[3]) && $function[3] == 'open' ? 'open' : 'closed',
'color' => isset($function[4]) && $function[4] != '' ? $function[4] : 'black'
];
if (isset($function[5]) && $function[5] != '') {
$current_function['label'] = [
'text' => str_replace('&x44;', ',', $function[5]),
'location' => isset($function[6]) ? $function[6] : 'above'
];
}
} else if ($function[0]=='text') {
$current_function = [
'type' => 'text',
'x' => $function[1],
'y' => $function[2],
'content' => str_replace('&x44;', ',', $function[3]),
'color' => isset($function[4]) && $function[4] != '' ? $function[4] : 'black',
'location' => isset($function[5]) ? $function[5] : 'centered',
'angle' => isset($function[6]) ? intval($function[6]) : 0
];
} else {
$func_details = [];
if ($function[0][0]=='[') {
$func_details = [
'type' => 'parametric',
'x_equation' => makepretty(str_replace("[","",$function[0])),
'y_equation' => makepretty(str_replace("]","",$function[1]))
];
array_shift($function);
} else if ($function[0][0]=='<' || $function[0][0]=='>') {
$ineqtype = ($function[0][1]=='=') ? substr($function[0],0,2) : $function[0][0];
$func_details = [
'type' => 'inequality',
'inequality_type' => $ineqtype,
'equation' => makepretty(substr($function[0],strlen($ineqtype)))
];
} else if (strlen($function[0])>1 && $function[0][0]=='x' && in_array($function[0][1], ['<','>','='])) {
if ($function[0][1]=='=') {
$func_details = ['type' => 'vertical_line', 'x_value' => substr($function[0],2)];
} else {
$ineqtype = ($function[0][2]=='=') ? substr($function[0],1,2) : $function[0][1];
$func_details = [
'type' => 'vertical_inequality',
'inequality_type' => $ineqtype,
'x_value' => substr($function[0],strlen($ineqtype)+1)
];
}
} else {
$func_details = ['type' => 'standard', 'equation' => makepretty($function[0])];
}
$attributes = [
'color' => isset($function[1]) && $function[1] != '' ? $function[1] : 'black',
'width' => isset($function[6]) && $function[6] != '' ? $function[6] : '1',
'style' => (isset($function[7]) && $function[7] == 'dash') || ($func_details['type'] == 'inequality' && strlen($func_details['inequality_type'])==1) ? 'dashed' : 'solid',
'endpoints' => [
'start' => isset($function[4]) && in_array($function[4], ['open','closed','arrow']) ? $function[4] : 'none',
'end' => isset($function[5]) && in_array($function[5], ['open','closed','arrow']) ? $function[5] : 'none'
]
];
$domain = ['min' => $winxmin, 'max' => $winxmax];
if (isset($function[2]) && $function[2] != '') { $domain['min'] = evalbasic($function[2], true, true); }
$avoid = [];
if (isset($function[3]) && $function[3] != '') {
$xmaxarr = explode('!',$function[3]);
$domain['max'] = ($xmaxarr[0] != '') ? evalbasic($xmaxarr[0], true, true) : $winxmax;
if (count($xmaxarr)>1) { $avoid = array_slice($xmaxarr,1); }
}
$attributes['domain'] = $domain;
$attributes['avoid_points'] = $avoid;
$current_function = array_merge($func_details, $attributes);
}
if (!empty($current_function)) {
$graph_settings['functions'][] = $current_function;
}
}
// --- 4. RETURN FINAL SETTINGS OBJECT ---
// Encode the entire settings and functions object into a JSON string.
// This passes all configuration and function definitions to the renderer.
$json_settings = json_encode($graph_settings);
// Create the script command for the client-side SVG renderer.
$commands = "drawPicture({$json_settings})";
return "<embed type='image/svg+xml' align='middle' width='$plotwidth' height='$plotheight' script='$commands' />\n";
}
/**
* Injects a function_list attribute into embed tags produced by showplot_with_functions.
* Each embed has script='drawPicture({JSON})'; this parses the JSON and builds a
* comma-separated function_list string that replace_graph_function_lists() in the
* Python backend can consume to produce human-readable <GraphData> blocks for LLMs.
*
* Supported function types serialised into function_list:
* standard → "equation,color"
* text → "text,x,y,content,color"
* dot → "dot,x,y,style,color"
*/
function injectFunctionListAttributes($html) {
return preg_replace_callback(
"/<embed([^>]*)script='drawPicture\((\{[^']*\})\)'([^>]*)\/>/s",
function($m) {
$before = $m[1]; $jsonStr = $m[2]; $after = $m[3];
$config = json_decode($jsonStr, true);
if (!$config || !isset($config['functions'])) return $m[0];
$list = [];
foreach ($config['functions'] as $f) {
$type = $f['type'] ?? '';
if ($type === 'standard') {
$str = $f['equation'] ?? '';
if (!empty($f['color'])) $str .= ',' . $f['color'];
$list[] = $str;
} elseif ($type === 'text') {
$str = 'text,' . ($f['x'] ?? '') . ',' . ($f['y'] ?? '') . ',' . ($f['content'] ?? '');
if (!empty($f['color'])) $str .= ',' . $f['color'];
$list[] = $str;
} elseif ($type === 'dot') {
$str = 'dot,' . ($f['x'] ?? '') . ',' . ($f['y'] ?? '');
if (!empty($f['style'])) $str .= ',' . $f['style'];
if (!empty($f['color'])) $str .= ',' . $f['color'];
$list[] = $str;
}
}
return "<embed{$before}function_list='" . json_encode($list) . "' script='drawPicture({$jsonStr})'{$after}/>";
},
$html
);
}
function processContent($matches) {
$content = $matches[1];
$processedContent = makepretty($content);
return "`" . $processedContent . "`";
}
function applyLatexConversion($text, $AMT, $wrap = true, $isAnswerMode = false) {
if (is_array($text)) {
foreach ($text as $k => $v) {
$text[$k] = applyLatexConversion($v, $AMT, $wrap, $isAnswerMode);
}
return $text;
}
if (!is_string($text)) return $text;
// Regex: Find anything between backticks and convert it
return preg_replace_callback('/`(.*?)`/s', function($matches) use ($AMT, $wrap, $isAnswerMode) {
$asciimath = $matches[1];
$tex = $AMT->convert($asciimath);
if ($wrap) {
return '<math-field read-only="">' . $tex . '</math-field>';
} else if ($isAnswerMode) {
return '\[' . $tex . '\]';
} else {
return $tex;
}
}, $text);
}
$a2 = new AssessStandalone($DBH);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$rawData = file_get_contents('php://input');
$data = json_decode($rawData, true);
if (!is_array($data)) {
throw new Exception('Received content contained invalid JSON!');
}
$qtype = $data['qtype'];
$control = $data['control'];
$qtext = $data['qtext'];
$solution = $data['solution'];
$seed = isset($data['seed']) ? $data["seed"] : rand(0,10000);
$stype = isset($data["stype"]) ? $data["stype"] : "template";
$convertToLatex = isset($data['convert_to_latex']) ? $data['convert_to_latex'] : false;
$showplot = isset($data["showplot"]) ? $data["showplot"] : "";
if (isset($data['nonce_secret']) && is_string($data['nonce_secret']) && $data['nonce_secret'] !== '') {
$GLOBALS['csv_nonce_secret'] = $data['nonce_secret'];
}
if ($showplot == "fn") {
$control = str_replace("showplot", "showplot_with_functions", $control);
}
$input = '{"email":"u@abc.co","id":"36","uniqueid":"1699501100492899","adddate":"1699501100","lastmoddate":"1699501137","ownerid":"1","author":"Nguyen,Vu","userights":"0","license":"1","description":"Algebra problem","qtype":"multipart","control":"","qcontrol":"","qtext":"","answer":"","solution":"","extref":"","hasimg":"0","deleted":"0","avgtime":"0","ancestors":"","ancestorauthors":"","otherattribution":"","importuid":"","replaceby":"0","broken":"0","solutionopts":"6","sourceinstall":"","meantimen":"1","meantime":"19","vartime":"0","meanscoren":"1","meanscore":"50","varscore":"0","isrand":"1"}';
$qn = 27;
$line = json_decode($input, true);
$line["qtype"] = $qtype;
$line["control"] = $control;
$line["qtext"] = $qtext;
if ($stype == "template") {
$line["solution"] = $solution;
} else {
$line["solution"] = "";
}
$a2->setQuestionData($qn, $line);
$state = array(
'seeds' => array($qn => $seed),
'qsid' => array($qn => $qn),
'stuanswers' => array(),
'stuanswersval' => array(),
'scorenonzero' => array(($qn+1) => -1),
'scoreiscorrect' => array(($qn+1) => -1),
'partattemptn' => array($qn => array()),
'rawscores' => array($qn => array())
);
$a2->setState($state);
$disp = $a2->displayQuestion($qn, [
'showans' => false,
'showallparts' => false,
'printformat' => true
]);
$question = $a2->getQuestion();
$questionContent = $question->getQuestionContent();
if ($showplot === "fn") {
$questionContent = injectFunctionListAttributes($questionContent);
}
if ($stype == "template") {
$originalSolution = $question->getSolutionContent();
} else {
$solutionCode = ($showplot === "fn")
? str_replace("showplot", "showplot_with_functions", $solution)
: $solution;
$vars = $question->getVarsOutput();
$sanitizedVars = [];
foreach ($vars as $key => $value) {
$sanitizedKey = ltrim($key, '$');
$sanitizedVars[$sanitizedKey] = $value;
}
extract($sanitizedVars);
ob_start();
eval($solutionCode);
$originalSolution = ob_get_clean();
}
if ($showplot === "fn") {
$originalSolution = injectFunctionListAttributes($originalSolution);
}
$prettySolution = preg_replace_callback('/`([^`]*)`/', 'processContent', $originalSolution);
$answers = $question->getCorrectAnswersForParts();
if ($showplot === "fn") {
$answers = injectFunctionListAttributes($answers);
}
$vars = $question->getVarsOutput();
$jsparams = $disp["jsparams"];
if ($convertToLatex) {
$AMT = new AMtoTeX;
$questionContent = applyLatexConversion($questionContent, $AMT);
$originalSolution = applyLatexConversion($originalSolution, $AMT);
$prettySolution = applyLatexConversion($prettySolution, $AMT);
$answers = applyLatexConversion($answers, $AMT, false, true);
$vars = applyLatexConversion($vars, $AMT);
$jsparams = applyLatexConversion($jsparams, $AMT);
}
$response = array(
"question" => $questionContent,
"originalSolution" => $originalSolution,
"solution" => $prettySolution,
"seed" => $seed,
"jsparams" => $jsparams,
"vars" => $vars,
"answers" => $answers
);
// Send response
header('Content-Type: application/json');
echo json_encode($response, JSON_PARTIAL_OUTPUT_ON_ERROR);
} else {
header('HTTP/1.0 405 Method Not Allowed');
header('Content-Type: application/json');
echo json_encode(['status' => false, 'message' => 'Method Not Allowed']);
}