Commit | Line | Data |
---|---|---|
50fcb1d8 | 1 | <?php |
2 | ||
3 | // This file is part of Moodle - http://moodle.org/ | |
4 | // | |
5 | // Moodle is free software: you can redistribute it and/or modify | |
6 | // it under the terms of the GNU General Public License as published by | |
7 | // the Free Software Foundation, either version 3 of the License, or | |
8 | // (at your option) any later version. | |
9 | // | |
10 | // Moodle is distributed in the hope that it will be useful, | |
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
13 | // GNU General Public License for more details. | |
14 | // | |
15 | // You should have received a copy of the GNU General Public License | |
16 | // along with Moodle. If not, see <http://www.gnu.org/licenses/>. | |
17 | ||
516cf3eb | 18 | /** |
6b11a0e8 | 19 | * Code for handling and processing questions |
20 | * | |
21 | * This is code that is module independent, i.e., can be used by any module that | |
22 | * uses questions, like quiz, lesson, .. | |
23 | * This script also loads the questiontype classes | |
24 | * Code for handling the editing of questions is in {@link question/editlib.php} | |
25 | * | |
26 | * TODO: separate those functions which form part of the API | |
27 | * from the helper functions. | |
28 | * | |
50fcb1d8 | 29 | * Major Contributors |
30 | * - Alex Smith, Julian Sedding and Gustav Delius {@link http://maths.york.ac.uk/serving_maths} | |
31 | * | |
78bfb562 | 32 | * @package core |
50fcb1d8 | 33 | * @subpackage question |
78bfb562 PS |
34 | * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} |
35 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
6b11a0e8 | 36 | */ |
37 | ||
78bfb562 PS |
38 | defined('MOODLE_INTERNAL') || die(); |
39 | ||
6b11a0e8 | 40 | /// CONSTANTS /////////////////////////////////// |
516cf3eb | 41 | |
e56a08dc | 42 | /**#@+ |
6b11a0e8 | 43 | * The different types of events that can create question states |
44 | */ | |
f30bbcaf | 45 | define('QUESTION_EVENTOPEN', '0'); // The state was created by Moodle |
46 | define('QUESTION_EVENTNAVIGATE', '1'); // The responses were saved because the student navigated to another page (this is not currently used) | |
47 | define('QUESTION_EVENTSAVE', '2'); // The student has requested that the responses should be saved but not submitted or validated | |
48 | define('QUESTION_EVENTGRADE', '3'); // Moodle has graded the responses. A SUBMIT event can be changed to a GRADE event by Moodle. | |
49 | define('QUESTION_EVENTDUPLICATE', '4'); // The responses submitted were the same as previously | |
50 | define('QUESTION_EVENTVALIDATE', '5'); // The student has requested a validation. This causes the responses to be saved as well, but not graded. | |
51 | define('QUESTION_EVENTCLOSEANDGRADE', '6'); // Moodle has graded the responses. A CLOSE event can be changed to a CLOSEANDGRADE event by Moodle. | |
52 | define('QUESTION_EVENTSUBMIT', '7'); // The student response has been submitted but it has not yet been marked | |
53 | define('QUESTION_EVENTCLOSE', '8'); // The response has been submitted and the session has been closed, either because the student requested it or because Moodle did it (e.g. because of a timelimit). The responses have not been graded. | |
bc2feba3 | 54 | define('QUESTION_EVENTMANUALGRADE', '9'); // Grade was entered by teacher |
720be6f2 | 55 | |
56 | define('QUESTION_EVENTS_GRADED', QUESTION_EVENTGRADE.','. | |
57 | QUESTION_EVENTCLOSEANDGRADE.','. | |
58 | QUESTION_EVENTMANUALGRADE); | |
8b92c1e3 | 59 | |
60 | ||
61 | define('QUESTION_EVENTS_CLOSED', QUESTION_EVENTCLOSE.','. | |
62 | QUESTION_EVENTCLOSEANDGRADE.','. | |
63 | QUESTION_EVENTMANUALGRADE); | |
64 | ||
65 | define('QUESTION_EVENTS_CLOSED_OR_GRADED', QUESTION_EVENTGRADE.','. | |
66 | QUESTION_EVENTS_CLOSED); | |
b55797b8 | 67 | |
e56a08dc | 68 | /**#@-*/ |
69 | ||
70 | /**#@+ | |
a2156789 | 71 | * The core question types. |
6b11a0e8 | 72 | */ |
60407982 | 73 | define("SHORTANSWER", "shortanswer"); |
74 | define("TRUEFALSE", "truefalse"); | |
75 | define("MULTICHOICE", "multichoice"); | |
76 | define("RANDOM", "random"); | |
77 | define("MATCH", "match"); | |
78 | define("RANDOMSAMATCH", "randomsamatch"); | |
79 | define("DESCRIPTION", "description"); | |
80 | define("NUMERICAL", "numerical"); | |
81 | define("MULTIANSWER", "multianswer"); | |
82 | define("CALCULATED", "calculated"); | |
60407982 | 83 | define("ESSAY", "essay"); |
e56a08dc | 84 | /**#@-*/ |
85 | ||
6b11a0e8 | 86 | /** |
87 | * Constant determines the number of answer boxes supplied in the editing | |
88 | * form for multiple choice and similar question types. | |
89 | */ | |
4f48fb42 | 90 | define("QUESTION_NUMANS", "10"); |
e56a08dc | 91 | |
271ffe3f | 92 | /** |
93 | * Constant determines the number of answer boxes supplied in the editing | |
94 | * form for multiple choice and similar question types to start with, with | |
95 | * the option of adding QUESTION_NUMANS_ADD more answers. | |
96 | */ | |
97 | define("QUESTION_NUMANS_START", 3); | |
98 | ||
99 | /** | |
100 | * Constant determines the number of answer boxes to add in the editing | |
101 | * form for multiple choice and similar question types when the user presses | |
102 | * 'add form fields button'. | |
103 | */ | |
104 | define("QUESTION_NUMANS_ADD", 3); | |
105 | ||
1b8a7434 | 106 | /** |
107 | * The options used when popping up a question preview window in Javascript. | |
108 | */ | |
8942639b | 109 | define('QUESTION_PREVIEW_POPUP_OPTIONS', 'scrollbars=yes&resizable=yes&width=700&height=540'); |
516cf3eb | 110 | |
6b11a0e8 | 111 | /**#@+ |
112 | * Option flags for ->optionflags | |
113 | * The options are read out via bitwise operation using these constants | |
114 | */ | |
115 | /** | |
116 | * Whether the questions is to be run in adaptive mode. If this is not set then | |
117 | * a question closes immediately after the first submission of responses. This | |
118 | * is how question is Moodle always worked before version 1.5 | |
119 | */ | |
120 | define('QUESTION_ADAPTIVE', 1); | |
62e76c67 | 121 | /**#@-*/ |
6b11a0e8 | 122 | |
62e76c67 | 123 | /**#@+ |
124 | * Options used in forms that move files. | |
3bee1ead | 125 | */ |
126 | define('QUESTION_FILENOTHINGSELECTED', 0); | |
127 | define('QUESTION_FILEDONOTHING', 1); | |
128 | define('QUESTION_FILECOPY', 2); | |
129 | define('QUESTION_FILEMOVE', 3); | |
130 | define('QUESTION_FILEMOVELINKSONLY', 4); | |
62e76c67 | 131 | /**#@-*/ |
3bee1ead | 132 | |
62e76c67 | 133 | /**#@+ |
134 | * Options for whether flags are shown/editable when rendering questions. | |
135 | */ | |
136 | define('QUESTION_FLAGSHIDDEN', 0); | |
137 | define('QUESTION_FLAGSSHOWN', 1); | |
138 | define('QUESTION_FLAGSEDITABLE', 2); | |
6b11a0e8 | 139 | /**#@-*/ |
140 | ||
50fcb1d8 | 141 | /** |
142 | * GLOBAL VARAIBLES | |
143 | * @global array $QTYPES | |
144 | * @name $QTYPES | |
145 | */ | |
f24493ec | 146 | global $QTYPES; |
516cf3eb | 147 | /** |
f24493ec | 148 | * Array holding question type objects. Initialised via calls to |
149 | * question_register_questiontype as the question type classes are included. | |
6b11a0e8 | 150 | */ |
a2156789 | 151 | $QTYPES = array(); |
a2156789 | 152 | |
153 | /** | |
154 | * Add a new question type to the various global arrays above. | |
271ffe3f | 155 | * |
50fcb1d8 | 156 | * @global object |
a2156789 | 157 | * @param object $qtype An instance of the new question type class. |
158 | */ | |
159 | function question_register_questiontype($qtype) { | |
f24493ec | 160 | global $QTYPES; |
271ffe3f | 161 | |
a2156789 | 162 | $name = $qtype->name(); |
163 | $QTYPES[$name] = $qtype; | |
a2156789 | 164 | } |
516cf3eb | 165 | |
643ec47d | 166 | require_once("$CFG->dirroot/question/type/questiontype.php"); |
516cf3eb | 167 | |
a2156789 | 168 | // Load the questiontype.php file for each question type |
271ffe3f | 169 | // These files in turn call question_register_questiontype() |
a2156789 | 170 | // with a new instance of each qtype class. |
17da2e6f | 171 | $qtypenames = get_plugin_list('qtype'); |
172 | foreach($qtypenames as $qtypename => $qdir) { | |
f02c6f01 | 173 | // Instanciates all plug-in question types |
17da2e6f | 174 | $qtypefilepath= "$qdir/questiontype.php"; |
f02c6f01 | 175 | |
176 | // echo "Loading $qtypename<br/>"; // Uncomment for debugging | |
177 | if (is_readable($qtypefilepath)) { | |
178 | require_once($qtypefilepath); | |
516cf3eb | 179 | } |
180 | } | |
181 | ||
e2ae84a2 | 182 | /** |
183 | * An array of question type names translated to the user's language, suitable for use when | |
184 | * creating a drop-down menu of options. | |
185 | * | |
186 | * Long-time Moodle programmers will realise that this replaces the old $QTYPE_MENU array. | |
187 | * The array returned will only hold the names of all the question types that the user should | |
188 | * be able to create directly. Some internal question types like random questions are excluded. | |
b9bd6da4 | 189 | * |
50fcb1d8 | 190 | * @global object |
e2ae84a2 | 191 | * @return array an array of question type names translated to the user's language. |
192 | */ | |
193 | function question_type_menu() { | |
194 | global $QTYPES; | |
7f92f0ad | 195 | static $menuoptions = null; |
196 | if (is_null($menuoptions)) { | |
af52ecee | 197 | $config = get_config('question'); |
7f92f0ad | 198 | $menuoptions = array(); |
e2ae84a2 | 199 | foreach ($QTYPES as $name => $qtype) { |
af52ecee | 200 | // Get the name if this qtype is enabled. |
e2ae84a2 | 201 | $menuname = $qtype->menu_name(); |
af52ecee | 202 | $enabledvar = $name . '_disabled'; |
203 | if ($menuname && !isset($config->$enabledvar)) { | |
7f92f0ad | 204 | $menuoptions[$name] = $menuname; |
e2ae84a2 | 205 | } |
206 | } | |
af52ecee | 207 | |
208 | $menuoptions = question_sort_qtype_array($menuoptions, $config); | |
e2ae84a2 | 209 | } |
7f92f0ad | 210 | return $menuoptions; |
e2ae84a2 | 211 | } |
212 | ||
af52ecee | 213 | /** |
214 | * Sort an array of question type names according to the question type sort order stored in | |
215 | * config_plugins. Entries for which there is no xxx_sortorder defined will go | |
216 | * at the end, sorted according to asort($inarray, SORT_LOCALE_STRING). | |
217 | * @param $inarray an array $qtype => $QTYPES[$qtype]->local_name(). | |
218 | * @param $config get_config('question'), if you happen to have it around, to save one DB query. | |
219 | * @return array the sorted version of $inarray. | |
220 | */ | |
221 | function question_sort_qtype_array($inarray, $config = null) { | |
222 | if (is_null($config)) { | |
223 | $config = get_config('question'); | |
224 | } | |
225 | ||
226 | $sortorder = array(); | |
227 | foreach ($inarray as $name => $notused) { | |
228 | $sortvar = $name . '_sortorder'; | |
229 | if (isset($config->$sortvar)) { | |
230 | $sortorder[$config->$sortvar] = $name; | |
231 | } | |
232 | } | |
233 | ||
234 | ksort($sortorder); | |
235 | $outarray = array(); | |
236 | foreach ($sortorder as $name) { | |
237 | $outarray[$name] = $inarray[$name]; | |
238 | unset($inarray[$name]); | |
239 | } | |
240 | asort($inarray, SORT_LOCALE_STRING); | |
241 | return array_merge($outarray, $inarray); | |
242 | } | |
243 | ||
244 | /** | |
245 | * Move one question type in a list of question types. If you try to move one element | |
246 | * off of the end, nothing will change. | |
117bd748 | 247 | * |
af52ecee | 248 | * @param array $sortedqtypes An array $qtype => anything. |
249 | * @param string $tomove one of the keys from $sortedqtypes | |
250 | * @param integer $direction +1 or -1 | |
251 | * @return array an array $index => $qtype, with $index from 0 to n in order, and | |
252 | * the $qtypes in the same order as $sortedqtypes, except that $tomove will | |
253 | * have been moved one place. | |
254 | */ | |
255 | function question_reorder_qtypes($sortedqtypes, $tomove, $direction) { | |
256 | $neworder = array_keys($sortedqtypes); | |
257 | // Find the element to move. | |
258 | $key = array_search($tomove, $neworder); | |
259 | if ($key === false) { | |
260 | return $neworder; | |
261 | } | |
262 | // Work out the other index. | |
263 | $otherkey = $key + $direction; | |
264 | if (!isset($neworder[$otherkey])) { | |
265 | return $neworder; | |
266 | } | |
267 | // Do the swap. | |
268 | $swap = $neworder[$otherkey]; | |
269 | $neworder[$otherkey] = $neworder[$key]; | |
270 | $neworder[$key] = $swap; | |
271 | return $neworder; | |
272 | } | |
273 | ||
274 | /** | |
275 | * Save a new question type order to the config_plugins table. | |
50fcb1d8 | 276 | * @global object |
af52ecee | 277 | * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order. |
278 | * @param $config get_config('question'), if you happen to have it around, to save one DB query. | |
279 | */ | |
280 | function question_save_qtype_order($neworder, $config = null) { | |
281 | global $DB; | |
282 | ||
283 | if (is_null($config)) { | |
284 | $config = get_config('question'); | |
285 | } | |
286 | ||
287 | foreach ($neworder as $index => $qtype) { | |
288 | $sortvar = $qtype . '_sortorder'; | |
289 | if (!isset($config->$sortvar) || $config->$sortvar != $index + 1) { | |
290 | set_config($sortvar, $index + 1, 'question'); | |
291 | } | |
292 | } | |
293 | } | |
294 | ||
516cf3eb | 295 | /// OTHER CLASSES ///////////////////////////////////////////////////////// |
296 | ||
297 | /** | |
6b11a0e8 | 298 | * This holds the options that are set by the course module |
50fcb1d8 | 299 | * |
300 | * @package moodlecore | |
301 | * @subpackage question | |
302 | * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} | |
303 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
6b11a0e8 | 304 | */ |
516cf3eb | 305 | class cmoptions { |
306 | /** | |
307 | * Whether a new attempt should be based on the previous one. If true | |
308 | * then a new attempt will start in a state where all responses are set | |
309 | * to the last responses from the previous attempt. | |
310 | */ | |
311 | var $attemptonlast = false; | |
312 | ||
313 | /** | |
314 | * Various option flags. The flags are accessed via bitwise operations | |
315 | * using the constants defined in the CONSTANTS section above. | |
316 | */ | |
6b11a0e8 | 317 | var $optionflags = QUESTION_ADAPTIVE; |
516cf3eb | 318 | |
319 | /** | |
320 | * Determines whether in the calculation of the score for a question | |
321 | * penalties for earlier wrong responses within the same attempt will | |
322 | * be subtracted. | |
323 | */ | |
324 | var $penaltyscheme = true; | |
325 | ||
326 | /** | |
327 | * The maximum time the user is allowed to answer the questions withing | |
328 | * an attempt. This is measured in minutes so needs to be multiplied by | |
329 | * 60 before compared to timestamps. If set to 0 no timelimit will be applied | |
330 | */ | |
331 | var $timelimit = 0; | |
332 | ||
333 | /** | |
334 | * Timestamp for the closing time. Responses submitted after this time will | |
335 | * be saved but no credit will be given for them. | |
336 | */ | |
337 | var $timeclose = 9999999999; | |
338 | ||
339 | /** | |
340 | * The id of the course from withing which the question is currently being used | |
341 | */ | |
342 | var $course = SITEID; | |
343 | ||
344 | /** | |
345 | * Whether the answers in a multiple choice question should be randomly | |
346 | * shuffled when a new attempt is started. | |
347 | */ | |
c4c11af8 | 348 | var $shuffleanswers = true; |
516cf3eb | 349 | |
350 | /** | |
351 | * The number of decimals to be shown when scores are printed | |
352 | */ | |
353 | var $decimalpoints = 2; | |
516cf3eb | 354 | } |
355 | ||
356 | ||
516cf3eb | 357 | /// FUNCTIONS ////////////////////////////////////////////////////// |
358 | ||
90c3f310 | 359 | /** |
f67172b6 | 360 | * Returns an array of names of activity modules that use this question |
90c3f310 | 361 | * |
50fcb1d8 | 362 | * @global object |
363 | * @global object | |
f67172b6 | 364 | * @param object $questionid |
365 | * @return array of strings | |
90c3f310 | 366 | */ |
f67172b6 | 367 | function question_list_instances($questionid) { |
eb84a826 | 368 | global $CFG, $DB; |
90c3f310 | 369 | $instances = array(); |
eb84a826 | 370 | $modules = $DB->get_records('modules'); |
90c3f310 | 371 | foreach ($modules as $module) { |
7453df70 | 372 | $fullmod = $CFG->dirroot . '/mod/' . $module->name; |
373 | if (file_exists($fullmod . '/lib.php')) { | |
374 | include_once($fullmod . '/lib.php'); | |
375 | $fn = $module->name.'_question_list_instances'; | |
376 | if (function_exists($fn)) { | |
377 | $instances = $instances + $fn($questionid); | |
378 | } | |
90c3f310 | 379 | } |
380 | } | |
381 | return $instances; | |
382 | } | |
516cf3eb | 383 | |
e2b347e9 | 384 | /** |
385 | * Determine whether there arey any questions belonging to this context, that is whether any of its | |
386 | * question categories contain any questions. This will return true even if all the questions are | |
387 | * hidden. | |
388 | * | |
50fcb1d8 | 389 | * @global object |
e2b347e9 | 390 | * @param mixed $context either a context object, or a context id. |
391 | * @return boolean whether any of the question categories beloning to this context have | |
392 | * any questions in them. | |
393 | */ | |
394 | function question_context_has_any_questions($context) { | |
eb84a826 | 395 | global $DB; |
e2b347e9 | 396 | if (is_object($context)) { |
397 | $contextid = $context->id; | |
398 | } else if (is_numeric($context)) { | |
399 | $contextid = $context; | |
400 | } else { | |
401 | print_error('invalidcontextinhasanyquestions', 'question'); | |
402 | } | |
eb84a826 | 403 | return $DB->record_exists_sql("SELECT * |
404 | FROM {question} q | |
405 | JOIN {question_categories} qc ON qc.id = q.category | |
406 | WHERE qc.contextid = ? AND q.parent = 0", array($contextid)); | |
e2b347e9 | 407 | } |
408 | ||
271ffe3f | 409 | /** |
e9de4366 | 410 | * Returns list of 'allowed' grades for grade selection |
411 | * formatted suitably for dropdown box function | |
412 | * @return object ->gradeoptionsfull full array ->gradeoptions +ve only | |
413 | */ | |
414 | function get_grade_options() { | |
30f09308 | 415 | // define basic array of grades. This list comprises all fractions of the form: |
416 | // a. p/q for q <= 6, 0 <= p <= q | |
417 | // b. p/10 for 0 <= p <= 10 | |
418 | // c. 1/q for 1 <= q <= 10 | |
419 | // d. 1/20 | |
e9de4366 | 420 | $grades = array( |
30f09308 | 421 | 1.0000000, |
422 | 0.9000000, | |
423 | 0.8333333, | |
424 | 0.8000000, | |
425 | 0.7500000, | |
426 | 0.7000000, | |
427 | 0.6666667, | |
428 | 0.6000000, | |
429 | 0.5000000, | |
430 | 0.4000000, | |
431 | 0.3333333, | |
432 | 0.3000000, | |
433 | 0.2500000, | |
434 | 0.2000000, | |
435 | 0.1666667, | |
436 | 0.1428571, | |
437 | 0.1250000, | |
438 | 0.1111111, | |
439 | 0.1000000, | |
440 | 0.0500000, | |
441 | 0.0000000); | |
e9de4366 | 442 | |
443 | // iterate through grades generating full range of options | |
444 | $gradeoptionsfull = array(); | |
445 | $gradeoptions = array(); | |
446 | foreach ($grades as $grade) { | |
447 | $percentage = 100 * $grade; | |
448 | $neggrade = -$grade; | |
449 | $gradeoptions["$grade"] = "$percentage %"; | |
450 | $gradeoptionsfull["$grade"] = "$percentage %"; | |
451 | $gradeoptionsfull["$neggrade"] = -$percentage." %"; | |
452 | } | |
453 | $gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none"); | |
454 | ||
455 | // sort lists | |
456 | arsort($gradeoptions, SORT_NUMERIC); | |
457 | arsort($gradeoptionsfull, SORT_NUMERIC); | |
458 | ||
459 | // construct return object | |
460 | $grades = new stdClass; | |
461 | $grades->gradeoptions = $gradeoptions; | |
462 | $grades->gradeoptionsfull = $gradeoptionsfull; | |
463 | ||
464 | return $grades; | |
465 | } | |
466 | ||
8511669c | 467 | /** |
468 | * match grade options | |
469 | * if no match return error or match nearest | |
470 | * @param array $gradeoptionsfull list of valid options | |
471 | * @param int $grade grade to be tested | |
472 | * @param string $matchgrades 'error' or 'nearest' | |
473 | * @return mixed either 'fixed' value or false if erro | |
474 | */ | |
475 | function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') { | |
476 | // if we just need an error... | |
477 | if ($matchgrades=='error') { | |
478 | foreach($gradeoptionsfull as $value => $option) { | |
2784b982 | 479 | // slightly fuzzy test, never check floats for equality :-) |
480 | if (abs($grade-$value)<0.00001) { | |
8511669c | 481 | return $grade; |
482 | } | |
483 | } | |
484 | // didn't find a match so that's an error | |
485 | return false; | |
486 | } | |
487 | // work out nearest value | |
488 | else if ($matchgrades=='nearest') { | |
489 | $hownear = array(); | |
490 | foreach($gradeoptionsfull as $value => $option) { | |
491 | if ($grade==$value) { | |
492 | return $grade; | |
493 | } | |
494 | $hownear[ $value ] = abs( $grade - $value ); | |
495 | } | |
496 | // reverse sort list of deltas and grab the last (smallest) | |
497 | asort( $hownear, SORT_NUMERIC ); | |
498 | reset( $hownear ); | |
499 | return key( $hownear ); | |
500 | } | |
501 | else { | |
502 | return false; | |
271ffe3f | 503 | } |
8511669c | 504 | } |
505 | ||
f67172b6 | 506 | /** |
507 | * Tests whether a category is in use by any activity module | |
508 | * | |
50fcb1d8 | 509 | * @global object |
f67172b6 | 510 | * @return boolean |
271ffe3f | 511 | * @param integer $categoryid |
f67172b6 | 512 | * @param boolean $recursive Whether to examine category children recursively |
513 | */ | |
514 | function question_category_isused($categoryid, $recursive = false) { | |
eb84a826 | 515 | global $DB; |
f67172b6 | 516 | |
517 | //Look at each question in the category | |
d11de005 | 518 | if ($questions = $DB->get_records('question', array('category'=>$categoryid), '', 'id,qtype')) { |
f67172b6 | 519 | foreach ($questions as $question) { |
520 | if (count(question_list_instances($question->id))) { | |
521 | return true; | |
522 | } | |
523 | } | |
524 | } | |
525 | ||
526 | //Look under child categories recursively | |
527 | if ($recursive) { | |
eb84a826 | 528 | if ($children = $DB->get_records('question_categories', array('parent'=>$categoryid))) { |
f67172b6 | 529 | foreach ($children as $child) { |
530 | if (question_category_isused($child->id, $recursive)) { | |
531 | return true; | |
532 | } | |
533 | } | |
534 | } | |
535 | } | |
536 | ||
537 | return false; | |
538 | } | |
539 | ||
0429cd86 | 540 | /** |
541 | * Deletes all data associated to an attempt from the database | |
542 | * | |
50fcb1d8 | 543 | * @global object |
544 | * @global object | |
93eb0ea3 | 545 | * @param integer $attemptid The id of the attempt being deleted |
0429cd86 | 546 | */ |
547 | function delete_attempt($attemptid) { | |
eb84a826 | 548 | global $QTYPES, $DB; |
0429cd86 | 549 | |
eb84a826 | 550 | $states = $DB->get_records('question_states', array('attempt'=>$attemptid)); |
9523cbfc | 551 | if ($states) { |
552 | $stateslist = implode(',', array_keys($states)); | |
3bee1ead | 553 | |
9523cbfc | 554 | // delete question-type specific data |
555 | foreach ($QTYPES as $qtype) { | |
556 | $qtype->delete_states($stateslist); | |
557 | } | |
0429cd86 | 558 | } |
559 | ||
560 | // delete entries from all other question tables | |
561 | // It is important that this is done only after calling the questiontype functions | |
eb84a826 | 562 | $DB->delete_records("question_states", array("attempt"=>$attemptid)); |
563 | $DB->delete_records("question_sessions", array("attemptid"=>$attemptid)); | |
564 | $DB->delete_records("question_attempts", array("id"=>$attemptid)); | |
0429cd86 | 565 | } |
f67172b6 | 566 | |
516cf3eb | 567 | /** |
6b11a0e8 | 568 | * Deletes question and all associated data from the database |
569 | * | |
90c3f310 | 570 | * It will not delete a question if it is used by an activity module |
50fcb1d8 | 571 | * |
572 | * @global object | |
573 | * @global object | |
6b11a0e8 | 574 | * @param object $question The question being deleted |
575 | */ | |
90c3f310 | 576 | function delete_question($questionid) { |
eb84a826 | 577 | global $QTYPES, $DB; |
271ffe3f | 578 | |
3c573960 | 579 | if (!$question = $DB->get_record('question', array('id'=>$questionid))) { |
580 | // In some situations, for example if this was a child of a | |
581 | // Cloze question that was previously deleted, the question may already | |
582 | // have gone. In this case, just do nothing. | |
583 | return; | |
584 | } | |
585 | ||
90c3f310 | 586 | // Do not delete a question if it is used by an activity module |
f67172b6 | 587 | if (count(question_list_instances($questionid))) { |
90c3f310 | 588 | return; |
589 | } | |
590 | ||
591 | // delete questiontype-specific data | |
3bee1ead | 592 | question_require_capability_on($question, 'edit'); |
593 | if ($question) { | |
cf60a28a | 594 | if (isset($QTYPES[$question->qtype])) { |
595 | $QTYPES[$question->qtype]->delete_question($questionid); | |
596 | } | |
597 | } else { | |
598 | echo "Question with id $questionid does not exist.<br />"; | |
516cf3eb | 599 | } |
90c3f310 | 600 | |
eb84a826 | 601 | if ($states = $DB->get_records('question_states', array('question'=>$questionid))) { |
5cb9076a | 602 | $stateslist = implode(',', array_keys($states)); |
271ffe3f | 603 | |
5cb9076a | 604 | // delete questiontype-specific data |
605 | foreach ($QTYPES as $qtype) { | |
606 | $qtype->delete_states($stateslist); | |
607 | } | |
0429cd86 | 608 | } |
609 | ||
90c3f310 | 610 | // delete entries from all other question tables |
611 | // It is important that this is done only after calling the questiontype functions | |
eb84a826 | 612 | $DB->delete_records("question_answers", array("question"=>$questionid)); |
613 | $DB->delete_records("question_states", array("question"=>$questionid)); | |
614 | $DB->delete_records("question_sessions", array("questionid"=>$questionid)); | |
90c3f310 | 615 | |
616 | // Now recursively delete all child questions | |
d11de005 | 617 | if ($children = $DB->get_records('question', array('parent' => $questionid), '', 'id,qtype')) { |
516cf3eb | 618 | foreach ($children as $child) { |
1d723a16 | 619 | if ($child->id != $questionid) { |
620 | delete_question($child->id); | |
621 | } | |
516cf3eb | 622 | } |
623 | } | |
271ffe3f | 624 | |
90c3f310 | 625 | // Finally delete the question record itself |
eb84a826 | 626 | $DB->delete_records('question', array('id'=>$questionid)); |
90c3f310 | 627 | |
628 | return; | |
516cf3eb | 629 | } |
630 | ||
f67172b6 | 631 | /** |
3bee1ead | 632 | * All question categories and their questions are deleted for this course. |
f67172b6 | 633 | * |
50fcb1d8 | 634 | * @global object |
3bee1ead | 635 | * @param object $mod an object representing the activity |
f67172b6 | 636 | * @param boolean $feedback to specify if the process must output a summary of its work |
637 | * @return boolean | |
638 | */ | |
639 | function question_delete_course($course, $feedback=true) { | |
642816a6 | 640 | global $DB, $OUTPUT; |
eb84a826 | 641 | |
f67172b6 | 642 | //To store feedback to be showed at the end of the process |
643 | $feedbackdata = array(); | |
644 | ||
645 | //Cache some strings | |
f67172b6 | 646 | $strcatdeleted = get_string('unusedcategorydeleted', 'quiz'); |
3bee1ead | 647 | $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); |
eb84a826 | 648 | $categoriescourse = $DB->get_records('question_categories', array('contextid'=>$coursecontext->id), 'parent', 'id, parent, name'); |
f67172b6 | 649 | |
3bee1ead | 650 | if ($categoriescourse) { |
f67172b6 | 651 | |
652 | //Sort categories following their tree (parent-child) relationships | |
3bee1ead | 653 | //this will make the feedback more readable |
654 | $categoriescourse = sort_categories_by_tree($categoriescourse); | |
655 | ||
656 | foreach ($categoriescourse as $category) { | |
657 | ||
658 | //Delete it completely (questions and category itself) | |
659 | //deleting questions | |
d11de005 | 660 | if ($questions = $DB->get_records('question', array('category' => $category->id), '', 'id,qtype')) { |
3bee1ead | 661 | foreach ($questions as $question) { |
662 | delete_question($question->id); | |
f67172b6 | 663 | } |
eb84a826 | 664 | $DB->delete_records("question", array("category"=>$category->id)); |
3bee1ead | 665 | } |
666 | //delete the category | |
eb84a826 | 667 | $DB->delete_records('question_categories', array('id'=>$category->id)); |
f67172b6 | 668 | |
3bee1ead | 669 | //Fill feedback |
670 | $feedbackdata[] = array($category->name, $strcatdeleted); | |
671 | } | |
672 | //Inform about changes performed if feedback is enabled | |
673 | if ($feedback) { | |
642816a6 | 674 | $table = new html_table(); |
3bee1ead | 675 | $table->head = array(get_string('category','quiz'), get_string('action')); |
676 | $table->data = $feedbackdata; | |
16be8974 | 677 | echo html_writer::table($table); |
3bee1ead | 678 | } |
679 | } | |
680 | return true; | |
681 | } | |
f67172b6 | 682 | |
e2b347e9 | 683 | /** |
684 | * Category is about to be deleted, | |
685 | * 1/ All question categories and their questions are deleted for this course category. | |
686 | * 2/ All questions are moved to new category | |
687 | * | |
50fcb1d8 | 688 | * @global object |
e2b347e9 | 689 | * @param object $category course category object |
690 | * @param object $newcategory empty means everything deleted, otherwise id of category where content moved | |
691 | * @param boolean $feedback to specify if the process must output a summary of its work | |
692 | * @return boolean | |
693 | */ | |
694 | function question_delete_course_category($category, $newcategory, $feedback=true) { | |
aa9a6867 | 695 | global $DB, $OUTPUT; |
534792cd | 696 | |
e2b347e9 | 697 | $context = get_context_instance(CONTEXT_COURSECAT, $category->id); |
698 | if (empty($newcategory)) { | |
699 | $feedbackdata = array(); // To store feedback to be showed at the end of the process | |
700 | $rescueqcategory = null; // See the code around the call to question_save_from_deletion. | |
701 | $strcatdeleted = get_string('unusedcategorydeleted', 'quiz'); | |
702 | ||
703 | // Loop over question categories. | |
eb84a826 | 704 | if ($categories = $DB->get_records('question_categories', array('contextid'=>$context->id), 'parent', 'id, parent, name')) { |
e2b347e9 | 705 | foreach ($categories as $category) { |
b9bd6da4 | 706 | |
e2b347e9 | 707 | // Deal with any questions in the category. |
d11de005 | 708 | if ($questions = $DB->get_records('question', array('category' => $category->id), '', 'id,qtype')) { |
e2b347e9 | 709 | |
710 | // Try to delete each question. | |
711 | foreach ($questions as $question) { | |
712 | delete_question($question->id); | |
713 | } | |
714 | ||
715 | // Check to see if there were any questions that were kept because they are | |
716 | // still in use somehow, even though quizzes in courses in this category will | |
717 | // already have been deteted. This could happen, for example, if questions are | |
718 | // added to a course, and then that course is moved to another category (MDL-14802). | |
534792cd | 719 | $questionids = $DB->get_records_menu('question', array('category'=>$category->id), '', 'id,1'); |
e2b347e9 | 720 | if (!empty($questionids)) { |
721 | if (!$rescueqcategory = question_save_from_deletion(implode(',', array_keys($questionids)), | |
722 | get_parent_contextid($context), print_context_name($context), $rescueqcategory)) { | |
723 | return false; | |
724 | } | |
725 | $feedbackdata[] = array($category->name, get_string('questionsmovedto', 'question', $rescueqcategory->name)); | |
726 | } | |
727 | } | |
728 | ||
729 | // Now delete the category. | |
eb84a826 | 730 | if (!$DB->delete_records('question_categories', array('id'=>$category->id))) { |
e2b347e9 | 731 | return false; |
732 | } | |
733 | $feedbackdata[] = array($category->name, $strcatdeleted); | |
734 | ||
735 | } // End loop over categories. | |
736 | } | |
737 | ||
738 | // Output feedback if requested. | |
739 | if ($feedback and $feedbackdata) { | |
642816a6 | 740 | $table = new html_table(); |
e2b347e9 | 741 | $table->head = array(get_string('questioncategory','question'), get_string('action')); |
742 | $table->data = $feedbackdata; | |
16be8974 | 743 | echo html_writer::table($table); |
e2b347e9 | 744 | } |
745 | ||
746 | } else { | |
747 | // Move question categories ot the new context. | |
748 | if (!$newcontext = get_context_instance(CONTEXT_COURSECAT, $newcategory->id)) { | |
749 | return false; | |
750 | } | |
eb84a826 | 751 | if (!$DB->set_field('question_categories', 'contextid', $newcontext->id, array('contextid'=>$context->id))) { |
e2b347e9 | 752 | return false; |
753 | } | |
754 | if ($feedback) { | |
755 | $a = new stdClass; | |
756 | $a->oldplace = print_context_name($context); | |
757 | $a->newplace = print_context_name($newcontext); | |
aa9a6867 | 758 | echo $OUTPUT->notification(get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess'); |
e2b347e9 | 759 | } |
760 | } | |
761 | ||
762 | return true; | |
763 | } | |
764 | ||
765 | /** | |
766 | * Enter description here... | |
767 | * | |
50fcb1d8 | 768 | * @global object |
e2b347e9 | 769 | * @param string $questionids list of questionids |
770 | * @param object $newcontext the context to create the saved category in. | |
b9bd6da4 | 771 | * @param string $oldplace a textual description of the think being deleted, e.g. from get_context_name |
e2b347e9 | 772 | * @param object $newcategory |
b9bd6da4 | 773 | * @return mixed false on |
e2b347e9 | 774 | */ |
775 | function question_save_from_deletion($questionids, $newcontextid, $oldplace, $newcategory = null) { | |
eb84a826 | 776 | global $DB; |
777 | ||
e2b347e9 | 778 | // Make a category in the parent context to move the questions to. |
779 | if (is_null($newcategory)) { | |
780 | $newcategory = new object(); | |
781 | $newcategory->parent = 0; | |
782 | $newcategory->contextid = $newcontextid; | |
eb84a826 | 783 | $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace); |
784 | $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace); | |
e2b347e9 | 785 | $newcategory->sortorder = 999; |
786 | $newcategory->stamp = make_unique_id_code(); | |
a8f3a651 | 787 | $newcategory->id = $DB->insert_record('question_categories', $newcategory); |
e2b347e9 | 788 | } |
789 | ||
790 | // Move any remaining questions to the 'saved' category. | |
791 | if (!question_move_questions_to_category($questionids, $newcategory->id)) { | |
792 | return false; | |
793 | } | |
794 | return $newcategory; | |
795 | } | |
796 | ||
3bee1ead | 797 | /** |
798 | * All question categories and their questions are deleted for this activity. | |
799 | * | |
50fcb1d8 | 800 | * @global object |
3bee1ead | 801 | * @param object $cm the course module object representing the activity |
802 | * @param boolean $feedback to specify if the process must output a summary of its work | |
803 | * @return boolean | |
804 | */ | |
805 | function question_delete_activity($cm, $feedback=true) { | |
642816a6 | 806 | global $DB, $OUTPUT; |
eb84a826 | 807 | |
3bee1ead | 808 | //To store feedback to be showed at the end of the process |
809 | $feedbackdata = array(); | |
f67172b6 | 810 | |
3bee1ead | 811 | //Cache some strings |
812 | $strcatdeleted = get_string('unusedcategorydeleted', 'quiz'); | |
813 | $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id); | |
eb84a826 | 814 | if ($categoriesmods = $DB->get_records('question_categories', array('contextid'=>$modcontext->id), 'parent', 'id, parent, name')){ |
3bee1ead | 815 | //Sort categories following their tree (parent-child) relationships |
816 | //this will make the feedback more readable | |
817 | $categoriesmods = sort_categories_by_tree($categoriesmods); | |
f67172b6 | 818 | |
3bee1ead | 819 | foreach ($categoriesmods as $category) { |
f67172b6 | 820 | |
3bee1ead | 821 | //Delete it completely (questions and category itself) |
822 | //deleting questions | |
d11de005 | 823 | if ($questions = $DB->get_records('question', array('category' => $category->id), '', 'id,qtype')) { |
3bee1ead | 824 | foreach ($questions as $question) { |
825 | delete_question($question->id); | |
826 | } | |
eb84a826 | 827 | $DB->delete_records("question", array("category"=>$category->id)); |
f67172b6 | 828 | } |
3bee1ead | 829 | //delete the category |
eb84a826 | 830 | $DB->delete_records('question_categories', array('id'=>$category->id)); |
3bee1ead | 831 | |
832 | //Fill feedback | |
833 | $feedbackdata[] = array($category->name, $strcatdeleted); | |
f67172b6 | 834 | } |
835 | //Inform about changes performed if feedback is enabled | |
836 | if ($feedback) { | |
642816a6 | 837 | $table = new html_table(); |
f67172b6 | 838 | $table->head = array(get_string('category','quiz'), get_string('action')); |
839 | $table->data = $feedbackdata; | |
16be8974 | 840 | echo html_writer::table($table); |
f67172b6 | 841 | } |
842 | } | |
843 | return true; | |
844 | } | |
7fb1b88d | 845 | |
846 | /** | |
847 | * This function should be considered private to the question bank, it is called from | |
848 | * question/editlib.php question/contextmoveq.php and a few similar places to to the work of | |
849 | * acutally moving questions and associated data. However, callers of this function also have to | |
850 | * do other work, which is why you should not call this method directly from outside the questionbank. | |
851 | * | |
50fcb1d8 | 852 | * @global object |
7fb1b88d | 853 | * @param string $questionids a comma-separated list of question ids. |
854 | * @param integer $newcategory the id of the category to move to. | |
855 | */ | |
856 | function question_move_questions_to_category($questionids, $newcategory) { | |
1c69b885 | 857 | global $DB; |
858 | ||
7fb1b88d | 859 | $result = true; |
860 | ||
861 | // Move the questions themselves. | |
1c69b885 | 862 | $result = $result && $DB->set_field_select('question', 'category', $newcategory, "id IN ($questionids)"); |
7fb1b88d | 863 | |
864 | // Move any subquestions belonging to them. | |
1c69b885 | 865 | $result = $result && $DB->set_field_select('question', 'category', $newcategory, "parent IN ($questionids)"); |
7fb1b88d | 866 | |
867 | // TODO Deal with datasets. | |
868 | ||
869 | return $result; | |
870 | } | |
871 | ||
5a2a5331 | 872 | /** |
78e7a3dd | 873 | * Given a list of ids, load the basic information about a set of questions from the questions table. |
874 | * The $join and $extrafields arguments can be used together to pull in extra data. | |
875 | * See, for example, the usage in mod/quiz/attemptlib.php, and | |
876 | * read the code below to see how the SQL is assembled. Throws exceptions on error. | |
5a2a5331 | 877 | * |
50fcb1d8 | 878 | * @global object |
879 | * @global object | |
78e7a3dd | 880 | * @param array $questionids array of question ids. |
881 | * @param string $extrafields extra SQL code to be added to the query. | |
882 | * @param string $join extra SQL code to be added to the query. | |
883 | * @param array $extraparams values for any placeholders in $join. | |
884 | * You are strongly recommended to use named placeholder. | |
5a2a5331 | 885 | * |
78e7a3dd | 886 | * @return array partially complete question objects. You need to call get_question_options |
887 | * on them before they can be properly used. | |
5a2a5331 | 888 | */ |
78e7a3dd | 889 | function question_preload_questions($questionids, $extrafields = '', $join = '', $extraparams = array()) { |
eb84a826 | 890 | global $CFG, $DB; |
4089d9ec | 891 | if (empty($questionids)) { |
892 | return array(); | |
893 | } | |
5a2a5331 | 894 | if ($join) { |
78e7a3dd | 895 | $join = ' JOIN '.$join; |
5a2a5331 | 896 | } |
897 | if ($extrafields) { | |
898 | $extrafields = ', ' . $extrafields; | |
899 | } | |
78e7a3dd | 900 | list($questionidcondition, $params) = $DB->get_in_or_equal( |
901 | $questionids, SQL_PARAMS_NAMED, 'qid0000'); | |
eb84a826 | 902 | $sql = 'SELECT q.*' . $extrafields . ' FROM {question} q' . $join . |
78e7a3dd | 903 | ' WHERE q.id ' . $questionidcondition; |
5a2a5331 | 904 | |
905 | // Load the questions | |
78e7a3dd | 906 | if (!$questions = $DB->get_records_sql($sql, $extraparams + $params)) { |
5a2a5331 | 907 | return 'Could not load questions.'; |
908 | } | |
909 | ||
78e7a3dd | 910 | foreach ($questions as $question) { |
911 | $question->_partiallyloaded = true; | |
912 | } | |
913 | ||
b55797b8 | 914 | // Note, a possible optimisation here would be to not load the TEXT fields |
915 | // (that is, questiontext and generalfeedback) here, and instead load them in | |
916 | // question_load_questions. That would add one DB query, but reduce the amount | |
917 | // of data transferred most of the time. I am not going to do this optimisation | |
918 | // until it is shown to be worthwhile. | |
919 | ||
78e7a3dd | 920 | return $questions; |
921 | } | |
922 | ||
923 | /** | |
924 | * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used | |
925 | * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and | |
926 | * read the code below to see how the SQL is assembled. Throws exceptions on error. | |
927 | * | |
928 | * @param array $questionids array of question ids. | |
929 | * @param string $extrafields extra SQL code to be added to the query. | |
930 | * @param string $join extra SQL code to be added to the query. | |
931 | * @param array $extraparams values for any placeholders in $join. | |
932 | * You are strongly recommended to use named placeholder. | |
933 | * | |
934 | * @return array question objects. | |
935 | */ | |
936 | function question_load_questions($questionids, $extrafields = '', $join = '') { | |
937 | $questions = question_preload_questions($questionids, $extrafields, $join); | |
938 | ||
5a2a5331 | 939 | // Load the question type specific information |
940 | if (!get_question_options($questions)) { | |
941 | return 'Could not load the question options'; | |
942 | } | |
943 | ||
944 | return $questions; | |
945 | } | |
946 | ||
516cf3eb | 947 | /** |
d7444d44 | 948 | * Private function to factor common code out of get_question_options(). |
271ffe3f | 949 | * |
50fcb1d8 | 950 | * @global object |
951 | * @global object | |
d7444d44 | 952 | * @param object $question the question to tidy. |
c599a682 | 953 | * @param boolean $loadtags load the question tags from the tags table. Optional, default false. |
271ffe3f | 954 | * @return boolean true if successful, else false. |
d7444d44 | 955 | */ |
c599a682 | 956 | function _tidy_question(&$question, $loadtags = false) { |
957 | global $CFG, $QTYPES; | |
d7444d44 | 958 | if (!array_key_exists($question->qtype, $QTYPES)) { |
959 | $question->qtype = 'missingtype'; | |
960 | $question->questiontext = '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext; | |
961 | } | |
962 | $question->name_prefix = question_make_name_prefix($question->id); | |
78e7a3dd | 963 | if ($success = $QTYPES[$question->qtype]->get_question_options($question)) { |
964 | if (isset($question->_partiallyloaded)) { | |
965 | unset($question->_partiallyloaded); | |
966 | } | |
967 | } | |
c599a682 | 968 | if ($loadtags && !empty($CFG->usetags)) { |
969 | require_once($CFG->dirroot . '/tag/lib.php'); | |
970 | $question->tags = tag_get_tags_array('question', $question->id); | |
971 | } | |
78e7a3dd | 972 | return $success; |
d7444d44 | 973 | } |
516cf3eb | 974 | |
d7444d44 | 975 | /** |
976 | * Updates the question objects with question type specific | |
977 | * information by calling {@link get_question_options()} | |
978 | * | |
979 | * Can be called either with an array of question objects or with a single | |
980 | * question object. | |
271ffe3f | 981 | * |
d7444d44 | 982 | * @param mixed $questions Either an array of question objects to be updated |
983 | * or just a single question object | |
c599a682 | 984 | * @param boolean $loadtags load the question tags from the tags table. Optional, default false. |
d7444d44 | 985 | * @return bool Indicates success or failure. |
986 | */ | |
c599a682 | 987 | function get_question_options(&$questions, $loadtags = false) { |
516cf3eb | 988 | if (is_array($questions)) { // deal with an array of questions |
d7444d44 | 989 | foreach ($questions as $i => $notused) { |
c599a682 | 990 | if (!_tidy_question($questions[$i], $loadtags)) { |
516cf3eb | 991 | return false; |
d7444d44 | 992 | } |
516cf3eb | 993 | } |
994 | return true; | |
995 | } else { // deal with single question | |
c599a682 | 996 | return _tidy_question($questions, $loadtags); |
516cf3eb | 997 | } |
998 | } | |
999 | ||
1000 | /** | |
117bd748 | 1001 | * Load the basic state information for |
81d833ad | 1002 | * |
50fcb1d8 | 1003 | * @global object |
81d833ad | 1004 | * @param integer $attemptid the attempt id to load the states for. |
1005 | * @return array an array of state data from the database, you will subsequently | |
1006 | * need to call question_load_states to get fully loaded states that can be | |
117bd748 | 1007 | * used by the question types. The states here should be sufficient for |
81d833ad | 1008 | * basic tasks like rendering navigation. |
1009 | */ | |
1010 | function question_preload_states($attemptid) { | |
1011 | global $DB; | |
766df8f7 | 1012 | // Note, changes here probably also need to be reflected in |
1013 | // regrade_question_in_attempt and question_load_specific_state. | |
516cf3eb | 1014 | |
81d833ad | 1015 | // The questionid field must be listed first so that it is used as the |
eb84a826 | 1016 | // array index in the array returned by $DB->get_records_sql |
59be14de TH |
1017 | $statefields = 'n.questionid as question, s.id, s.attempt, ' . |
1018 | 's.seq_number, s.answer, s.timestamp, s.event, s.grade, s.raw_grade, ' . | |
1019 | 's.penalty, n.sumpenalty, n.manualcomment, n.flagged, n.id as questionsessionid'; | |
81d833ad | 1020 | |
516cf3eb | 1021 | // Load the newest states for the questions |
eb84a826 | 1022 | $sql = "SELECT $statefields |
1023 | FROM {question_states} s, {question_sessions} n | |
81d833ad | 1024 | WHERE s.id = n.newest AND n.attemptid = ?"; |
1025 | $states = $DB->get_records_sql($sql, array($attemptid)); | |
1026 | if (!$states) { | |
1027 | return false; | |
1028 | } | |
516cf3eb | 1029 | |
1030 | // Load the newest graded states for the questions | |
eb84a826 | 1031 | $sql = "SELECT $statefields |
1032 | FROM {question_states} s, {question_sessions} n | |
81d833ad | 1033 | WHERE s.id = n.newgraded AND n.attemptid = ?"; |
1034 | $gradedstates = $DB->get_records_sql($sql, array($attemptid)); | |
1035 | ||
1036 | // Hook the two together. | |
1037 | foreach ($states as $questionid => $state) { | |
1038 | $states[$questionid]->_partiallyloaded = true; | |
1039 | if ($gradedstates[$questionid]) { | |
81d833ad | 1040 | $states[$questionid]->last_graded = $gradedstates[$questionid]; |
40d1feeb | 1041 | $states[$questionid]->last_graded->_partiallyloaded = true; |
81d833ad | 1042 | } |
1043 | } | |
1044 | ||
1045 | return $states; | |
1046 | } | |
1047 | ||
1048 | /** | |
1049 | * Finish loading the question states that were extracted from the database with | |
1050 | * question_preload_states, creating new states for any question where there | |
1051 | * is not a state in the database. | |
1052 | * | |
50fcb1d8 | 1053 | * @global object |
1054 | * @global object | |
81d833ad | 1055 | * @param array $questions the questions to load state for. |
40d1feeb | 1056 | * @param array $states the partially loaded states this array is updated. |
81d833ad | 1057 | * @param object $cmoptions options from the module we are loading the states for. E.g. $quiz. |
1058 | * @param object $attempt The attempt for which the question sessions are | |
1059 | * to be restored or created. | |
1060 | * @param mixed either the id of a previous attempt, if this attmpt is | |
1061 | * building on a previous one, or false for a clean attempt. | |
40d1feeb | 1062 | * @return true or false for success or failure. |
81d833ad | 1063 | */ |
1064 | function question_load_states(&$questions, &$states, $cmoptions, $attempt, $lastattemptid = false) { | |
1065 | global $QTYPES, $DB; | |
516cf3eb | 1066 | |
1067 | // loop through all questions and set the last_graded states | |
81d833ad | 1068 | foreach (array_keys($questions) as $qid) { |
1069 | if (isset($states[$qid])) { | |
1070 | restore_question_state($questions[$qid], $states[$qid]); | |
1071 | if (isset($states[$qid]->_partiallyloaded)) { | |
1072 | unset($states[$qid]->_partiallyloaded); | |
1073 | } | |
40d1feeb | 1074 | if (isset($states[$qid]->last_graded)) { |
1075 | restore_question_state($questions[$qid], $states[$qid]->last_graded); | |
1076 | if (isset($states[$qid]->last_graded->_partiallyloaded)) { | |
1077 | unset($states[$qid]->last_graded->_partiallyloaded); | |
1078 | } | |
1079 | } else { | |
1080 | $states[$qid]->last_graded = clone($states[$qid]); | |
516cf3eb | 1081 | } |
1082 | } else { | |
fb708c11 | 1083 | if ($lastattemptid) { |
47ceac47 | 1084 | // If the new attempt is to be based on this previous attempt. |
1085 | // Find the responses from the previous attempt and save them to the new session | |
fb708c11 | 1086 | |
59be14de TH |
1087 | // Load the last graded state for the question. Note, $statefields is |
1088 | // the same as above, except that we don't want n.manualcomment. | |
1089 | $statefields = 'n.questionid as question, s.id, s.attempt, ' . | |
1090 | 's.seq_number, s.answer, s.timestamp, s.event, s.grade, s.raw_grade, ' . | |
1091 | 's.penalty, n.sumpenalty'; | |
eb84a826 | 1092 | $sql = "SELECT $statefields |
1093 | FROM {question_states} s, {question_sessions} n | |
0b8506ec | 1094 | WHERE s.id = n.newest |
eb84a826 | 1095 | AND n.attemptid = ? |
1096 | AND n.questionid = ?"; | |
81d833ad | 1097 | if (!$laststate = $DB->get_record_sql($sql, array($lastattemptid, $qid))) { |
fb708c11 | 1098 | // Only restore previous responses that have been graded |
1099 | continue; | |
1100 | } | |
1101 | // Restore the state so that the responses will be restored | |
81d833ad | 1102 | restore_question_state($questions[$qid], $laststate); |
1103 | $states[$qid] = clone($laststate); | |
1104 | unset($states[$qid]->id); | |
fb708c11 | 1105 | } else { |
d402153a | 1106 | // create a new empty state |
81d833ad | 1107 | $states[$qid] = new object; |
1108 | $states[$qid]->question = $qid; | |
1109 | $states[$qid]->responses = array('' => ''); | |
1110 | $states[$qid]->raw_grade = 0; | |
fb708c11 | 1111 | } |
1112 | ||
1113 | // now fill/overide initial values | |
81d833ad | 1114 | $states[$qid]->attempt = $attempt->uniqueid; |
1115 | $states[$qid]->seq_number = 0; | |
1116 | $states[$qid]->timestamp = $attempt->timestart; | |
1117 | $states[$qid]->event = ($attempt->timefinish) ? QUESTION_EVENTCLOSE : QUESTION_EVENTOPEN; | |
1118 | $states[$qid]->grade = 0; | |
1119 | $states[$qid]->penalty = 0; | |
1120 | $states[$qid]->sumpenalty = 0; | |
1121 | $states[$qid]->manualcomment = ''; | |
1122 | $states[$qid]->flagged = 0; | |
fb708c11 | 1123 | |
d23e3e11 | 1124 | // Prevent further changes to the session from incrementing the |
1125 | // sequence number | |
81d833ad | 1126 | $states[$qid]->changed = true; |
d23e3e11 | 1127 | |
fb708c11 | 1128 | if ($lastattemptid) { |
1129 | // prepare the previous responses for new processing | |
1130 | $action = new stdClass; | |
1131 | $action->responses = $laststate->responses; | |
1132 | $action->timestamp = $laststate->timestamp; | |
1133 | $action->event = QUESTION_EVENTSAVE; //emulate save of questions from all pages MDL-7631 | |
1134 | ||
1135 | // Process these responses ... | |
81d833ad | 1136 | question_process_responses($questions[$qid], $states[$qid], $action, $cmoptions, $attempt); |
fb708c11 | 1137 | |
1138 | // Fix for Bug #5506: When each attempt is built on the last one, | |
3bee1ead | 1139 | // preserve the options from any previous attempt. |
fb708c11 | 1140 | if ( isset($laststate->options) ) { |
81d833ad | 1141 | $states[$qid]->options = $laststate->options; |
fb708c11 | 1142 | } |
1143 | } else { | |
1144 | // Create the empty question type specific information | |
81d833ad | 1145 | if (!$QTYPES[$questions[$qid]->qtype]->create_session_and_responses( |
1146 | $questions[$qid], $states[$qid], $cmoptions, $attempt)) { | |
fb708c11 | 1147 | return false; |
1148 | } | |
516cf3eb | 1149 | } |
81d833ad | 1150 | $states[$qid]->last_graded = clone($states[$qid]); |
516cf3eb | 1151 | } |
1152 | } | |
40d1feeb | 1153 | return true; |
516cf3eb | 1154 | } |
1155 | ||
81d833ad | 1156 | /** |
1157 | * Loads the most recent state of each question session from the database | |
1158 | * or create new one. | |
1159 | * | |
1160 | * For each question the most recent session state for the current attempt | |
1161 | * is loaded from the question_states table and the question type specific data and | |
1162 | * responses are added by calling {@link restore_question_state()} which in turn | |
1163 | * calls {@link restore_session_and_responses()} for each question. | |
1164 | * If no states exist for the question instance an empty state object is | |
1165 | * created representing the start of a session and empty question | |
1166 | * type specific information and responses are created by calling | |
1167 | * {@link create_session_and_responses()}. | |
1168 | * | |
1169 | * @return array An array of state objects representing the most recent | |
1170 | * states of the question sessions. | |
1171 | * @param array $questions The questions for which sessions are to be restored or | |
1172 | * created. | |
1173 | * @param object $cmoptions | |
1174 | * @param object $attempt The attempt for which the question sessions are | |
1175 | * to be restored or created. | |
1176 | * @param mixed either the id of a previous attempt, if this attmpt is | |
1177 | * building on a previous one, or false for a clean attempt. | |
1178 | */ | |
1179 | function get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) { | |
81d833ad | 1180 | // Preload the states. |
1181 | $states = question_preload_states($attempt->uniqueid); | |
1182 | if (!$states) { | |
1183 | $states = array(); | |
1184 | } | |
1185 | ||
1186 | // Then finish the job. | |
40d1feeb | 1187 | if (!question_load_states($questions, $states, $cmoptions, $attempt, $lastattemptid)) { |
1188 | return false; | |
1189 | } | |
81d833ad | 1190 | |
1191 | return $states; | |
1192 | } | |
1193 | ||
b55797b8 | 1194 | /** |
1195 | * Load a particular previous state of a question. | |
1196 | * | |
50fcb1d8 | 1197 | * @global object |
b55797b8 | 1198 | * @param array $question The question to load the state for. |
1199 | * @param object $cmoptions Options from the specifica activity module, e.g. $quiz. | |
1200 | * @param object $attempt The attempt for which the question sessions are to be loaded. | |
1201 | * @param integer $stateid The id of a specific state of this question. | |
1202 | * @return object the requested state. False on error. | |
1203 | */ | |
1204 | function question_load_specific_state($question, $cmoptions, $attempt, $stateid) { | |
8b92c1e3 | 1205 | global $DB; |
b55797b8 | 1206 | // Load specified states for the question. |
766df8f7 | 1207 | // sess.sumpenalty is probably wrong here shoul really be a sum of penalties from before the one we are asking for. |
1208 | $sql = 'SELECT st.*, sess.sumpenalty, sess.manualcomment, sess.flagged, sess.id as questionsessionid | |
b55797b8 | 1209 | FROM {question_states} st, {question_sessions} sess |
1210 | WHERE st.id = ? | |
1211 | AND st.attempt = ? | |
1212 | AND sess.attemptid = st.attempt | |
1213 | AND st.question = ? | |
1214 | AND sess.questionid = st.question'; | |
1215 | $state = $DB->get_record_sql($sql, array($stateid, $attempt->id, $question->id)); | |
1216 | if (!$state) { | |
1217 | return false; | |
1218 | } | |
1219 | restore_question_state($question, $state); | |
1220 | ||
1221 | // Load the most recent graded states for the questions before the specified one. | |
766df8f7 | 1222 | $sql = 'SELECT st.*, sess.sumpenalty, sess.manualcomment, sess.flagged, sess.id as questionsessionid |
b55797b8 | 1223 | FROM {question_states} st, {question_sessions} sess |
1224 | WHERE st.seq_number <= ? | |
1225 | AND st.attempt = ? | |
1226 | AND sess.attemptid = st.attempt | |
1227 | AND st.question = ? | |
1228 | AND sess.questionid = st.question | |
8b92c1e3 | 1229 | AND st.event IN ('.QUESTION_EVENTS_GRADED.') '. |
b55797b8 | 1230 | 'ORDER BY st.seq_number DESC'; |
8b92c1e3 | 1231 | $gradedstates = $DB->get_records_sql($sql, array($state->seq_number, $attempt->id, $question->id), 0, 1); |
b55797b8 | 1232 | if (empty($gradedstates)) { |
1233 | $state->last_graded = clone($state); | |
1234 | } else { | |
1235 | $gradedstate = reset($gradedstates); | |
1236 | restore_question_state($question, $gradedstate); | |
1237 | $state->last_graded = $gradedstate; | |
1238 | } | |
1239 | return $state; | |
1240 | } | |
516cf3eb | 1241 | |
1242 | /** | |
1243 | * Creates the run-time fields for the states | |
1244 | * | |
1245 | * Extends the state objects for a question by calling | |
1246 | * {@link restore_session_and_responses()} | |
50fcb1d8 | 1247 | * |
1248 | * @global object | |
516cf3eb | 1249 | * @param object $question The question for which the state is needed |
865b7534 | 1250 | * @param object $state The state as loaded from the database |
1251 | * @return boolean Represents success or failure | |
516cf3eb | 1252 | */ |
4f48fb42 | 1253 | function restore_question_state(&$question, &$state) { |
f02c6f01 | 1254 | global $QTYPES; |
516cf3eb | 1255 | |
1256 | // initialise response to the value in the answer field | |
294ce987 | 1257 | $state->responses = array('' => $state->answer); |
516cf3eb | 1258 | unset($state->answer); |
294ce987 | 1259 | $state->manualcomment = isset($state->manualcomment) ? $state->manualcomment : ''; |
516cf3eb | 1260 | |
1261 | // Set the changed field to false; any code which changes the | |
1262 | // question session must set this to true and must increment | |
4f48fb42 | 1263 | // ->seq_number. The save_question_session |
516cf3eb | 1264 | // function will save the new state object to the database if the field is |
1265 | // set to true. | |
1266 | $state->changed = false; | |
1267 | ||
1268 | // Load the question type specific data | |
f02c6f01 | 1269 | return $QTYPES[$question->qtype] |
865b7534 | 1270 | ->restore_session_and_responses($question, $state); |
516cf3eb | 1271 | |
1272 | } | |
1273 | ||
1274 | /** | |
1275 | * Saves the current state of the question session to the database | |
1276 | * | |
1277 | * The state object representing the current state of the session for the | |
4f48fb42 | 1278 | * question is saved to the question_states table with ->responses[''] saved |
516cf3eb | 1279 | * to the answer field of the database table. The information in the |
1280 | * question_sessions table is updated. | |
1281 | * The question type specific data is then saved. | |
50fcb1d8 | 1282 | * |
1283 | * @global array | |
1284 | * @global object | |
bc2feba3 | 1285 | * @return mixed The id of the saved or updated state or false |
516cf3eb | 1286 | * @param object $question The question for which session is to be saved. |
1287 | * @param object $state The state information to be saved. In particular the | |
1288 | * most recent responses are in ->responses. The object | |
1289 | * is updated to hold the new ->id. | |
1290 | */ | |
66d07f81 | 1291 | function save_question_session($question, $state) { |
eb84a826 | 1292 | global $QTYPES, $DB; |
5e9170b4 | 1293 | |
516cf3eb | 1294 | // Check if the state has changed |
1295 | if (!$state->changed && isset($state->id)) { | |
5e9170b4 | 1296 | if (isset($state->newflaggedstate) && $state->flagged != $state->newflaggedstate) { |
1297 | // If this fails, don't worry too much, it is not critical data. | |
1298 | question_update_flag($state->questionsessionid, $state->newflaggedstate); | |
1299 | } | |
bc2feba3 | 1300 | return $state->id; |
516cf3eb | 1301 | } |
1302 | // Set the legacy answer field | |
1303 | $state->answer = isset($state->responses['']) ? $state->responses[''] : ''; | |
1304 | ||
1305 | // Save the state | |
36be25f6 | 1306 | if (!empty($state->update)) { // this forces the old state record to be overwritten |
eb84a826 | 1307 | $DB->update_record('question_states', $state); |
516cf3eb | 1308 | } else { |
a8f3a651 | 1309 | $state->id = $DB->insert_record('question_states', $state); |
b6e907a2 | 1310 | } |
516cf3eb | 1311 | |
b6e907a2 | 1312 | // create or update the session |
b9bd6da4 | 1313 | if (!$session = $DB->get_record('question_sessions', array('attemptid' => $state->attempt, 'questionid' => $question->id))) { |
5e9170b4 | 1314 | $session = new stdClass; |
2e9b6d15 | 1315 | $session->attemptid = $state->attempt; |
1316 | $session->questionid = $question->id; | |
1317 | $session->newest = $state->id; | |
1318 | // The following may seem weird, but the newgraded field needs to be set | |
1319 | // already even if there is no graded state yet. | |
1320 | $session->newgraded = $state->id; | |
1321 | $session->sumpenalty = $state->sumpenalty; | |
3e3e5a40 | 1322 | $session->manualcomment = $state->manualcomment; |
5e9170b4 | 1323 | $session->flagged = !empty($state->newflaggedstate); |
fc29e51b | 1324 | $DB->insert_record('question_sessions', $session); |
b6e907a2 | 1325 | } else { |
2e9b6d15 | 1326 | $session->newest = $state->id; |
1327 | if (question_state_is_graded($state) or $state->event == QUESTION_EVENTOPEN) { | |
1328 | // this state is graded or newly opened, so it goes into the lastgraded field as well | |
1329 | $session->newgraded = $state->id; | |
1330 | $session->sumpenalty = $state->sumpenalty; | |
3e3e5a40 | 1331 | $session->manualcomment = $state->manualcomment; |
ef822868 | 1332 | } else { |
eb84a826 | 1333 | $session->manualcomment = $session->manualcomment; |
516cf3eb | 1334 | } |
5e9170b4 | 1335 | $session->flagged = !empty($state->newflaggedstate); |
bb4b6010 | 1336 | $DB->update_record('question_sessions', $session); |
516cf3eb | 1337 | } |
1338 | ||
1339 | unset($state->answer); | |
1340 | ||
1341 | // Save the question type specific state information and responses | |
5e9170b4 | 1342 | if (!$QTYPES[$question->qtype]->save_session_and_responses($question, $state)) { |
516cf3eb | 1343 | return false; |
1344 | } | |
5e9170b4 | 1345 | |
516cf3eb | 1346 | // Reset the changed flag |
1347 | $state->changed = false; | |
bc2feba3 | 1348 | return $state->id; |
516cf3eb | 1349 | } |
1350 | ||
1351 | /** | |
1352 | * Determines whether a state has been graded by looking at the event field | |
1353 | * | |
1354 | * @return boolean true if the state has been graded | |
1355 | * @param object $state | |
1356 | */ | |
4f48fb42 | 1357 | function question_state_is_graded($state) { |
8b92c1e3 | 1358 | static $question_events_graded = array(); |
1359 | if (!$question_events_graded){ | |
1360 | $question_events_graded = explode(',', QUESTION_EVENTS_GRADED); | |
1361 | } | |
1362 | return (in_array($state->event, $question_events_graded)); | |
f30bbcaf | 1363 | } |
1364 | ||
1365 | /** | |
1366 | * Determines whether a state has been closed by looking at the event field | |
1367 | * | |
1368 | * @return boolean true if the state has been closed | |
1369 | * @param object $state | |
1370 | */ | |
1371 | function question_state_is_closed($state) { | |
8b92c1e3 | 1372 | static $question_events_closed = array(); |
1373 | if (!$question_events_closed){ | |
1374 | $question_events_closed = explode(',', QUESTION_EVENTS_CLOSED); | |
1375 | } | |
1376 | return (in_array($state->event, $question_events_closed)); | |
516cf3eb | 1377 | } |
1378 | ||
1379 | ||
1380 | /** | |
4dca7e51 | 1381 | * Extracts responses from submitted form |
1382 | * | |
1383 | * This can extract the responses given to one or several questions present on a page | |
1384 | * It returns an array with one entry for each question, indexed by question id | |
1385 | * Each entry is an object with the properties | |
1386 | * ->event The event that has triggered the submission. This is determined by which button | |
1387 | * the user has pressed. | |
1388 | * ->responses An array holding the responses to an individual question, indexed by the | |
1389 | * name of the corresponding form element. | |
1390 | * ->timestamp A unix timestamp | |
1391 | * @return array array of action objects, indexed by question ids. | |
1392 | * @param array $questions an array containing at least all questions that are used on the form | |
1393 | * @param array $formdata the data submitted by the form on the question page | |
1394 | * @param integer $defaultevent the event type used if no 'mark' or 'validate' is submitted | |
1395 | */ | |
1396 | function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE) { | |
516cf3eb | 1397 | |
4dca7e51 | 1398 | $time = time(); |
516cf3eb | 1399 | $actions = array(); |
4dca7e51 | 1400 | foreach ($formdata as $key => $response) { |
516cf3eb | 1401 | // Get the question id from the response name |
4f48fb42 | 1402 | if (false !== ($quid = question_get_id_from_name_prefix($key))) { |
516cf3eb | 1403 | // check if this is a valid id |
1404 | if (!isset($questions[$quid])) { | |
d89ec019 | 1405 | print_error('formquestionnotinids', 'question'); |
516cf3eb | 1406 | } |
1407 | ||
1408 | // Remove the name prefix from the name | |
1409 | //decrypt trying | |
1410 | $key = substr($key, strlen($questions[$quid]->name_prefix)); | |
1411 | if (false === $key) { | |
1412 | $key = ''; | |
1413 | } | |
1414 | // Check for question validate and mark buttons & set events | |
1415 | if ($key === 'validate') { | |
4f48fb42 | 1416 | $actions[$quid]->event = QUESTION_EVENTVALIDATE; |
4dca7e51 | 1417 | } else if ($key === 'submit') { |
f30bbcaf | 1418 | $actions[$quid]->event = QUESTION_EVENTSUBMIT; |
516cf3eb | 1419 | } else { |
1420 | $actions[$quid]->event = $defaultevent; | |
1421 | } | |
516cf3eb | 1422 | // Update the state with the new response |
1423 | $actions[$quid]->responses[$key] = $response; | |
271ffe3f | 1424 | |
4dca7e51 | 1425 | // Set the timestamp |
1426 | $actions[$quid]->timestamp = $time; | |
516cf3eb | 1427 | } |
1428 | } | |
3ebdddf7 | 1429 | foreach ($actions as $quid => $notused) { |
1430 | ksort($actions[$quid]->responses); | |
1431 | } | |
516cf3eb | 1432 | return $actions; |
1433 | } | |
1434 | ||
1435 | ||
bc75cc52 | 1436 | /** |
1437 | * Returns the html for question feedback image. | |
50fcb1d8 | 1438 | * |
1439 | * @global object | |
bc75cc52 | 1440 | * @param float $fraction value representing the correctness of the user's |
1441 | * response to a question. | |
1442 | * @param boolean $selected whether or not the answer is the one that the | |
1443 | * user picked. | |
1444 | * @return string | |
1445 | */ | |
1446 | function question_get_feedback_image($fraction, $selected=true) { | |
d4a03c00 | 1447 | global $CFG, $OUTPUT; |
b10c38a3 | 1448 | static $icons = array('correct' => 'tick_green', 'partiallycorrect' => 'tick_amber', |
1449 | 'incorrect' => 'cross_red'); | |
bc75cc52 | 1450 | |
b10c38a3 | 1451 | if ($selected) { |
1452 | $size = 'big'; | |
bc75cc52 | 1453 | } else { |
b10c38a3 | 1454 | $size = 'small'; |
bc75cc52 | 1455 | } |
b10c38a3 | 1456 | $class = question_get_feedback_class($fraction); |
b5d0cafc | 1457 | return '<img src="' . $OUTPUT->pix_url('i/' . $icons[$class] . '_' . $size) . |
ddedf979 | 1458 | '" alt="' . get_string($class, 'quiz') . '" class="icon" />'; |
bc75cc52 | 1459 | } |
1460 | ||
bc75cc52 | 1461 | /** |
1462 | * Returns the class name for question feedback. | |
1463 | * @param float $fraction value representing the correctness of the user's | |
1464 | * response to a question. | |
1465 | * @return string | |
1466 | */ | |
1467 | function question_get_feedback_class($fraction) { | |
b10c38a3 | 1468 | if ($fraction >= 1/1.01) { |
1469 | return 'correct'; | |
1470 | } else if ($fraction > 0.0) { | |
1471 | return 'partiallycorrect'; | |
bc75cc52 | 1472 | } else { |
b10c38a3 | 1473 | return 'incorrect'; |
bc75cc52 | 1474 | } |
bc75cc52 | 1475 | } |
1476 | ||
516cf3eb | 1477 | |
1478 | /** | |
1479 | * For a given question in an attempt we walk the complete history of states | |
1480 | * and recalculate the grades as we go along. | |
1481 | * | |
1482 | * This is used when a question is changed and old student | |
1483 | * responses need to be marked with the new version of a question. | |
1484 | * | |
50fcb1d8 | 1485 | * @todo Make sure this is not quiz-specific |
4f48fb42 | 1486 | * |
50fcb1d8 | 1487 | * @global object |
0a5b58af | 1488 | * @return boolean Indicates whether the grade has changed |
516cf3eb | 1489 | * @param object $question A question object |
1490 | * @param object $attempt The attempt, in which the question needs to be regraded. | |
1491 | * @param object $cmoptions | |
1492 | * @param boolean $verbose Optional. Whether to print progress information or not. | |
98f38217 | 1493 | * @param boolean $dryrun Optional. Whether to make changes to grades records |
1494 | * or record that changes need to be made for a later regrade. | |
516cf3eb | 1495 | */ |
98f38217 | 1496 | function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false, $dryrun=false) { |
aa9a6867 | 1497 | global $DB, $OUTPUT; |
516cf3eb | 1498 | |
1499 | // load all states for this question in this attempt, ordered in sequence | |
eb84a826 | 1500 | if ($states = $DB->get_records('question_states', |
1501 | array('attempt'=>$attempt->uniqueid, 'question'=>$question->id), | |
865b7534 | 1502 | 'seq_number ASC')) { |
516cf3eb | 1503 | $states = array_values($states); |
1504 | ||
1505 | // Subtract the grade for the latest state from $attempt->sumgrades to get the | |
271ffe3f | 1506 | // sumgrades for the attempt without this question. |
516cf3eb | 1507 | $attempt->sumgrades -= $states[count($states)-1]->grade; |
1508 | ||
1509 | // Initialise the replaystate | |
766df8f7 | 1510 | $replaystate = question_load_specific_state($question, $cmoptions, $attempt, $states[0]->id); |
1511 | $replaystate->sumpenalty = 0; | |
1512 | $replaystate->last_graded->sumpenalty = 0; | |
516cf3eb | 1513 | |
0a5b58af | 1514 | $changed = false; |
516cf3eb | 1515 | for($j = 1; $j < count($states); $j++) { |
4f48fb42 | 1516 | restore_question_state($question, $states[$j]); |
516cf3eb | 1517 | $action = new stdClass; |
1518 | $action->responses = $states[$j]->responses; | |
1519 | $action->timestamp = $states[$j]->timestamp; | |
1520 | ||
f30bbcaf | 1521 | // Change event to submit so that it will be reprocessed |
766df8f7 | 1522 | if (in_array($states[$j]->event, array(QUESTION_EVENTCLOSE, |
1523 | QUESTION_EVENTGRADE, QUESTION_EVENTCLOSEANDGRADE))) { | |
f30bbcaf | 1524 | $action->event = QUESTION_EVENTSUBMIT; |
516cf3eb | 1525 | |
1526 | // By default take the event that was saved in the database | |
1527 | } else { | |
1528 | $action->event = $states[$j]->event; | |
1529 | } | |
36be25f6 | 1530 | |
5e60643e | 1531 | if ($action->event == QUESTION_EVENTMANUALGRADE) { |
b9bd6da4 | 1532 | // Ensure that the grade is in range - in the past this was not checked, |
994c8c35 | 1533 | // but now it is (MDL-14835) - so we need to ensure the data is valid before |
1534 | // proceeding. | |
1535 | if ($states[$j]->grade < 0) { | |
1536 | $states[$j]->grade = 0; | |
98f38217 | 1537 | $changed = true; |
994c8c35 | 1538 | } else if ($states[$j]->grade > $question->maxgrade) { |
1539 | $states[$j]->grade = $question->maxgrade; | |
98f38217 | 1540 | $changed = true; |
117bd748 | 1541 | |
994c8c35 | 1542 | } |
98f38217 | 1543 | if (!$dryrun){ |
1544 | $error = question_process_comment($question, $replaystate, $attempt, | |
1545 | $replaystate->manualcomment, $states[$j]->grade); | |
1546 | if (is_string($error)) { | |
aa9a6867 | 1547 | echo $OUTPUT->notification($error); |
98f38217 | 1548 | } |
1549 | } else { | |
1550 | $replaystate->grade = $states[$j]->grade; | |
994c8c35 | 1551 | } |
36be25f6 | 1552 | } else { |
36be25f6 | 1553 | // Reprocess (regrade) responses |
865b7534 | 1554 | if (!question_process_responses($question, $replaystate, |
766df8f7 | 1555 | $action, $cmoptions, $attempt) && $verbose) { |
1556 | $a = new stdClass; | |
1557 | $a->qid = $question->id; | |
1558 | $a->stateid = $states[$j]->id; | |
aa9a6867 | 1559 | echo $OUTPUT->notification(get_string('errorduringregrade', 'question', $a)); |
36be25f6 | 1560 | } |
98f38217 | 1561 | // We need rounding here because grades in the DB get truncated |
1562 | // e.g. 0.33333 != 0.3333333, but we want them to be equal here | |
1563 | if ((round((float)$replaystate->raw_grade, 5) != round((float)$states[$j]->raw_grade, 5)) | |
1564 | or (round((float)$replaystate->penalty, 5) != round((float)$states[$j]->penalty, 5)) | |
1565 | or (round((float)$replaystate->grade, 5) != round((float)$states[$j]->grade, 5))) { | |
1566 | $changed = true; | |
1567 | } | |
766df8f7 | 1568 | // If this was previously a closed state, and it has been knoced back to |
1569 | // graded, then fix up the state again. | |
1570 | if ($replaystate->event == QUESTION_EVENTGRADE && | |
1571 | ($states[$j]->event == QUESTION_EVENTCLOSE || | |
1572 | $states[$j]->event == QUESTION_EVENTCLOSEANDGRADE)) { | |
1573 | $replaystate->event = $states[$j]->event; | |
1574 | } | |
516cf3eb | 1575 | } |
516cf3eb | 1576 | |
1577 | $replaystate->id = $states[$j]->id; | |
271ffe3f | 1578 | $replaystate->changed = true; |
d23e3e11 | 1579 | $replaystate->update = true; // This will ensure that the existing database entry is updated rather than a new one created |
98f38217 | 1580 | if (!$dryrun){ |
1581 | save_question_session($question, $replaystate); | |
1582 | } | |
516cf3eb | 1583 | } |
0a5b58af | 1584 | if ($changed) { |
98f38217 | 1585 | if (!$dryrun){ |
1586 | // TODO, call a method in quiz to do this, where 'quiz' comes from | |
1587 | // the question_attempts table. | |
1588 | $DB->update_record('quiz_attempts', $attempt); | |
1589 | } | |
1590 | } | |
1591 | if ($changed){ | |
1592 | $toinsert = new object(); | |
1593 | $toinsert->oldgrade = round((float)$states[count($states)-1]->grade, 5); | |
1594 | $toinsert->newgrade = round((float)$replaystate->grade, 5); | |
1595 | $toinsert->attemptid = $attempt->uniqueid; | |
1596 | $toinsert->questionid = $question->id; | |
1597 | //the grade saved is the old grade if the new grade is saved | |
1598 | //it is the new grade if this is a dry run. | |
1599 | $toinsert->regraded = $dryrun?0:1; | |
1600 | $toinsert->timemodified = time(); | |
1601 | $DB->insert_record('quiz_question_regrade', $toinsert); | |
1602 | return true; | |
1603 | } else { | |
1604 | return false; | |
516cf3eb | 1605 | } |
516cf3eb | 1606 | } |
0a5b58af | 1607 | return false; |
516cf3eb | 1608 | } |
1609 | ||
1610 | /** | |
1611 | * Processes an array of student responses, grading and saving them as appropriate | |
1612 | * | |
50fcb1d8 | 1613 | * @global array |
516cf3eb | 1614 | * @param object $question Full question object, passed by reference |
1615 | * @param object $state Full state object, passed by reference | |
1616 | * @param object $action object with the fields ->responses which | |
1617 | * is an array holding the student responses, | |
4f48fb42 | 1618 | * ->action which specifies the action, e.g., QUESTION_EVENTGRADE, |
516cf3eb | 1619 | * and ->timestamp which is a timestamp from when the responses |
1620 | * were submitted by the student. | |
1621 | * @param object $cmoptions | |
1622 | * @param object $attempt The attempt is passed by reference so that | |
1623 | * during grading its ->sumgrades field can be updated | |
373f0afd | 1624 | * @return boolean Indicates success/failure |
516cf3eb | 1625 | */ |
66d07f81 | 1626 | function question_process_responses($question, &$state, $action, $cmoptions, &$attempt) { |
f02c6f01 | 1627 | global $QTYPES; |
516cf3eb | 1628 | |
1629 | // if no responses are set initialise to empty response | |
1630 | if (!isset($action->responses)) { | |
1631 | $action->responses = array('' => ''); | |
1632 | } | |
1633 | ||
5e9170b4 | 1634 | $state->newflaggedstate = !empty($action->responses['_flagged']); |
1635 | ||
516cf3eb | 1636 | // make sure these are gone! |
5e9170b4 | 1637 | unset($action->responses['submit'], $action->responses['validate'], $action->responses['_flagged']); |
516cf3eb | 1638 | |
1639 | // Check the question session is still open | |
f30bbcaf | 1640 | if (question_state_is_closed($state)) { |
516cf3eb | 1641 | return true; |
1642 | } | |
f30bbcaf | 1643 | |
516cf3eb | 1644 | // If $action->event is not set that implies saving |
1645 | if (! isset($action->event)) { | |
a6b691d8 | 1646 | debugging('Ambiguous action in question_process_responses.' , DEBUG_DEVELOPER); |
4f48fb42 | 1647 | $action->event = QUESTION_EVENTSAVE; |
516cf3eb | 1648 | } |
f30bbcaf | 1649 | // If submitted then compare against last graded |
516cf3eb | 1650 | // responses, not last given responses in this case |
4f48fb42 | 1651 | if (question_isgradingevent($action->event)) { |
516cf3eb | 1652 | $state->responses = $state->last_graded->responses; |
1653 | } | |
271ffe3f | 1654 | |
516cf3eb | 1655 | // Check for unchanged responses (exactly unchanged, not equivalent). |
1656 | // We also have to catch questions that the student has not yet attempted | |
47cdbd1f | 1657 | $sameresponses = $QTYPES[$question->qtype]->compare_responses($question, $action, $state); |
4f2c86ad | 1658 | if (!empty($state->last_graded) && $state->last_graded->event == QUESTION_EVENTOPEN && |
1659 | question_isgradingevent($action->event)) { | |
47cdbd1f | 1660 | $sameresponses = false; |
1661 | } | |
516cf3eb | 1662 | |
f30bbcaf | 1663 | // If the response has not been changed then we do not have to process it again |
1664 | // unless the attempt is closing or validation is requested | |
4f48fb42 | 1665 | if ($sameresponses and QUESTION_EVENTCLOSE != $action->event |
5a14d563 | 1666 | and QUESTION_EVENTVALIDATE != $action->event) { |
516cf3eb | 1667 | return true; |
1668 | } | |
1669 | ||
1670 | // Roll back grading information to last graded state and set the new | |
1671 | // responses | |
1672 | $newstate = clone($state->last_graded); | |
1673 | $newstate->responses = $action->responses; | |
1674 | $newstate->seq_number = $state->seq_number + 1; | |
1675 | $newstate->changed = true; // will assure that it gets saved to the database | |
ca56222d | 1676 | $newstate->last_graded = clone($state->last_graded); |
516cf3eb | 1677 | $newstate->timestamp = $action->timestamp; |
5e9170b4 | 1678 | $newstate->newflaggedstate = $state->newflaggedstate; |
1679 | $newstate->flagged = $state->flagged; | |
1680 | $newstate->questionsessionid = $state->questionsessionid; | |
516cf3eb | 1681 | $state = $newstate; |
1682 | ||
1683 | // Set the event to the action we will perform. The question type specific | |
4f48fb42 | 1684 | // grading code may override this by setting it to QUESTION_EVENTCLOSE if the |
516cf3eb | 1685 | // attempt at the question causes the session to close |
1686 | $state->event = $action->event; | |
1687 | ||
4f48fb42 | 1688 | if (!question_isgradingevent($action->event)) { |
516cf3eb | 1689 | // Grade the response but don't update the overall grade |
373f0afd | 1690 | if (!$QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions)) { |
1691 | return false; | |
1692 | } | |
3bee1ead | 1693 | |
47e16978 | 1694 | // Temporary hack because question types are not given enough control over what is going |
1695 | // on. Used by Opaque questions. | |
1696 | // TODO fix this code properly. | |
1697 | if (!empty($state->believeevent)) { | |
1698 | // If the state was graded we need to ... | |
1699 | if (question_state_is_graded($state)) { | |
1700 | question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions); | |
1701 | ||
1702 | // update the attempt grade | |
1703 | $attempt->sumgrades -= (float)$state->last_graded->grade; | |
1704 | $attempt->sumgrades += (float)$state->grade; | |
3bee1ead | 1705 | |
47e16978 | 1706 | // and update the last_graded field. |
1707 | unset($state->last_graded); | |
1708 | $state->last_graded = clone($state); | |
1709 | unset($state->last_graded->changed); | |
1710 | } | |
1711 | } else { | |
1712 | // Don't allow the processing to change the event type | |
1713 | $state->event = $action->event; | |
1714 | } | |
3bee1ead | 1715 | |
ca56222d | 1716 | } else { // grading event |
516cf3eb | 1717 | |
271ffe3f | 1718 | // Unless the attempt is closing, we want to work out if the current responses |
1719 | // (or equivalent responses) were already given in the last graded attempt. | |
5a14d563 | 1720 | if(QUESTION_EVENTCLOSE != $action->event && QUESTION_EVENTOPEN != $state->last_graded->event && |
1721 | $QTYPES[$question->qtype]->compare_responses($question, $state, $state->last_graded)) { | |
f30bbcaf | 1722 | $state->event = QUESTION_EVENTDUPLICATE; |
516cf3eb | 1723 | } |
f30bbcaf | 1724 | |
ca56222d | 1725 | // If we did not find a duplicate or if the attempt is closing, perform grading |
5a14d563 | 1726 | if ((!$sameresponses and QUESTION_EVENTDUPLICATE != $state->event) or |
1727 | QUESTION_EVENTCLOSE == $action->event) { | |
373f0afd | 1728 | if (!$QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions)) { |
1729 | return false; | |
1730 | } | |
f30bbcaf | 1731 | |
f30bbcaf | 1732 | // Calculate overall grade using correct penalty method |
1733 | question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions); | |
516cf3eb | 1734 | } |
516cf3eb | 1735 | |
47e16978 | 1736 | // If the state was graded we need to ... |
ca56222d | 1737 | if (question_state_is_graded($state)) { |
47e16978 | 1738 | // update the attempt grade |
1739 | $attempt->sumgrades -= (float)$state->last_graded->grade; | |
1740 | $attempt->sumgrades += (float)$state->grade; | |
1741 | ||
1742 | // and update the last_graded field. | |
ca56222d | 1743 | unset($state->last_graded); |
1744 | $state->last_graded = clone($state); | |
1745 | unset($state->last_graded->changed); | |
1746 | } | |
516cf3eb | 1747 | } |
1748 | $attempt->timemodified = $action->timestamp; | |
1749 | ||
1750 | return true; | |
1751 | } | |
1752 | ||
1753 | /** | |
1754 | * Determine if event requires grading | |
1755 | */ | |
4f48fb42 | 1756 | function question_isgradingevent($event) { |
f30bbcaf | 1757 | return (QUESTION_EVENTSUBMIT == $event || QUESTION_EVENTCLOSE == $event); |
516cf3eb | 1758 | } |
1759 | ||
516cf3eb | 1760 | /** |
1761 | * Applies the penalty from the previous graded responses to the raw grade | |
1762 | * for the current responses | |
1763 | * | |
1764 | * The grade for the question in the current state is computed by subtracting the | |
1765 | * penalty accumulated over the previous graded responses at the question from the | |
1766 | * raw grade. If the timestamp is more than 1 minute beyond the end of the attempt | |
1767 | * the grade is set to zero. The ->grade field of the state object is modified to | |
1768 | * reflect the new grade but is never allowed to decrease. | |
1769 | * @param object $question The question for which the penalty is to be applied. | |
1770 | * @param object $state The state for which the grade is to be set from the | |
1771 | * raw grade and the cumulative penalty from the last | |
1772 | * graded state. The ->grade field is updated by applying | |
1773 | * the penalty scheme determined in $cmoptions to the ->raw_grade and | |
1774 | * ->last_graded->penalty fields. | |
1775 | * @param object $cmoptions The options set by the course module. | |
1776 | * The ->penaltyscheme field determines whether penalties | |
1777 | * for incorrect earlier responses are subtracted. | |
1778 | */ | |
4f48fb42 | 1779 | function question_apply_penalty_and_timelimit(&$question, &$state, $attempt, $cmoptions) { |
b423cff1 | 1780 | // TODO. Quiz dependancy. The fact that the attempt that is passed in here |
1781 | // is from quiz_attempts, and we use things like $cmoptions->timelimit. | |
3bee1ead | 1782 | |
f30bbcaf | 1783 | // deal with penalty |
516cf3eb | 1784 | if ($cmoptions->penaltyscheme) { |
47e16978 | 1785 | $state->grade = $state->raw_grade - $state->sumpenalty; |
1786 | $state->sumpenalty += (float) $state->penalty; | |
516cf3eb | 1787 | } else { |
1788 | $state->grade = $state->raw_grade; | |
1789 | } | |
1790 | ||
1791 | // deal with timelimit | |
1792 | if ($cmoptions->timelimit) { | |
1793 | // We allow for 5% uncertainty in the following test | |
84e628a0 | 1794 | if ($state->timestamp - $attempt->timestart > $cmoptions->timelimit * 1.05) { |
c7318911 | 1795 | $cm = get_coursemodule_from_instance('quiz', $cmoptions->id); |
1796 | if (!has_capability('mod/quiz:ignoretimelimits', get_context_instance(CONTEXT_MODULE, $cm->id), | |
1797 | $attempt->userid, false)) { | |
1798 | $state->grade = 0; | |
1799 | } | |
516cf3eb | 1800 | } |
1801 | } | |
1802 | ||
1803 | // deal with closing time | |
1804 | if ($cmoptions->timeclose and $state->timestamp > ($cmoptions->timeclose + 60) // allowing 1 minute lateness | |
1805 | and !$attempt->preview) { // ignore closing time for previews | |
1806 | $state->grade = 0; | |
1807 | } | |
1808 | ||
1809 | // Ensure that the grade does not go down | |
1810 | $state->grade = max($state->grade, $state->last_graded->grade); | |
1811 | } | |
1812 | ||
516cf3eb | 1813 | /** |
1814 | * Print the icon for the question type | |
1815 | * | |
50fcb1d8 | 1816 | * @global array |
1817 | * @global object | |
3843d274 | 1818 | * @param object $question The question object for which the icon is required |
1819 | * only $question->qtype is used. | |
1820 | * @param boolean $return If true the functions returns the link as a string | |
516cf3eb | 1821 | */ |
dcc2ffde | 1822 | function print_question_icon($question, $return = false) { |
dc1f00de | 1823 | global $QTYPES, $CFG; |
516cf3eb | 1824 | |
b9d4b031 | 1825 | if (array_key_exists($question->qtype, $QTYPES)) { |
05efb0e5 | 1826 | $namestr = $QTYPES[$question->qtype]->local_name(); |
b9d4b031 | 1827 | } else { |
1828 | $namestr = 'missingtype'; | |
1829 | } | |
dcc2ffde | 1830 | $html = '<img src="' . $CFG->wwwroot . '/question/type/' . |
1831 | $question->qtype . '/icon.gif" alt="' . | |
1832 | $namestr . '" title="' . $namestr . '" />'; | |
516cf3eb | 1833 | if ($return) { |
1834 | return $html; | |
1835 | } else { | |
1836 | echo $html; | |
1837 | } | |
1838 | } | |
1839 | ||
516cf3eb | 1840 | /** |
1841 | * Returns a html link to the question image if there is one | |
1842 | * | |
50fcb1d8 | 1843 | * @global object |
1844 | * @global object | |
516cf3eb | 1845 | * @return string The html image tag or the empy string if there is no image. |
1846 | * @param object $question The question object | |
1847 | */ | |
9fc3100f | 1848 | function get_question_image($question) { |
eb84a826 | 1849 | global $CFG, $DB; |
516cf3eb | 1850 | $img = ''; |
1851 | ||
eb84a826 | 1852 | if (!$category = $DB->get_record('question_categories', array('id'=>$question->category))) { |
d89ec019 | 1853 | print_error('invalidcategory'); |
9fc3100f | 1854 | } |
1855 | $coursefilesdir = get_filesdir_from_context(get_context_instance_by_id($category->contextid)); | |
1856 | ||
516cf3eb | 1857 | if ($question->image) { |
1858 | ||
1859 | if (substr(strtolower($question->image), 0, 7) == 'http://') { | |
1860 | $img .= $question->image; | |
1861 | ||
516cf3eb | 1862 | } else { |
5a254a29 | 1863 | require_once($CFG->libdir .'/filelib.php'); |
bbf795df | 1864 | $img = get_file_url("$coursefilesdir/{$question->image}"); |
117bd748 | 1865 | } |
516cf3eb | 1866 | } |
1867 | return $img; | |
1868 | } | |
b6e907a2 | 1869 | |
50fcb1d8 | 1870 | /** |
1871 | * @global array | |
1872 | */ | |
e8f99abc | 1873 | function question_print_comment_fields($question, $state, $prefix, $cmoptions, $caption = '') { |
83f0fef5 | 1874 | global $QTYPES; |
766df8f7 | 1875 | $idprefix = preg_replace('/[^-_a-zA-Z0-9]/', '', $prefix); |
574c3750 | 1876 | $otherquestionsinuse = ''; |
1877 | if (!empty($cmoptions->questions)) { | |
1878 | $otherquestionsinuse = $cmoptions->questions; | |
1879 | } | |
1880 | if (!question_state_is_graded($state) && $QTYPES[$question->qtype]->is_question_manual_graded($question, $otherquestionsinuse)) { | |
83f0fef5 | 1881 | $grade = ''; |
1882 | } else { | |
1883 | $grade = question_format_grade($cmoptions, $state->last_graded->grade); | |
1884 | } | |
766df8f7 | 1885 | $maxgrade = question_format_grade($cmoptions, $question->maxgrade); |
1886 | $fieldsize = strlen($maxgrade) - 1; | |
e8f99abc | 1887 | if (empty($caption)) { |
1888 | $caption = format_string($question->name); | |
1889 | } | |
1890 | ?> | |
1891 | <fieldset class="que comment clearfix"> | |
1892 | <legend class="ftoggler"><?php echo $caption; ?></legend> | |
1893 | <div class="fcontainer clearfix"> | |
1894 | <div class="fitem"> | |
1895 | <div class="fitemtitle"> | |
1896 | <label for="<?php echo $idprefix; ?>_comment_box"><?php print_string('comment', 'quiz'); ?></label> | |
1897 | </div> | |
1898 | <div class="felement fhtmleditor"> | |
1899 | <?php print_textarea(can_use_html_editor(), 15, 60, 630, 300, $prefix . '[comment]', | |
1900 | $state->manualcomment, 0, false, $idprefix . '_comment_box'); ?> | |
1901 | </div> | |
1902 | </div> | |
1903 | <div class="fitem"> | |
1904 | <div class="fitemtitle"> | |
1905 | <label for="<?php echo $idprefix; ?>_grade_field"><?php print_string('grade', 'quiz'); ?></label> | |
1906 | </div> | |
1907 | <div class="felement ftext"> | |
1908 | <input type="text" name="<?php echo $prefix; ?>[grade]" size="<?php echo $fieldsize; ?>" id="<?php echo $idprefix; ?>_grade_field" value="<?php echo $grade; ?>" /> / <?php echo $maxgrade; ?> | |
1909 | </div> | |
1910 | </div> | |
1911 | </div> | |
1912 | </fieldset> | |
1913 | <?php | |
b6e907a2 | 1914 | } |
1915 | ||
994c8c35 | 1916 | /** |
1917 | * Process a manual grading action. That is, use $comment and $grade to update | |
1918 | * $state and $attempt. The attempt and the comment text are stored in the | |
1919 | * database. $state is only updated in memory, it is up to the call to store | |
1920 | * that, if appropriate. | |
1921 | * | |
50fcb1d8 | 1922 | * @global object |
994c8c35 | 1923 | * @param object $question the question |
1924 | * @param object $state the state to be updated. | |
1925 | * @param object $attempt the attempt the state belongs to, to be updated. | |
83f0fef5 | 1926 | * @param string $comment the new comment from the teacher. |
1927 | * @param mixed $grade the grade the teacher assigned, or '' to not change the grade. | |
994c8c35 | 1928 | * @return mixed true on success, a string error message if a problem is detected |
1929 | * (for example score out of range). | |
1930 | */ | |
b6e907a2 | 1931 | function question_process_comment($question, &$state, &$attempt, $comment, $grade) { |
eb84a826 | 1932 | global $DB; |
1933 | ||
83f0fef5 | 1934 | $grade = trim($grade); |
994c8c35 | 1935 | if ($grade < 0 || $grade > $question->maxgrade) { |
1936 | $a = new stdClass; | |
1937 | $a->grade = $grade; | |
1938 | $a->maxgrade = $question->maxgrade; | |
1939 | $a->name = $question->name; | |
1940 | return get_string('errormanualgradeoutofrange', 'question', $a); | |
1941 | } | |
b6e907a2 | 1942 | |
1943 | // Update the comment and save it in the database | |
fca490bc | 1944 | $comment = trim($comment); |
3e3e5a40 | 1945 | $state->manualcomment = $comment; |
f23f98dd | 1946 | $state->newflaggedstate = $state->flagged; |
eb84a826 | 1947 | if (!$DB->set_field('question_sessions', 'manualcomment', $comment, array('attemptid'=>$attempt->uniqueid, 'questionid'=>$question->id))) { |
994c8c35 | 1948 | return get_string('errorsavingcomment', 'question', $question); |
b6e907a2 | 1949 | } |
95ac8a40 | 1950 | |
1951 | // Update the attempt if the score has changed. | |
83f0fef5 | 1952 | if ($grade !== '' && (abs($state->last_graded->grade - $grade) > 0.002 || $state->last_graded->event != QUESTION_EVENTMANUALGRADE)) { |
b6e907a2 | 1953 | $attempt->sumgrades = $attempt->sumgrades - $state->last_graded->grade + $grade; |
1954 | $attempt->timemodified = time(); | |
bb4b6010 | 1955 | $DB->update_record('quiz_attempts', $attempt); |
84bf852c | 1956 | |
1957 | // We want to update existing state (rather than creating new one) if it | |
1958 | // was itself created by a manual grading event. | |
83f0fef5 | 1959 | $state->update = $state->event == QUESTION_EVENTMANUALGRADE; |
84bf852c | 1960 | |
1961 | // Update the other parts of the state object. | |
b6e907a2 | 1962 | $state->raw_grade = $grade; |
1963 | $state->grade = $grade; | |
1964 | $state->penalty = 0; | |
1965 | $state->timestamp = time(); | |
36be25f6 | 1966 | $state->seq_number++; |
95ac8a40 | 1967 | $state->event = QUESTION_EVENTMANUALGRADE; |
1968 | ||
b6e907a2 | 1969 | // Update the last graded state (don't simplify!) |
1970 | unset($state->last_graded); | |
1971 | $state->last_graded = clone($state); | |
95ac8a40 | 1972 | |
1973 | // We need to indicate that the state has changed in order for it to be saved. | |
1974 | $state->changed = 1; | |
b6e907a2 | 1975 | } |
1976 | ||
994c8c35 | 1977 | return true; |
b6e907a2 | 1978 | } |
1979 | ||
516cf3eb | 1980 | /** |
1981 | * Construct name prefixes for question form element names | |
1982 | * | |
1983 | * Construct the name prefix that should be used for example in the | |
1984 | * names of form elements created by questions. | |
4f48fb42 | 1985 | * This is called by {@link get_question_options()} |
516cf3eb | 1986 | * to set $question->name_prefix. |
1987 | * This name prefix includes the question id which can be | |
4f48fb42 | 1988 | * extracted from it with {@link question_get_id_from_name_prefix()}. |
516cf3eb | 1989 | * |
1990 | * @return string | |
1991 | * @param integer $id The question id | |
1992 | */ | |
4f48fb42 | 1993 | function question_make_name_prefix($id) { |
516cf3eb | 1994 | return 'resp' . $id . '_'; |
1995 | } | |
1996 | ||
1997 | /** | |
f62040ed | 1998 | * Extract question id from the prefix of form element names |
1999 | * | |
2000 | * @return integer The question id | |
2001 | * @param string $name The name that contains a prefix that was | |
2002 | * constructed with {@link question_make_name_prefix()} | |
2003 | */ | |
4f48fb42 | 2004 | function question_get_id_from_name_prefix($name) { |
f62040ed | 2005 | if (!preg_match('/^resp([0-9]+)_/', $name, $matches)) { |
516cf3eb | 2006 | return false; |
f62040ed | 2007 | } |
516cf3eb | 2008 | return (integer) $matches[1]; |
2009 | } | |
2010 | ||
f62040ed | 2011 | /** |
2012 | * Extract question id from the prefix of form element names | |
2013 | * | |
2014 | * @return integer The question id | |
2015 | * @param string $name The name that contains a prefix that was | |
2016 | * constructed with {@link question_make_name_prefix()} | |
2017 | */ | |
2018 | function question_id_and_key_from_post_name($name) { | |
2019 | if (!preg_match('/^resp([0-9]+)_(.*)$/', $name, $matches)) { | |
2020 | return array(false, false); | |
2021 | } | |
2022 | return array((integer) $matches[1], $matches[2]); | |
2023 | } | |
2024 | ||
4f48fb42 | 2025 | /** |
4dca7e51 | 2026 | * Returns the unique id for a new attempt |
2027 | * | |
2028 | * Every module can keep their own attempts table with their own sequential ids but | |
2029 | * the question code needs to also have a unique id by which to identify all these | |
2030 | * attempts. Hence a module, when creating a new attempt, calls this function and | |
2031 | * stores the return value in the 'uniqueid' field of its attempts table. | |
50fcb1d8 | 2032 | * |
2033 | * @global object | |
4f48fb42 | 2034 | */ |
36be25f6 | 2035 | function question_new_attempt_uniqueid($modulename='quiz') { |
eb84a826 | 2036 | global $DB; |
2037 | ||
d7444d44 | 2038 | $attempt = new stdClass; |
36be25f6 | 2039 | $attempt->modulename = $modulename; |
a8d6ef8c | 2040 | $id = $DB->insert_record('question_attempts', $attempt); |
36be25f6 | 2041 | return $id; |
516cf3eb | 2042 | } |
2043 | ||
36be25f6 | 2044 | /** |
2045 | * Creates a stamp that uniquely identifies this version of the question | |
cbe20043 | 2046 | * |
2047 | * In future we want this to use a hash of the question data to guarantee that | |
2048 | * identical versions have the same version stamp. | |
2049 | * | |
2050 | * @param object $question | |
2051 | * @return string A unique version stamp | |
2052 | */ | |
2053 | function question_hash($question) { | |
2054 | return make_unique_id_code(); | |
2055 | } | |
2056 | ||
f88fb62c | 2057 | /** |
2058 | * Round a grade to to the correct number of decimal places, and format it for display. | |
84e628a0 | 2059 | * If $cmoptions->questiondecimalpoints is set, that is used, otherwise |
2060 | * else if $cmoptions->decimalpoints is used, | |
2061 | * otherwise a default of 2 is used, but this should not be relied upon, and generated a developer debug warning. | |
2062 | * However, if $cmoptions->questiondecimalpoints is -1, the means use $cmoptions->decimalpoints. | |
f88fb62c | 2063 | * |
84e628a0 | 2064 | * @param object $cmoptions The modules settings. |
f88fb62c | 2065 | * @param float $grade The grade to round. |
2066 | */ | |
2067 | function question_format_grade($cmoptions, $grade) { | |
84e628a0 | 2068 | if (isset($cmoptions->questiondecimalpoints) && $cmoptions->questiondecimalpoints != -1) { |
2069 | $decimalplaces = $cmoptions->questiondecimalpoints; | |
2070 | } else if (isset($cmoptions->decimalpoints)) { | |
2071 | $decimalplaces = $cmoptions->decimalpoints; | |
2072 | } else { | |
2073 | $decimalplaces = 2; | |
2074 | debugging('Code that leads to question_format_grade being called should set ' . | |
2075 | '$cmoptions->questiondecimalpoints or $cmoptions->decimalpoints', DEBUG_DEVELOPER); | |
2076 | } | |
2077 | return format_float($grade, $decimalplaces); | |
f88fb62c | 2078 | } |
516cf3eb | 2079 | |
62e76c67 | 2080 | /** |
2081 | * @return string An inline script that creates a JavaScript object storing | |
2082 | * various strings and bits of configuration that the scripts in qengine.js need | |
2083 | * to get from PHP. | |
2084 | */ | |
ddedf979 | 2085 | function question_init_qengine_js() { |
2086 | global $CFG, $PAGE, $OUTPUT; | |
ff065f96 TH |
2087 | static $done = false; |
2088 | if ($done) { | |
2089 | return; | |
2090 | } | |
2091 | $module = array( | |
2092 | 'name' => 'core_question_flags', | |
2093 | 'fullpath' => '/question/flags.js', | |
2094 | 'requires' => array('base', 'dom', 'event-delegate', 'io-base'), | |
2095 | ); | |
2096 | $actionurl = $CFG->wwwroot . '/question/toggleflag.php'; | |
2097 | $flagattributes = array( | |
2098 | 0 => array( | |
2099 | 'src' => $OUTPUT->pix_url('i/unflagged') . '', | |
2100 | 'title' => get_string('clicktoflag', 'question'), | |
2101 | 'alt' => get_string('notflagged', 'question'), | |
2102 | ), | |
2103 | 1 => array( | |
2104 | 'src' => $OUTPUT->pix_url('i/flagged') . '', | |
2105 | 'title' => get_string('clicktounflag', 'question'), | |
2106 | 'alt' => get_string('flagged', 'question'), | |
2107 | ), | |
62e76c67 | 2108 | ); |
ff065f96 TH |
2109 | $PAGE->requires->js_init_call('M.core_question_flags.init', |
2110 | array($actionurl, $flagattributes), false, $module); | |
2111 | $done = true; | |
62e76c67 | 2112 | } |
2113 | ||
516cf3eb | 2114 | /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS ////////////////////////////////// |
99ba746d | 2115 | /** |
25ddb7ef | 2116 | * Give the questions in $questionlist a chance to request the CSS or JavaScript |
2117 | * they need, before the header is printed. | |
2118 | * | |
2119 | * If your code is going to call the print_question function, it must call this | |
2120 | * funciton before print_header. | |
99ba746d | 2121 | * |
2122 | * @param array $questionlist a list of questionids of the questions what will appear on this page. | |
2123 | * @param array $questions an array of question objects, whose keys are question ids. | |
2124 | * Must contain all the questions in $questionlist | |
2125 | * @param array $states an array of question state objects, whose keys are question ids. | |
2126 | * Must contain the state of all the questions in $questionlist | |
99ba746d | 2127 | */ |
ff065f96 | 2128 | function question_get_html_head_contributions($questionlist, &$questions, &$states) { |
c28bf5c9 | 2129 | global $CFG, $PAGE, $QTYPES; |
62e76c67 | 2130 | |
2131 | // The question engine's own JavaScript. | |
ddedf979 | 2132 | question_init_qengine_js(); |
516cf3eb | 2133 | |
62e76c67 | 2134 | // Anything that questions on this page need. |
99ba746d | 2135 | foreach ($questionlist as $questionid) { |
2136 | $question = $questions[$questionid]; | |
34a2777c | 2137 | $QTYPES[$question->qtype]->get_html_head_contributions($question, $states[$questionid]); |
99ba746d | 2138 | } |
99ba746d | 2139 | } |
2140 | ||
50da63eb | 2141 | /** |
25ddb7ef | 2142 | * Like {@link get_html_head_contributions()} but for the editing page |
50da63eb | 2143 | * question/question.php. |
2144 | * | |
2145 | * @param $question A question object. Only $question->qtype is used. | |
25ddb7ef | 2146 | * @return string Deprecated. Some HTML code that can go inside the head tag. |
50da63eb | 2147 | */ |
ff065f96 | 2148 | function question_get_editing_head_contributions($question) { |
50da63eb | 2149 | global $QTYPES; |
34a2777c | 2150 | $QTYPES[$question->qtype]->get_editing_head_contributions(); |
50da63eb | 2151 | } |
2152 | ||
99ba746d | 2153 | /** |
4dca7e51 | 2154 | * Prints a question |
2155 | * | |
2156 | * Simply calls the question type specific print_question() method. | |
50fcb1d8 | 2157 | * |
2158 | * @global array | |
4dca7e51 | 2159 | * @param object $question The question to be rendered. |
2160 | * @param object $state The state to render the question in. | |
2161 | * @param integer $number The number for this question. | |
2162 | * @param object $cmoptions The options specified by the course module | |
2163 | * @param object $options An object specifying the rendering options. | |
2164 | */ | |
4f48fb42 | 2165 | function print_question(&$question, &$state, $number, $cmoptions, $options=null) { |
f02c6f01 | 2166 | global $QTYPES; |
426091ee | 2167 | $QTYPES[$question->qtype]->print_question($question, $state, $number, $cmoptions, $options); |
516cf3eb | 2168 | } |
f5565b69 | 2169 | /** |
99ba746d | 2170 | * Saves question options |
2171 | * | |
2172 | * Simply calls the question type specific save_question_options() method. | |
50fcb1d8 | 2173 | * |
2174 | * @global array | |
99ba746d | 2175 | */ |
f5565b69 | 2176 | function save_question_options($question) { |
2177 | global $QTYPES; | |
2178 | ||
2179 | $QTYPES[$question->qtype]->save_question_options($question); | |
2180 | } | |
516cf3eb | 2181 | |
2182 | /** | |
2183 | * Gets all teacher stored answers for a given question | |
2184 | * | |
2185 | * Simply calls the question type specific get_all_responses() method. | |
50fcb1d8 | 2186 | * |
2187 | * @global array | |
516cf3eb | 2188 | */ |
2189 | // ULPGC ecastro | |
4f48fb42 | 2190 | function get_question_responses($question, $state) { |
f02c6f01 | 2191 | global $QTYPES; |
2192 | $r = $QTYPES[$question->qtype]->get_all_responses($question, $state); | |
516cf3eb | 2193 | return $r; |
2194 | } | |
2195 | ||
516cf3eb | 2196 | /** |
dc1f00de | 2197 | * Gets the response given by the user in a particular state |
516cf3eb | 2198 | * |
2199 | * Simply calls the question type specific get_actual_response() method. | |
50fcb1d8 | 2200 | * |
2201 | * @global array | |
516cf3eb | 2202 | */ |
2203 | // ULPGC ecastro | |
4f48fb42 | 2204 | function get_question_actual_response($question, $state) { |
f02c6f01 | 2205 | global $QTYPES; |
516cf3eb | 2206 | |
f02c6f01 | 2207 | $r = $QTYPES[$question->qtype]->get_actual_response($question, $state); |
516cf3eb | 2208 | return $r; |
2209 | } | |
2210 | ||
2211 | /** | |
dc1f00de | 2212 | * TODO: document this |
50fcb1d8 | 2213 | * |
2214 | * @global array | |
516cf3eb | 2215 | */ |
2216 | // ULPGc ecastro | |
4f48fb42 | 2217 | function get_question_fraction_grade($question, $state) { |
f02c6f01 | 2218 | global $QTYPES; |
516cf3eb | 2219 | |
f02c6f01 | 2220 | $r = $QTYPES[$question->qtype]->get_fractional_grade($question, $state); |
516cf3eb | 2221 | return $r; |
2222 | } | |
6f51ed72 | 2223 | /** |
50fcb1d8 | 2224 | * @global array |
6f51ed72 | 2225 | * @return integer grade out of 1 that a random guess by a student might score. |
2226 | */ | |
2227 | // ULPGc ecastro | |
455c3efa | 2228 | function question_get_random_guess_score($question) { |
6f51ed72 | 2229 | global $QTYPES; |
117bd748 | 2230 | |
6f51ed72 | 2231 | $r = $QTYPES[$question->qtype]->get_random_guess_score($question); |
2232 | return $r; | |
2233 | } | |
516cf3eb | 2234 | /// CATEGORY FUNCTIONS ///////////////////////////////////////////////////////////////// |
2235 | ||
6cb4910c | 2236 | /** |
2237 | * returns the categories with their names ordered following parent-child relationships | |
2238 | * finally it tries to return pending categories (those being orphaned, whose parent is | |
2239 | * incorrect) to avoid missing any category from original array. | |
50fcb1d8 | 2240 | * |
2241 | * @global object | |
6cb4910c | 2242 | */ |
2243 | function sort_categories_by_tree(&$categories, $id = 0, $level = 1) { | |
eb84a826 | 2244 | global $DB; |
2245 | ||
6cb4910c | 2246 | $children = array(); |
2247 | $keys = array_keys($categories); | |
2248 | ||
2249 | foreach ($keys as $key) { | |
2250 | if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) { | |
2251 | $children[$key] = $categories[$key]; | |
2252 | $categories[$key]->processed = true; | |
2253 | $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1); | |
2254 | } | |
2255 | } | |
2256 | //If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too | |
2257 | if ($level == 1) { | |
2258 | foreach ($keys as $key) { | |
2259 | //If not processed and it's a good candidate to start (because its parent doesn't exist in the course) | |
eb84a826 | 2260 | if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories', array('course'=>$categories[$key]->course, 'id'=>$categories[$key]->parent))) { |
6cb4910c | 2261 | $children[$key] = $categories[$key]; |
2262 | $categories[$key]->processed = true; | |
2263 | $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1); | |
2264 | } | |
2265 | } | |
2266 | } | |
2267 | return $children; | |
2268 | } | |
2269 | ||
2270 | /** | |
062a7522 | 2271 | * Private method, only for the use of add_indented_names(). |
271ffe3f | 2272 | * |
062a7522 | 2273 | * Recursively adds an indentedname field to each category, starting with the category |
271ffe3f | 2274 | * with id $id, and dealing with that category and all its children, and |
062a7522 | 2275 | * return a new array, with those categories in the right order. |
2276 | * | |
271ffe3f | 2277 | * @param array $categories an array of categories which has had childids |
062a7522 | 2278 | * fields added by flatten_category_tree(). Passed by reference for |
2279 | * performance only. It is not modfied. | |
2280 | * @param int $id the category to start the indenting process from. | |
2281 | * @param int $depth the indent depth. Used in recursive calls. | |
2282 | * @return array a new array of categories, in the right order for the tree. | |
6cb4910c | 2283 | */ |
3bee1ead | 2284 | function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) { |
271ffe3f | 2285 | |
062a7522 | 2286 | // Indent the name of this category. |
2287 | $newcategories = array(); | |
2288 | $newcategories[$id] = $categories[$id]; | |
2289 | $newcategories[$id]->indentedname = str_repeat(' ', $depth) . $categories[$id]->name; | |
271ffe3f | 2290 | |
062a7522 | 2291 | // Recursively indent the children. |
2292 | foreach ($categories[$id]->childids as $childid) { | |
3bee1ead | 2293 | if ($childid != $nochildrenof){ |
2294 | $newcategories = $newcategories + flatten_category_tree($categories, $childid, $depth + 1, $nochildrenof); | |
2295 | } | |
6cb4910c | 2296 | } |
271ffe3f | 2297 | |
062a7522 | 2298 | // Remove the childids array that were temporarily added. |
2299 | unset($newcategories[$id]->childids); | |
271ffe3f | 2300 | |
062a7522 | 2301 | return $newcategories; |
6cb4910c | 2302 | } |
2303 | ||
2304 | /** | |
062a7522 | 2305 | * Format categories into an indented list reflecting the tree structure. |
271ffe3f | 2306 | * |
062a7522 | 2307 | * @param array $categories An array of category objects, for example from the. |
2308 | * @return array The formatted list of categories. | |
6cb4910c | 2309 | */ |
3bee1ead | 2310 | function add_indented_names($categories, $nochildrenof = -1) { |
6cb4910c | 2311 | |
271ffe3f | 2312 | // Add an array to each category to hold the child category ids. This array will be removed |
062a7522 | 2313 | // again by flatten_category_tree(). It should not be used outside these two functions. |
2314 | foreach (array_keys($categories) as $id) { | |
2315 | $categories[$id]->childids = array(); | |
6cb4910c | 2316 | } |
2317 | ||
062a7522 | 2318 | // Build the tree structure, and record which categories are top-level. |
271ffe3f | 2319 | // We have to be careful, because the categories array may include published |
062a7522 | 2320 | // categories from other courses, but not their parents. |
2321 | $toplevelcategoryids = array(); | |
2322 | foreach (array_keys($categories) as $id) { | |
2323 | if (!empty($categories[$id]->parent) && array_key_exists($categories[$id]->parent, $categories)) { | |
2324 | $categories[$categories[$id]->parent]->childids[] = $id; | |
2325 | } else { | |
2326 | $toplevelcategoryids[] = $id; | |
6cb4910c | 2327 | } |
2328 | } | |
2329 | ||
062a7522 | 2330 | // Flatten the tree to and add the indents. |
2331 | $newcategories = array(); | |
2332 | foreach ($toplevelcategoryids as $id) { | |
3bee1ead | 2333 | $newcategories = $newcategories + flatten_category_tree($categories, $id, 0, $nochildrenof); |
6cb4910c | 2334 | } |
2335 | ||
062a7522 | 2336 | return $newcategories; |
6cb4910c | 2337 | } |
2dd6d66b | 2338 | |
516cf3eb | 2339 | /** |
062a7522 | 2340 | * Output a select menu of question categories. |
271ffe3f | 2341 | * |
062a7522 | 2342 | * Categories from this course and (optionally) published categories from other courses |
271ffe3f | 2343 | * are included. Optionally, only categories the current user may edit can be included. |
062a7522 | 2344 | * |
2345 | * @param integer $courseid the id of the course to get the categories for. | |
2346 | * @param integer $published if true, include publised categories from other courses. | |
2347 | * @param integer $only_editable if true, exclude categories this user is not allowed to edit. | |
2348 | * @param integer $selected optionally, the id of a category to be selected by default in the dropdown. | |
2349 | */ | |
3bee1ead | 2350 | function question_category_select_menu($contexts, $top = false, $currentcat = 0, $selected = "", $nochildrenof = -1) { |
641454c6 | 2351 | global $OUTPUT; |
3bee1ead | 2352 | $categoriesarray = question_category_options($contexts, $top, $currentcat, false, $nochildrenof); |
3ed998f3 | 2353 | if ($selected) { |
6770330d | 2354 | $choose = ''; |
3ed998f3 | 2355 | } else { |
6770330d | 2356 | $choose = 'choosedots'; |
516cf3eb | 2357 | } |
6770330d PS |
2358 | $options = array(); |
2359 | foreach($categoriesarray as $group=>$opts) { | |
2360 | $options[] = array($group=>$opts); | |
2361 | } | |
2362 | ||
2363 | echo html_writer::select($options, 'category', $selected, $choose); | |
516cf3eb | 2364 | } |
2365 | ||
cca6e300 | 2366 | /** |
50fcb1d8 | 2367 | * @global object |
cca6e300 | 2368 | * @param integer $contextid a context id. |
2369 | * @return object the default question category for that context, or false if none. | |
2370 | */ | |
2371 | function question_get_default_category($contextid) { | |
2372 | global $DB; | |
2373 | $category = $DB->get_records('question_categories', array('contextid' => $contextid),'id','*',0,1); | |
2374 | if (!empty($category)) { | |
2375 | return reset($category); | |
2376 | } else { | |
2377 | return false; | |
2378 | } | |
2379 | } | |
2380 | ||
2381 | /** | |
50fcb1d8 | 2382 | * @global object |
2383 | * @global object | |
cca6e300 | 2384 | * @param object $context a context |
2385 | * @return string A URL for editing questions in this context. | |
2386 | */ | |
2387 | function question_edit_url($context) { | |
2388 | global $CFG, $SITE; | |
2389 | if (!has_any_capability(question_get_question_capabilities(), $context)) { | |
2390 | return false; | |
2391 | } | |
2392 | $baseurl = $CFG->wwwroot . '/question/edit.php?'; | |
2393 | $defaultcategory = question_get_default_category($context->id); | |
2394 | if ($defaultcategory) { | |
bdff6b85 | 2395 | $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&'; |
cca6e300 | 2396 | } |
2397 | switch ($context->contextlevel) { | |
2398 | case CONTEXT_SYSTEM: | |
2399 | return $baseurl . 'courseid=' . $SITE->id; | |
2400 | case CONTEXT_COURSECAT: | |
2401 | // This is nasty, becuase we can only edit questions in a course | |
2402 | // context at the moment, so for now we just return false. | |
2403 | return false; | |
2404 | case CONTEXT_COURSE: | |
2405 | return $baseurl . 'courseid=' . $context->instanceid; | |
2406 | case CONTEXT_MODULE: | |
2407 | return $baseurl . 'cmid=' . $context->instanceid; | |
2408 | } | |
117bd748 | 2409 | |
cca6e300 | 2410 | } |
2411 | ||
8f0f605d | 2412 | /** |
2413 | * Gets the default category in the most specific context. | |
2414 | * If no categories exist yet then default ones are created in all contexts. | |
2415 | * | |
50fcb1d8 | 2416 | * @global object |
8f0f605d | 2417 | * @param array $contexts The context objects for this context and all parent contexts. |
2418 | * @return object The default category - the category in the course context | |
2419 | */ | |
2420 | function question_make_default_categories($contexts) { | |
eb84a826 | 2421 | global $DB; |
353b2d70 | 2422 | static $preferredlevels = array( |
2423 | CONTEXT_COURSE => 4, | |
2424 | CONTEXT_MODULE => 3, | |
2425 | CONTEXT_COURSECAT => 2, | |
2426 | CONTEXT_SYSTEM => 1, | |
2427 | ); | |
eb84a826 | 2428 | |
8f0f605d | 2429 | $toreturn = null; |
353b2d70 | 2430 | $preferredness = 0; |
8f0f605d | 2431 | // If it already exists, just return it. |
2432 | foreach ($contexts as $key => $context) { | |
353b2d70 | 2433 | if (!$exists = $DB->record_exists("question_categories", array('contextid'=>$context->id))) { |
eb84a826 | 2434 | // Otherwise, we need to make one |
2435 | $category = new stdClass; | |
2436 | $contextname = print_context_name($context, false, true); | |
2437 | $category->name = get_string('defaultfor', 'question', $contextname); | |
2438 | $category->info = get_string('defaultinfofor', 'question', $contextname); | |
2439 | $category->contextid = $context->id; | |
2440 | $category->parent = 0; | |
2441 | $category->sortorder = 999; // By default, all categories get this number, and are sorted alphabetically. | |
2442 | $category->stamp = make_unique_id_code(); | |
bf8e93d7 | 2443 | $category->id = $DB->insert_record('question_categories', $category); |
b9bd6da4 | 2444 | } else { |
cca6e300 | 2445 | $category = question_get_default_category($context->id); |
8f0f605d | 2446 | } |
80f7bafd | 2447 | if ($preferredlevels[$context->contextlevel] > $preferredness && |
2448 | has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) { | |
353b2d70 | 2449 | $toreturn = $category; |
2450 | $preferredness = $preferredlevels[$context->contextlevel]; | |
8f0f605d | 2451 | } |
2452 | } | |
2453 | ||
353b2d70 | 2454 | if (!is_null($toreturn)) { |
2455 | $toreturn = clone($toreturn); | |
2456 | } | |
8f0f605d | 2457 | return $toreturn; |
2458 | } | |
2459 | ||
375ed78a | 2460 | /** |
3bee1ead | 2461 | * Get all the category objects, including a count of the number of questions in that category, |
2462 | * for all the categories in the lists $contexts. | |
375ed78a | 2463 | * |
50fcb1d8 | 2464 | * @global object |
3bee1ead | 2465 | * @param mixed $contexts either a single contextid, or a comma-separated list of context ids. |
2466 | * @param string $sortorder used as the ORDER BY clause in the select statement. | |
2467 | * @return array of category objects. | |
375ed78a | 2468 | */ |
3bee1ead | 2469 | function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') { |
eb84a826 | 2470 | global $DB; |
2471 | return $DB->get_records_sql(" | |
630a3dc3 | 2472 | SELECT c.*, (SELECT count(1) FROM {question} q |
eb84a826 | 2473 | WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount |
2474 | FROM {question_categories} c | |
2475 | WHERE c.contextid IN ($contexts) | |
2476 | ORDER BY $sortorder"); | |
3bee1ead | 2477 | } |
3a3c454e | 2478 | |
3bee1ead | 2479 | /** |
2480 | * Output an array of question categories. | |
50fcb1d8 | 2481 | * @global object |
3bee1ead | 2482 | */ |
2483 | function question_category_options($contexts, $top = false, $currentcat = 0, $popupform = false, $nochildrenof = -1) { | |
2484 | global $CFG; | |
2485 | $pcontexts = array(); | |
2486 | foreach($contexts as $context){ | |
2487 | $pcontexts[] = $context->id; | |
61d9b9fc | 2488 | } |
3bee1ead | 2489 | $contextslist = join($pcontexts, ', '); |
2490 | ||
2491 | $categories = get_categories_for_contexts($contextslist); | |
375ed78a | 2492 | |
3bee1ead | 2493 | $categories = question_add_context_in_key($categories); |
2494 | ||
2495 | if ($top){ | |
2496 | $categories = question_add_tops($categories, $pcontexts); | |
2497 | } | |
2498 | $categories = add_indented_names($categories, $nochildrenof); | |
3ed998f3 | 2499 | |
3bee1ead | 2500 | //sort cats out into different contexts |
375ed78a | 2501 | $categoriesarray = array(); |
3bee1ead | 2502 | foreach ($pcontexts as $pcontext){ |
2503 | $contextstring = print_context_name(get_context_instance_by_id($pcontext), true, true); | |
2504 | foreach ($categories as $category) { | |
2505 | if ($category->contextid == $pcontext){ | |
2506 | $cid = $category->id; | |
2507 | if ($currentcat!= $cid || $currentcat==0) { | |
1e05bf54 | 2508 | $countstring = (!empty($category->questioncount))?" ($category->questioncount)":''; |
3bee1ead | 2509 | $categoriesarray[$contextstring][$cid] = $category->indentedname.$countstring; |
2510 | } | |
2511 | } | |
375ed78a | 2512 | } |
2513 | } | |
3bee1ead | 2514 | if ($popupform){ |
2515 | $popupcats = array(); | |
2516 | foreach ($categoriesarray as $contextstring => $optgroup){ | |
94fa6be4 PS |
2517 | $group = array(); |
2518 | foreach ($optgroup as $key=>$value) { | |
78bfb562 PS |
2519 | $key = str_replace($CFG->wwwroot, '', $key); |
2520 | $group[$key] = $value; | |
94fa6be4 PS |
2521 | } |
2522 | $popupcats[] = array($contextstring=>$group); | |
3bee1ead | 2523 | } |
2524 | return $popupcats; | |
2525 | } else { | |
2526 | return $categoriesarray; | |
2527 | } | |
375ed78a | 2528 | } |
2529 | ||
3bee1ead | 2530 | function question_add_context_in_key($categories){ |
2531 | $newcatarray = array(); | |
2532 | foreach ($categories as $id => $category) { | |
2533 | $category->parent = "$category->parent,$category->contextid"; | |
2534 | $category->id = "$category->id,$category->contextid"; | |
2535 | $newcatarray["$id,$category->contextid"] = $category; | |
516cf3eb | 2536 | } |
3bee1ead | 2537 | return $newcatarray; |
2538 | } | |
2539 | function question_add_tops($categories, $pcontexts){ | |
2540 | $topcats = array(); | |
2541 | foreach ($pcontexts as $context){ | |
2542 | $newcat = new object(); | |
2543 | $newcat->id = "0,$context"; | |
2544 | $newcat->name = get_string('top'); | |
2545 | $newcat->parent = -1; | |
2546 | $newcat->contextid = $context; | |
2547 | $topcats["0,$context"] = $newcat; | |
2548 | } | |
2549 | //put topcats in at beginning of array - they'll be sorted into different contexts later. | |
2550 | return array_merge($topcats, $categories); | |
516cf3eb | 2551 | } |
2552 | ||
516cf3eb | 2553 | /** |
b20ea669 | 2554 | * Returns a comma separated list of ids of the category and all subcategories |
50fcb1d8 | 2555 | * @global object |
b20ea669 | 2556 | */ |
dc1f00de | 2557 | function question_categorylist($categoryid) { |
eb84a826 | 2558 | global $DB; |
2559 | ||
516cf3eb | 2560 | // returns a comma separated list of ids of the category and all subcategories |
2561 | $categorylist = $categoryid; | |
df4e2244 | 2562 | if ($subcategories = $DB->get_records('question_categories', array('parent'=>$categoryid), 'sortorder ASC', 'id, 1')) { |
516cf3eb | 2563 | foreach ($subcategories as $subcategory) { |
dc1f00de | 2564 | $categorylist .= ','. question_categorylist($subcategory->id); |
516cf3eb | 2565 | } |
2566 | } | |
2567 | return $categorylist; | |
2568 | } | |
2569 | ||
f5c15407 | 2570 | |
3bee1ead | 2571 | |
516cf3eb | 2572 | |
947217d7 | 2573 | //=========================== |
2574 | // Import/Export Functions | |
2575 | //=========================== | |
2576 | ||
ff4b6492 | 2577 | /** |
2578 | * Get list of available import or export formats | |
50fcb1d8 | 2579 | * |
2580 | * @global object | |
ff4b6492 | 2581 | * @param string $type 'import' if import list, otherwise export list assumed |
271ffe3f | 2582 | * @return array sorted list of import/export formats available |
50fcb1d8 | 2583 | */ |
ff4b6492 | 2584 | function get_import_export_formats( $type ) { |
2585 | ||
2586 | global $CFG; | |
17da2e6f | 2587 | $fileformats = get_plugin_list("qformat"); |
ff4b6492 | 2588 | |
2589 | $fileformatname=array(); | |
947217d7 | 2590 | require_once( "{$CFG->dirroot}/question/format.php" ); |
17da2e6f | 2591 | foreach ($fileformats as $fileformat=>$fdir) { |
2592 | $format_file = "$fdir/format.php"; | |
2593 | if (file_exists($format_file) ) { | |
2594 | require_once($format_file); | |
ff4b6492 | 2595 | } |
2596 | else { | |
2597 | continue; | |
2598 | } | |
70c01adb | 2599 | $classname = "qformat_$fileformat"; |
ff4b6492 | 2600 | $format_class = new $classname(); |
2601 | if ($type=='import') { | |
2602 | $provided = $format_class->provide_import(); | |
2603 | } | |
2604 | else { | |
2605 | $provided = $format_class->provide_export(); | |
2606 | } | |
2607 | if ($provided) { | |
2608 | $formatname = get_string($fileformat, 'quiz'); | |
2609 | if ($formatname == "[[$fileformat]]") { | |
b0ea27b4 | 2610 | $formatname = get_string($fileformat, 'qformat_'.$fileformat); |
2611 | if ($formatname == "[[$fileformat]]") { | |
2612 | $formatname = $fileformat; // Just use the raw folder name | |
2613 | } | |
ff4b6492 | 2614 | } |
2615 | $fileformatnames[$fileformat] = $formatname; | |
2616 | } | |
2617 | } | |
2618 | natcasesort($fileformatnames); | |
2619 | ||
2620 | return $fileformatnames; | |
2621 | } | |
feb60a07 | 2622 | |
2623 | ||
2624 | /** | |
2625 | * Create default export filename | |
2626 | * | |
2627 | * @return string default export filename | |
2628 | * @param object $course | |
2629 | * @param object $category | |
2630 | */ | |
2631 | function default_export_filename($course,$category) { | |
2632 | //Take off some characters in the filename !! | |
2633 | $takeoff = array(" ", ":", "/", "\\", "|"); | |
57f1b914 | 2634 | $export_word = str_replace($takeoff,"_",moodle_strtolower(get_string("exportfilename","quiz"))); |
feb60a07 | 2635 | //If non-translated, use "export" |
2636 | if (substr($export_word,0,1) == "[") { | |
2637 | $export_word= "export"; | |
2638 | } | |
2639 | ||
2640 | //Calculate the date format string | |
2641 | $export_date_format = str_replace(" ","_",get_string("exportnameformat","quiz")); | |
2642 | //If non-translated, use "%Y%m%d-%H%M" | |
2643 | if (substr($export_date_format,0,1) == "[") { | |
2644 | $export_date_format = "%%Y%%m%%d-%%H%%M"; | |
2645 | } | |
2646 | ||
2647 | //Calculate the shortname | |
2648 | $export_shortname = clean_filename($course->shortname); | |
2649 | if (empty($export_shortname) or $export_shortname == '_' ) { | |
2650 | $export_shortname = $course->id; | |
2651 | } | |
2652 | ||
2653 | //Calculate the category name | |
2654 | $export_categoryname = clean_filename($category->name); | |
2655 | ||
2656 | //Calculate the final export filename | |
2657 | //The export word | |
2658 | $export_name = $export_word."-"; | |
2659 | //The shortname | |
57f1b914 | 2660 | $export_name .= moodle_strtolower($export_shortname)."-"; |
feb60a07 | 2661 | //The category name |
57f1b914 | 2662 | $export_name .= moodle_strtolower($export_categoryname)."-"; |
feb60a07 | 2663 | //The date format |
2664 | $export_name .= userdate(time(),$export_date_format,99,false); | |
6c58e198 | 2665 | //Extension is supplied by format later. |
feb60a07 | 2666 | |
2667 | return $export_name; | |
2668 | } | |
50fcb1d8 | 2669 | |
2670 | /** | |
2671 | * @package moodlecore | |
2672 | * @subpackage question | |
2673 | * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} | |
2674 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
2675 | */ | |
3bee1ead | 2676 | class context_to_string_translator{ |
2677 | /** | |
2678 | * @var array used to translate between contextids and strings for this context. | |
2679 | */ | |
2680 | var $contexttostringarray = array(); | |
2681 | ||
2682 | function context_to_string_translator($contexts){ | |
2683 | $this->generate_context_to_string_array($contexts); | |
2684 | } | |
2685 | ||
2686 | function context_to_string($contextid){ | |
2687 | return $this->contexttostringarray[$contextid]; | |
2688 | } | |
2689 | ||
2690 | function string_to_context($contextname){ | |
2691 | $contextid = array_search($contextname, $this->contexttostringarray); | |
2692 | return $contextid; | |
2693 | } | |
2694 | ||
2695 | function generate_context_to_string_array($contexts){ | |
2696 | if (!$this->contexttostringarray){ | |
2697 | $catno = 1; | |
2698 | foreach ($contexts as $context){ | |
2699 | switch ($context->contextlevel){ | |
2700 | case CONTEXT_MODULE : | |
2701 | $contextstring = 'module'; | |
2702 | break; | |
2703 | case CONTEXT_COURSE : | |
2704 | $contextstring = 'course'; | |
2705 | break; | |
2706 | case CONTEXT_COURSECAT : | |
2707 | $contextstring = "cat$catno"; | |
2708 | $catno++; | |
2709 | break; | |
2710 | case CONTEXT_SYSTEM : | |
2711 | $contextstring = 'system'; | |
2712 | break; | |
2713 | } | |
2714 | $this->contexttostringarray[$context->id] = $contextstring; | |
2715 | } | |
2716 | } | |
2717 | } | |
2718 | ||
2719 | } | |
feb60a07 | 2720 | |
cca6e300 | 2721 | /** |
2722 | * @return array all the capabilities that relate to accessing particular questions. | |
2723 | */ | |
2724 | function question_get_question_capabilities() { | |
2725 | return array( | |
2726 | 'moodle/question:add', | |
2727 | 'moodle/question:editmine', | |
2728 | 'moodle/question:editall', | |
2729 | 'moodle/question:viewmine', | |
2730 | 'moodle/question:viewall', | |
2731 | 'moodle/question:usemine', | |
2732 | 'moodle/question:useall', | |
2733 | 'moodle/question:movemine', | |
2734 | 'moodle/question:moveall', | |
2735 | ); | |
2736 | } | |
2737 | ||
2738 | /** | |
2739 | * @return array all the question bank capabilities. | |
2740 | */ | |
2741 | function question_get_all_capabilities() { | |
2742 | $caps = question_get_question_capabilities(); | |
2743 | $caps[] = 'moodle/question:managecategory'; | |
2744 | $caps[] = 'moodle/question:flag'; | |
2745 | return $caps; | |
2746 | } | |
3bee1ead | 2747 | |
2748 | /** | |
2749 | * Check capability on category | |
50fcb1d8 | 2750 | * |
2751 | * @global object | |
2752 | * @global object | |
3bee1ead | 2753 | * @param mixed $question object or id |
2754 | * @param string $cap 'add', 'edit', 'view', 'use', 'move' | |
2755 | * @param integer $cachecat useful to cache all question records in a category | |
2756 | * @return boolean this user has the capability $cap for this question $question? | |
2757 | */ | |
2758 | function question_has_capability_on($question, $cap, $cachecat = -1){ | |
eb84a826 | 2759 | global $USER, $DB; |
2760 | ||
415f8c3e | 2761 | // nicolasconnault@gmail.com In some cases I get $question === false. Since no such object exists, it can't be deleted, we can safely return true |
2762 | if ($question === false) { | |
2763 | return true; | |
2764 | } | |
2765 | ||
3bee1ead | 2766 | // these are capabilities on existing questions capabilties are |
2767 | //set per category. Each of these has a mine and all version. Append 'mine' and 'all' | |
2768 | $question_questioncaps = array('edit', 'view', 'use', 'move'); | |
3bee1ead | 2769 | static $questions = array(); |
2770 | static $categories = array(); | |
2771 | static $cachedcat = array(); | |
9f1017a0 | 2772 | if ($cachecat != -1 && (array_search($cachecat, $cachedcat)===FALSE)){ |
eb84a826 | 2773 | $questions += $DB->get_records('question', array('category'=>$cachecat)); |
3bee1ead | 2774 | $cachedcat[] = $cachecat; |
2775 | } | |
2776 | if (!is_object($question)){ | |
2777 | if (!isset($questions[$question])){ | |
f3409e53 | 2778 | if (!$questions[$question] = $DB->get_record('question', array('id'=>$question), 'id,category,createdby')) { |
0f6475b3 | 2779 | print_error('questiondoesnotexist', 'question'); |
3bee1ead | 2780 | } |
2781 | } | |
2782 | $question = $questions[$question]; | |
2783 | } | |
2784 | if (!isset($categories[$question->category])){ | |
eb84a826 | 2785 | if (!$categories[$question->category] = $DB->get_record('question_categories', array('id'=>$question->category))) { |
3bee1ead | 2786 | print_error('invalidcategory', 'quiz'); |
2787 | } | |
2788 | } | |
2789 | $category = $categories[$question->category]; | |
2790 | ||
2791 | if (array_search($cap, $question_questioncaps)!== FALSE){ | |
2792 | if (!has_capability('moodle/question:'.$cap.'all', get_context_instance_by_id($category->contextid))){ | |
2793 | if ($question->createdby == $USER->id){ | |
2794 | return has_capability('moodle/question:'.$cap.'mine', get_context_instance_by_id($category->contextid)); | |
2795 | } else { | |
2796 | return false; | |
2797 | } | |
2798 | } else { | |
2799 | return true; | |
2800 | } | |
2801 | } else { | |
2802 | return has_capability('moodle/question:'.$cap, get_context_instance_by_id($category->contextid)); | |
2803 | } | |
2804 | ||
2805 | } | |
2806 | ||
2807 | /** | |
2808 | * Require capability on question. | |
2809 | */ | |
2810 | function question_require_capability_on($question, $cap){ | |
2811 | if (!question_has_capability_on($question, $cap)){ | |
2812 | print_error('nopermissions', '', '', $cap); | |
2813 | } | |
2814 | return true; | |
2815 | } | |
2816 | ||
50fcb1d8 | 2817 | /** |
2818 | * @global object | |
2819 | */ | |
3bee1ead | 2820 | function question_file_links_base_url($courseid){ |
2821 | global $CFG; | |
2822 | $baseurl = preg_quote("$CFG->wwwroot/file.php", '!'); | |
2823 | $baseurl .= '('.preg_quote('?file=', '!').')?';//may or may not | |
2824 | //be using slasharguments, accept either | |
2825 | $baseurl .= "/$courseid/";//course directory | |
2826 | return $baseurl; | |
2827 | } | |
2828 | ||
50fcb1d8 | 2829 | /** |
3bee1ead | 2830 | * Find all course / site files linked to in a piece of html. |
50fcb1d8 | 2831 | * @global object |
3bee1ead | 2832 | * @param string html the html to search |
2833 | * @param int course search for files for courseid course or set to siteid for | |
2834 | * finding site files. | |
2835 | * @return array files with keys being files. | |
2836 | */ | |
2837 | function question_find_file_links_from_html($html, $courseid){ | |
2838 | global $CFG; | |
2839 | $baseurl = question_file_links_base_url($courseid); | |
2840 | $searchfor = '!'. | |
2841 | '(<\s*(a|img)\s[^>]*(href|src)\s*=\s*")'.$baseurl.'([^"]*)"'. | |
2842 | '|'. | |
2843 | '(<\s*(a|img)\s[^>]*(href|src)\s*=\s*\')'.$baseurl.'([^\']*)\''. | |
2844 | '!i'; | |
2845 | $matches = array(); | |
2846 | $no = preg_match_all($searchfor, $html, $matches); | |
2847 | if ($no){ | |
2848 | $rawurls = array_filter(array_merge($matches[5], $matches[10]));//array_filter removes empty elements | |
2849 | //remove any links that point somewhere they shouldn't | |
2850 | foreach (array_keys($rawurls) as $rawurlkey){ | |
2851 | if (!$cleanedurl = question_url_check($rawurls[$rawurlkey])){ | |
2852 | unset($rawurls[$rawurlkey]); | |
2853 | } else { | |
2854 | $rawurls[$rawurlkey] = $cleanedurl; | |
2855 | } | |
2856 | ||
2857 | } | |
2858 | $urls = array_flip($rawurls);// array_flip removes duplicate files | |
2859 | // and when we merge arrays will continue to automatically remove duplicates | |
2860 | } else { | |
2861 | $urls = array(); | |
2862 | } | |
2863 | return $urls; | |
2864 | } | |
eb84a826 | 2865 | |
2866 | /** | |
3bee1ead | 2867 | * Check that url doesn't point anywhere it shouldn't |
2868 | * | |
50fcb1d8 | 2869 | * @global object |
3bee1ead | 2870 | * @param $url string relative url within course files directory |
2871 | * @return mixed boolean false if not OK or cleaned URL as string if OK | |
2872 | */ | |
2873 | function question_url_check($url){ | |
2874 | global $CFG; | |
2875 | if ((substr(strtolower($url), 0, strlen($CFG->moddata)) == strtolower($CFG->moddata)) || | |
2876 | (substr(strtolower($url), 0, 10) == 'backupdata')){ | |
2877 | return false; | |
2878 | } else { | |
2879 | return clean_param($url, PARAM_PATH); | |
2880 | } | |
2881 | } | |
2882 | ||
eb84a826 | 2883 | /** |
3bee1ead | 2884 | * Find all course / site files linked to in a piece of html. |
50fcb1d8 | 2885 | * |
2886 | * @global object | |
3bee1ead | 2887 | * @param string html the html to search |
2888 | * @param int course search for files for courseid course or set to siteid for | |
2889 | * finding site files. | |
2890 | * @return array files with keys being files. | |
2891 | */ | |
2892 | function question_replace_file_links_in_html($html, $fromcourseid, $tocourseid, $url, $destination, &$changed){ | |
2893 | global $CFG; | |
5a254a29 | 2894 | require_once($CFG->libdir .'/filelib.php'); |
2895 | $tourl = get_file_url("$tocourseid/$destination"); | |
3bee1ead | 2896 | $fromurl = question_file_links_base_url($fromcourseid).preg_quote($url, '!'); |
2897 | $searchfor = array('!(<\s*(a|img)\s[^>]*(href|src)\s*=\s*")'.$fromurl.'(")!i', | |
2898 | '!(<\s*(a|img)\s[^>]*(href|src)\s*=\s*\')'.$fromurl.'(\')!i'); | |
2899 | $newhtml = preg_replace($searchfor, '\\1'.$tourl.'\\5', $html); | |
2900 | if ($newhtml != $html){ | |
2901 | $changed = true; | |
2902 | } | |
2903 | return $newhtml; | |
2904 | } | |
2905 | ||
50fcb1d8 | 2906 | /** |
2907 | * @global object | |
2908 | */ | |
3bee1ead | 2909 | function get_filesdir_from_context($context){ |
eb84a826 | 2910 | global $DB; |
2911 | ||
3bee1ead | 2912 | switch ($context->contextlevel){ |
2913 | case CONTEXT_COURSE : | |
2914 | $courseid = $context->instanceid; | |
2915 | break; | |
2916 | case CONTEXT_MODULE : | |
eb84a826 | 2917 | $courseid = $DB->get_field('course_modules', 'course', array('id'=>$context->instanceid)); |
3bee1ead | 2918 | break; |
2919 | case CONTEXT_COURSECAT : | |
2920 | case CONTEXT_SYSTEM : | |
2921 | $courseid = SITEID; | |
2922 | break; | |
2923 | default : | |
d89ec019 | 2924 | print_error('invalidcontext'); |
3bee1ead | 2925 | } |
2926 | return $courseid; | |
2927 | } | |
4f5ffac0 | 2928 | /** |
43ec99aa | 2929 | * Get the real state - the correct question id and answer - for a random |
2930 | * question. | |
4f5ffac0 | 2931 | * @param object $state with property answer. |
2932 | * @return mixed return integer real question id or false if there was an | |
2933 | * error.. | |
2934 | */ | |
43ec99aa | 2935 | function question_get_real_state($state){ |
aa9a6867 | 2936 | global $OUTPUT; |
43ec99aa | 2937 | $realstate = clone($state); |
4f5ffac0 | 2938 | $matches = array(); |
91ec2c42 | 2939 | if (!preg_match('|^random([0-9]+)-(.*)|', $state->answer, $matches)){ |
aa9a6867 | 2940 | echo $OUTPUT->notification(get_string('errorrandom', 'quiz_statistics')); |
4f5ffac0 | 2941 | return false; |
2942 | } else { | |
43ec99aa | 2943 | $realstate->question = $matches[1]; |
2944 | $realstate->answer = $matches[2]; | |
2945 | return $realstate; | |
4f5ffac0 | 2946 | } |
2947 | } | |
43ec99aa | 2948 | |
62e76c67 | 2949 | /** |
2950 | * Update the flagged state of a particular question session. | |
2951 | * | |
50fcb1d8 | 2952 | * @global object |
62e76c67 | 2953 | * @param integer $sessionid question_session id. |
2954 | * @param boolean $newstate the new state for the flag. | |
2955 | * @return boolean success or failure. | |
2956 | */ | |
2957 | function question_update_flag($sessionid, $newstate) { | |
2958 | global $DB; | |
2959 | return $DB->set_field('question_sessions', 'flagged', $newstate, array('id' => $sessionid)); | |
2960 | } | |
2961 | ||
f62040ed | 2962 | /** |
2963 | * Update the flagged state of all the questions in an attempt, where a new . | |
2964 | * | |
50fcb1d8 | 2965 | * @global object |
f62040ed | 2966 | * @param integer $sessionid question_session id. |
2967 | * @param boolean $newstate the new state for the flag. | |
2968 | * @return boolean success or failure. | |
2969 | */ | |
2970 | function question_save_flags($formdata, $attemptid, $questionids) { | |
2971 | global $DB; | |
2972 | $donequestionids = array(); | |
2973 | foreach ($formdata as $postvariable => $value) { | |
2974 | list($qid, $key) = question_id_and_key_from_post_name($postvariable); | |
2975 | if ($qid !== false && in_array($qid, $questionids)) { | |
2976 | if ($key == '_flagged') { | |
2977 | $DB->set_field('question_sessions', 'flagged', !empty($value), | |
2978 | array('attemptid' => $attemptid, 'questionid' => $qid)); | |
2979 | $donequestionids[$qid] = 1; | |
2980 | } | |
2981 | } | |
2982 | } | |
2983 | foreach ($questionids as $qid) { | |
2984 | if (!isset($donequestionids[$qid])) { | |
2985 | $DB->set_field('question_sessions', 'flagged', 0, | |
2986 | array('attemptid' => $attemptid, 'questionid' => $qid)); | |
2987 | } | |
2988 | } | |
2989 | } | |
2990 | ||
62e76c67 | 2991 | /** |
50fcb1d8 | 2992 | * |
2993 | * @global object | |
62e76c67 | 2994 | * @param integer $attemptid the question_attempt id. |
2995 | * @param integer $questionid the question id. | |
2996 | * @param integer $sessionid the question_session id. | |
2997 | * @param object $user a user, or null to use $USER. | |
2998 | * @return string that needs to be sent to question/toggleflag.php for it to work. | |
2999 | */ | |
3000 | function question_get_toggleflag_checksum($attemptid, $questionid, $sessionid, $user = null) { | |
3001 | if (is_null($user)) { | |
3002 | global $USER; | |
3003 | $user = $USER; | |
3004 | } | |
3005 | return md5($attemptid . "_" . $user->secret . "_" . $questionid . "_" . $sessionid); | |
3006 | } | |
56ed242b SH |
3007 | |
3008 | /** | |
792881f0 | 3009 | * Adds question bank setting links to the given navigation node if caps are met. |
56ed242b SH |
3010 | * |
3011 | * @param navigation_node $navigationnode The navigation node to add the question branch to | |
3012 | * @param stdClass $context | |
3013 | * @return navigation_node Returns the question branch that was added | |
3014 | */ | |
3015 | function question_extend_settings_navigation(navigation_node $navigationnode, $context) { | |
3016 | global $PAGE; | |
3017 | ||
3018 | if ($context->contextlevel == CONTEXT_COURSE) { | |
3019 | $params = array('courseid'=>$context->instanceid); | |
3020 | } else if ($context->contextlevel == CONTEXT_MODULE) { | |
3021 | $params = array('cmid'=>$context->instanceid); | |
3022 | } else { | |
3023 | return; | |
3024 | } | |
3025 | ||
3026 | $questionnode = $navigationnode->add(get_string('questionbank','question'), new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER); | |
3027 | ||
3028 | $contexts = new question_edit_contexts($context); | |
3029 | if ($contexts->have_one_edit_tab_cap('questions')) { | |
3030 | $questionnode->add(get_string('questions', 'quiz'), new moodle_url('/question/edit.php', $params), navigation_node::TYPE_SETTING); | |
3031 | } | |
3032 | if ($contexts->have_one_edit_tab_cap('categories')) { | |
3033 | $questionnode->add(get_string('categories', 'quiz'), new moodle_url('/question/category.php', $params), navigation_node::TYPE_SETTING); | |
3034 | } | |
3035 | if ($contexts->have_one_edit_tab_cap('import')) { | |
3036 | $questionnode->add(get_string('import', 'quiz'), new moodle_url('/question/import.php', $params), navigation_node::TYPE_SETTING); | |
3037 | } | |
3038 | if ($contexts->have_one_edit_tab_cap('export')) { | |
3039 | $questionnode->add(get_string('export', 'quiz'), new moodle_url('/question/export.php', $params), navigation_node::TYPE_SETTING); | |
3040 | } | |
3041 | ||
3042 | return $questionnode; | |
3043 | } | |
3044 | ||
3045 | class question_edit_contexts { | |
3046 | ||
3047 | public static $CAPS = array( | |
3048 | 'editq' => array('moodle/question:add', | |
3049 | 'moodle/question:editmine', | |
3050 | 'moodle/question:editall', | |
3051 | 'moodle/question:viewmine', | |
3052 | 'moodle/question:viewall', | |
3053 | 'moodle/question:usemine', | |
3054 | 'moodle/question:useall', | |
3055 | 'moodle/question:movemine', | |
3056 | 'moodle/question:moveall'), | |
3057 | 'questions'=>array('moodle/question:add', | |
3058 | 'moodle/question:editmine', | |
3059 | 'moodle/question:editall', | |
3060 | 'moodle/question:viewmine', | |
3061 | 'moodle/question:viewall', | |
3062 | 'moodle/question:movemine', | |
3063 | 'moodle/question:moveall'), | |
3064 | 'categories'=>array('moodle/question:managecategory'), | |
3065 | 'import'=>array('moodle/question:add'), | |
3066 | 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine')); | |
3067 | ||
3068 | protected $allcontexts; | |
3069 | ||
3070 | /** | |
3071 | * @param current context | |
3072 | */ | |
3073 | public function question_edit_contexts($thiscontext){ | |
3074 | $pcontextids = get_parent_contexts($thiscontext); | |
3075 | $contexts = array($thiscontext); | |
3076 | foreach ($pcontextids as $pcontextid){ | |
3077 | $contexts[] = get_context_instance_by_id($pcontextid); | |
3078 | } | |
3079 | $this->allcontexts = $contexts; | |
3080 | } | |
3081 | /** | |
3082 | * @return array all parent contexts | |
3083 | */ | |
3084 | public function all(){ | |
3085 | return $this->allcontexts; | |
3086 | } | |
3087 | /** | |
3088 | * @return object lowest context which must be either the module or course context | |
3089 | */ | |
3090 | public function lowest(){ | |
3091 | return $this->allcontexts[0]; | |
3092 | } | |
3093 | /** | |
3094 | * @param string $cap capability | |
3095 | * @return array parent contexts having capability, zero based index | |
3096 | */ | |
3097 | public function having_cap($cap){ | |
3098 | $contextswithcap = array(); | |
3099 | foreach ($this->allcontexts as $context){ | |
3100 | if (has_capability($cap, $context)){ | |
3101 | $contextswithcap[] = $context; | |
3102 | } | |
3103 | } | |
3104 | return $contextswithcap; | |
3105 | } | |
3106 | /** | |
3107 | * @param array $caps capabilities | |
3108 | * @return array parent contexts having at least one of $caps, zero based index | |
3109 | */ | |
3110 | public function having_one_cap($caps){ | |
3111 | $contextswithacap = array(); | |
3112 | foreach ($this->allcontexts as $context){ | |
3113 | foreach ($caps as $cap){ | |
3114 | if (has_capability($cap, $context)){ | |
3115 | $contextswithacap[] = $context; | |
3116 | break; //done with caps loop | |
3117 | } | |
3118 | } | |
3119 | } | |
3120 | return $contextswithacap; | |
3121 | } | |
3122 | /** | |
3123 | * @param string $tabname edit tab name | |
3124 | * @return array parent contexts having at least one of $caps, zero based index | |
3125 | */ | |
3126 | public function having_one_edit_tab_cap($tabname){ | |
3127 | return $this->having_one_cap(self::$CAPS[$tabname]); | |
3128 | } | |
3129 | /** | |
3130 | * Has at least one parent context got the cap $cap? | |
3131 | * | |
3132 | * @param string $cap capability | |
3133 | * @return boolean | |
3134 | */ | |
3135 | public function have_cap($cap){ | |
3136 | return (count($this->having_cap($cap))); | |
3137 | } | |
3138 | ||
3139 | /** | |
3140 | * Has at least one parent context got one of the caps $caps? | |
3141 | * | |
3142 | * @param array $caps capability | |
3143 | * @return boolean | |
3144 | */ | |
3145 | public function have_one_cap($caps){ | |
3146 | foreach ($caps as $cap) { | |
3147 | if ($this->have_cap($cap)) { | |
3148 | return true; | |
3149 | } | |
3150 | } | |
3151 | return false; | |
3152 | } | |
3153 | /** | |
3154 | * Has at least one parent context got one of the caps for actions on $tabname | |
3155 | * | |
3156 | * @param string $tabname edit tab name | |
3157 | * @return boolean | |
3158 | */ | |
3159 | public function have_one_edit_tab_cap($tabname){ | |
3160 | return $this->have_one_cap(self::$CAPS[$tabname]); | |
3161 | } | |
3162 | /** | |
3163 | * Throw error if at least one parent context hasn't got the cap $cap | |
3164 | * | |
3165 | * @param string $cap capability | |
3166 | */ | |
3167 | public function require_cap($cap){ | |
3168 | if (!$this->have_cap($cap)){ | |
3169 | print_error('nopermissions', '', '', $cap); | |
3170 | } | |
3171 | } | |
3172 | /** | |
3173 | * Throw error if at least one parent context hasn't got one of the caps $caps | |
3174 | * | |
3175 | * @param array $cap capabilities | |
3176 | */ | |
3177 | public function require_one_cap($caps) { | |
3178 | if (!$this->have_one_cap($caps)) { | |
3179 | $capsstring = join($caps, ', '); | |
3180 | print_error('nopermissions', '', '', $capsstring); | |
3181 | } | |
3182 | } | |
3183 | ||
3184 | /** | |
3185 | * Throw error if at least one parent context hasn't got one of the caps $caps | |
3186 | * | |
3187 | * @param string $tabname edit tab name | |
3188 | */ | |
3189 | public function require_one_edit_tab_cap($tabname){ | |
3190 | if (!$this->have_one_edit_tab_cap($tabname)) { | |
3191 | print_error('nopermissions', '', '', 'access question edit tab '.$tabname); | |
3192 | } | |
3193 | } | |
3194 | } |