MDL-11082 Improved groups upgrade performance 1.8x -> 1.9; thanks Eloy for telling...
[moodle-pu.git] / lib / questionlib.php
blob68707d3da5d852f32818a8a111afc98917975008
1 <?php // $Id$
2 /**
3 * Code for handling and processing questions
5 * This is code that is module independent, i.e., can be used by any module that
6 * uses questions, like quiz, lesson, ..
7 * This script also loads the questiontype classes
8 * Code for handling the editing of questions is in {@link question/editlib.php}
10 * TODO: separate those functions which form part of the API
11 * from the helper functions.
13 * @author Martin Dougiamas and many others. This has recently been completely
14 * rewritten by Alex Smith, Julian Sedding and Gustav Delius as part of
15 * the Serving Mathematics project
16 * {@link http://maths.york.ac.uk/serving_maths}
17 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
18 * @package question
21 /// CONSTANTS ///////////////////////////////////
23 /**#@+
24 * The different types of events that can create question states
26 define('QUESTION_EVENTOPEN', '0'); // The state was created by Moodle
27 define('QUESTION_EVENTNAVIGATE', '1'); // The responses were saved because the student navigated to another page (this is not currently used)
28 define('QUESTION_EVENTSAVE', '2'); // The student has requested that the responses should be saved but not submitted or validated
29 define('QUESTION_EVENTGRADE', '3'); // Moodle has graded the responses. A SUBMIT event can be changed to a GRADE event by Moodle.
30 define('QUESTION_EVENTDUPLICATE', '4'); // The responses submitted were the same as previously
31 define('QUESTION_EVENTVALIDATE', '5'); // The student has requested a validation. This causes the responses to be saved as well, but not graded.
32 define('QUESTION_EVENTCLOSEANDGRADE', '6'); // Moodle has graded the responses. A CLOSE event can be changed to a CLOSEANDGRADE event by Moodle.
33 define('QUESTION_EVENTSUBMIT', '7'); // The student response has been submitted but it has not yet been marked
34 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.
35 define('QUESTION_EVENTMANUALGRADE', '9'); // Grade was entered by teacher
36 /**#@-*/
38 /**#@+
39 * The core question types.
41 define("SHORTANSWER", "shortanswer");
42 define("TRUEFALSE", "truefalse");
43 define("MULTICHOICE", "multichoice");
44 define("RANDOM", "random");
45 define("MATCH", "match");
46 define("RANDOMSAMATCH", "randomsamatch");
47 define("DESCRIPTION", "description");
48 define("NUMERICAL", "numerical");
49 define("MULTIANSWER", "multianswer");
50 define("CALCULATED", "calculated");
51 define("ESSAY", "essay");
52 /**#@-*/
54 /**
55 * Constant determines the number of answer boxes supplied in the editing
56 * form for multiple choice and similar question types.
58 define("QUESTION_NUMANS", "10");
60 /**
61 * Constant determines the number of answer boxes supplied in the editing
62 * form for multiple choice and similar question types to start with, with
63 * the option of adding QUESTION_NUMANS_ADD more answers.
65 define("QUESTION_NUMANS_START", 3);
67 /**
68 * Constant determines the number of answer boxes to add in the editing
69 * form for multiple choice and similar question types when the user presses
70 * 'add form fields button'.
72 define("QUESTION_NUMANS_ADD", 3);
74 /**
75 * The options used when popping up a question preview window in Javascript.
77 define('QUESTION_PREVIEW_POPUP_OPTIONS', 'scrollbars=yes,resizable=yes,width=700,height=540');
79 /**#@+
80 * Option flags for ->optionflags
81 * The options are read out via bitwise operation using these constants
83 /**
84 * Whether the questions is to be run in adaptive mode. If this is not set then
85 * a question closes immediately after the first submission of responses. This
86 * is how question is Moodle always worked before version 1.5
88 define('QUESTION_ADAPTIVE', 1);
90 /**
91 * options used in forms that move files.
94 define('QUESTION_FILENOTHINGSELECTED', 0);
95 define('QUESTION_FILEDONOTHING', 1);
96 define('QUESTION_FILECOPY', 2);
97 define('QUESTION_FILEMOVE', 3);
98 define('QUESTION_FILEMOVELINKSONLY', 4);
100 /**#@-*/
102 /// QTYPES INITIATION //////////////////
103 // These variables get initialised via calls to question_register_questiontype
104 // as the question type classes are included.
105 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
107 * Array holding question type objects
109 $QTYPES = array();
111 * Array of question types names translated to the user's language
113 * The $QTYPE_MENU array holds the names of all the question types that the user should
114 * be able to create directly. Some internal question types like random questions are excluded.
115 * The complete list of question types can be found in {@link $QTYPES}.
117 $QTYPE_MENU = array();
119 * String in the format "'type1','type2'" that can be used in SQL clauses like
120 * "WHERE q.type IN ($QTYPE_MANUAL)".
122 $QTYPE_MANUAL = '';
124 * String in the format "'type1','type2'" that can be used in SQL clauses like
125 * "WHERE q.type NOT IN ($QTYPE_EXCLUDE_FROM_RANDOM)".
127 $QTYPE_EXCLUDE_FROM_RANDOM = '';
130 * Add a new question type to the various global arrays above.
132 * @param object $qtype An instance of the new question type class.
134 function question_register_questiontype($qtype) {
135 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
137 $name = $qtype->name();
138 $QTYPES[$name] = $qtype;
139 $menuname = $qtype->menu_name();
140 if ($menuname) {
141 $QTYPE_MENU[$name] = $menuname;
143 if ($qtype->is_manual_graded()) {
144 if ($QTYPE_MANUAL) {
145 $QTYPE_MANUAL .= ',';
147 $QTYPE_MANUAL .= "'$name'";
149 if (!$qtype->is_usable_by_random()) {
150 if ($QTYPE_EXCLUDE_FROM_RANDOM) {
151 $QTYPE_EXCLUDE_FROM_RANDOM .= ',';
153 $QTYPE_EXCLUDE_FROM_RANDOM .= "'$name'";
157 require_once("$CFG->dirroot/question/type/questiontype.php");
159 // Load the questiontype.php file for each question type
160 // These files in turn call question_register_questiontype()
161 // with a new instance of each qtype class.
162 $qtypenames= get_list_of_plugins('question/type');
163 foreach($qtypenames as $qtypename) {
164 // Instanciates all plug-in question types
165 $qtypefilepath= "$CFG->dirroot/question/type/$qtypename/questiontype.php";
167 // echo "Loading $qtypename<br/>"; // Uncomment for debugging
168 if (is_readable($qtypefilepath)) {
169 require_once($qtypefilepath);
173 /// OTHER CLASSES /////////////////////////////////////////////////////////
176 * This holds the options that are set by the course module
178 class cmoptions {
180 * Whether a new attempt should be based on the previous one. If true
181 * then a new attempt will start in a state where all responses are set
182 * to the last responses from the previous attempt.
184 var $attemptonlast = false;
187 * Various option flags. The flags are accessed via bitwise operations
188 * using the constants defined in the CONSTANTS section above.
190 var $optionflags = QUESTION_ADAPTIVE;
193 * Determines whether in the calculation of the score for a question
194 * penalties for earlier wrong responses within the same attempt will
195 * be subtracted.
197 var $penaltyscheme = true;
200 * The maximum time the user is allowed to answer the questions withing
201 * an attempt. This is measured in minutes so needs to be multiplied by
202 * 60 before compared to timestamps. If set to 0 no timelimit will be applied
204 var $timelimit = 0;
207 * Timestamp for the closing time. Responses submitted after this time will
208 * be saved but no credit will be given for them.
210 var $timeclose = 9999999999;
213 * The id of the course from withing which the question is currently being used
215 var $course = SITEID;
218 * Whether the answers in a multiple choice question should be randomly
219 * shuffled when a new attempt is started.
221 var $shuffleanswers = true;
224 * The number of decimals to be shown when scores are printed
226 var $decimalpoints = 2;
230 /// FUNCTIONS //////////////////////////////////////////////////////
233 * Returns an array of names of activity modules that use this question
235 * @param object $questionid
236 * @return array of strings
238 function question_list_instances($questionid) {
239 $instances = array();
240 $modules = get_records('modules');
241 foreach ($modules as $module) {
242 $fn = $module->name.'_question_list_instances';
243 if (function_exists($fn)) {
244 $instances = $instances + $fn($questionid);
247 return $instances;
252 * Returns list of 'allowed' grades for grade selection
253 * formatted suitably for dropdown box function
254 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
256 function get_grade_options() {
257 // define basic array of grades
258 $grades = array(
260 0.9,
261 0.8,
262 0.75,
263 0.70,
264 0.66666,
265 0.60,
266 0.50,
267 0.40,
268 0.33333,
269 0.30,
270 0.25,
271 0.20,
272 0.16666,
273 0.142857,
274 0.125,
275 0.11111,
276 0.10,
277 0.05,
280 // iterate through grades generating full range of options
281 $gradeoptionsfull = array();
282 $gradeoptions = array();
283 foreach ($grades as $grade) {
284 $percentage = 100 * $grade;
285 $neggrade = -$grade;
286 $gradeoptions["$grade"] = "$percentage %";
287 $gradeoptionsfull["$grade"] = "$percentage %";
288 $gradeoptionsfull["$neggrade"] = -$percentage." %";
290 $gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
292 // sort lists
293 arsort($gradeoptions, SORT_NUMERIC);
294 arsort($gradeoptionsfull, SORT_NUMERIC);
296 // construct return object
297 $grades = new stdClass;
298 $grades->gradeoptions = $gradeoptions;
299 $grades->gradeoptionsfull = $gradeoptionsfull;
301 return $grades;
305 * match grade options
306 * if no match return error or match nearest
307 * @param array $gradeoptionsfull list of valid options
308 * @param int $grade grade to be tested
309 * @param string $matchgrades 'error' or 'nearest'
310 * @return mixed either 'fixed' value or false if erro
312 function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
313 // if we just need an error...
314 if ($matchgrades=='error') {
315 foreach($gradeoptionsfull as $value => $option) {
316 // slightly fuzzy test, never check floats for equality :-)
317 if (abs($grade-$value)<0.00001) {
318 return $grade;
321 // didn't find a match so that's an error
322 return false;
324 // work out nearest value
325 else if ($matchgrades=='nearest') {
326 $hownear = array();
327 foreach($gradeoptionsfull as $value => $option) {
328 if ($grade==$value) {
329 return $grade;
331 $hownear[ $value ] = abs( $grade - $value );
333 // reverse sort list of deltas and grab the last (smallest)
334 asort( $hownear, SORT_NUMERIC );
335 reset( $hownear );
336 return key( $hownear );
338 else {
339 return false;
344 * Tests whether a category is in use by any activity module
346 * @return boolean
347 * @param integer $categoryid
348 * @param boolean $recursive Whether to examine category children recursively
350 function question_category_isused($categoryid, $recursive = false) {
352 //Look at each question in the category
353 if ($questions = get_records('question', 'category', $categoryid)) {
354 foreach ($questions as $question) {
355 if (count(question_list_instances($question->id))) {
356 return true;
361 //Look under child categories recursively
362 if ($recursive) {
363 if ($children = get_records('question_categories', 'parent', $categoryid)) {
364 foreach ($children as $child) {
365 if (question_category_isused($child->id, $recursive)) {
366 return true;
372 return false;
376 * Deletes all data associated to an attempt from the database
378 * @param integer $attemptid The id of the attempt being deleted
380 function delete_attempt($attemptid) {
381 global $QTYPES;
383 $states = get_records('question_states', 'attempt', $attemptid);
384 if ($states) {
385 $stateslist = implode(',', array_keys($states));
387 // delete question-type specific data
388 foreach ($QTYPES as $qtype) {
389 $qtype->delete_states($stateslist);
393 // delete entries from all other question tables
394 // It is important that this is done only after calling the questiontype functions
395 delete_records("question_states", "attempt", $attemptid);
396 delete_records("question_sessions", "attemptid", $attemptid);
397 delete_records("question_attempts", "id", $attemptid);
401 * Deletes question and all associated data from the database
403 * It will not delete a question if it is used by an activity module
404 * @param object $question The question being deleted
406 function delete_question($questionid) {
407 global $QTYPES;
409 // Do not delete a question if it is used by an activity module
410 if (count(question_list_instances($questionid))) {
411 return;
414 // delete questiontype-specific data
415 $question = get_record('question', 'id', $questionid);
416 question_require_capability_on($question, 'edit');
417 if ($question) {
418 if (isset($QTYPES[$question->qtype])) {
419 $QTYPES[$question->qtype]->delete_question($questionid);
421 } else {
422 echo "Question with id $questionid does not exist.<br />";
425 if ($states = get_records('question_states', 'question', $questionid)) {
426 $stateslist = implode(',', array_keys($states));
428 // delete questiontype-specific data
429 foreach ($QTYPES as $qtype) {
430 $qtype->delete_states($stateslist);
434 // delete entries from all other question tables
435 // It is important that this is done only after calling the questiontype functions
436 delete_records("question_answers", "question", $questionid);
437 delete_records("question_states", "question", $questionid);
438 delete_records("question_sessions", "questionid", $questionid);
440 // Now recursively delete all child questions
441 if ($children = get_records('question', 'parent', $questionid)) {
442 foreach ($children as $child) {
443 if ($child->id != $questionid) {
444 delete_question($child->id);
449 // Finally delete the question record itself
450 delete_records('question', 'id', $questionid);
452 return;
456 * All question categories and their questions are deleted for this course.
458 * @param object $mod an object representing the activity
459 * @param boolean $feedback to specify if the process must output a summary of its work
460 * @return boolean
462 function question_delete_course($course, $feedback=true) {
463 //To store feedback to be showed at the end of the process
464 $feedbackdata = array();
466 //Cache some strings
467 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
468 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
469 $categoriescourse = get_records('question_categories', 'contextid', $coursecontext->id, 'parent', 'id, parent, name');
471 if ($categoriescourse) {
473 //Sort categories following their tree (parent-child) relationships
474 //this will make the feedback more readable
475 $categoriescourse = sort_categories_by_tree($categoriescourse);
477 foreach ($categoriescourse as $category) {
479 //Delete it completely (questions and category itself)
480 //deleting questions
481 if ($questions = get_records("question", "category", $category->id)) {
482 foreach ($questions as $question) {
483 delete_question($question->id);
485 delete_records("question", "category", $category->id);
487 //delete the category
488 delete_records('question_categories', 'id', $category->id);
490 //Fill feedback
491 $feedbackdata[] = array($category->name, $strcatdeleted);
493 //Inform about changes performed if feedback is enabled
494 if ($feedback) {
495 $table = new stdClass;
496 $table->head = array(get_string('category','quiz'), get_string('action'));
497 $table->data = $feedbackdata;
498 print_table($table);
501 return true;
505 * All question categories and their questions are deleted for this activity.
507 * @param object $cm the course module object representing the activity
508 * @param boolean $feedback to specify if the process must output a summary of its work
509 * @return boolean
511 function question_delete_activity($cm, $feedback=true) {
512 //To store feedback to be showed at the end of the process
513 $feedbackdata = array();
515 //Cache some strings
516 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
517 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
518 if ($categoriesmods = get_records('question_categories', 'contextid', $modcontext->id, 'parent', 'id, parent, name')){
519 //Sort categories following their tree (parent-child) relationships
520 //this will make the feedback more readable
521 $categoriesmods = sort_categories_by_tree($categoriesmods);
523 foreach ($categoriesmods as $category) {
525 //Delete it completely (questions and category itself)
526 //deleting questions
527 if ($questions = get_records("question", "category", $category->id)) {
528 foreach ($questions as $question) {
529 delete_question($question->id);
531 delete_records("question", "category", $category->id);
533 //delete the category
534 delete_records('question_categories', 'id', $category->id);
536 //Fill feedback
537 $feedbackdata[] = array($category->name, $strcatdeleted);
539 //Inform about changes performed if feedback is enabled
540 if ($feedback) {
541 $table = new stdClass;
542 $table->head = array(get_string('category','quiz'), get_string('action'));
543 $table->data = $feedbackdata;
544 print_table($table);
547 return true;
550 * @param array $row tab objects
551 * @param question_edit_contexts $contexts object representing contexts available from this context
552 * @param string $querystring to append to urls
553 * */
554 function questionbank_navigation_tabs(&$row, $contexts, $querystring) {
555 global $CFG, $QUESTION_EDITTABCAPS;
556 $tabs = array(
557 'questions' =>array("$CFG->wwwroot/question/edit.php?$querystring", get_string('questions', 'quiz'), get_string('editquestions', 'quiz')),
558 'categories' =>array("$CFG->wwwroot/question/category.php?$querystring", get_string('categories', 'quiz'), get_string('editqcats', 'quiz')),
559 'import' =>array("$CFG->wwwroot/question/import.php?$querystring", get_string('import', 'quiz'), get_string('importquestions', 'quiz')),
560 'export' =>array("$CFG->wwwroot/question/export.php?$querystring", get_string('export', 'quiz'), get_string('exportquestions', 'quiz')));
561 foreach ($tabs as $tabname => $tabparams){
562 if ($contexts->have_one_edit_tab_cap($tabname)) {
563 $row[] = new tabobject($tabname, $tabparams[0], $tabparams[1], $tabparams[2]);
569 * Private function to factor common code out of get_question_options().
571 * @param object $question the question to tidy.
572 * @return boolean true if successful, else false.
574 function _tidy_question(&$question) {
575 global $QTYPES;
576 if (!array_key_exists($question->qtype, $QTYPES)) {
577 $question->qtype = 'missingtype';
578 $question->questiontext = '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext;
580 $question->name_prefix = question_make_name_prefix($question->id);
581 return $QTYPES[$question->qtype]->get_question_options($question);
585 * Updates the question objects with question type specific
586 * information by calling {@link get_question_options()}
588 * Can be called either with an array of question objects or with a single
589 * question object.
591 * @param mixed $questions Either an array of question objects to be updated
592 * or just a single question object
593 * @return bool Indicates success or failure.
595 function get_question_options(&$questions) {
596 if (is_array($questions)) { // deal with an array of questions
597 foreach ($questions as $i => $notused) {
598 if (!_tidy_question($questions[$i])) {
599 return false;
602 return true;
603 } else { // deal with single question
604 return _tidy_question($questions);
609 * Loads the most recent state of each question session from the database
610 * or create new one.
612 * For each question the most recent session state for the current attempt
613 * is loaded from the question_states table and the question type specific data and
614 * responses are added by calling {@link restore_question_state()} which in turn
615 * calls {@link restore_session_and_responses()} for each question.
616 * If no states exist for the question instance an empty state object is
617 * created representing the start of a session and empty question
618 * type specific information and responses are created by calling
619 * {@link create_session_and_responses()}.
621 * @return array An array of state objects representing the most recent
622 * states of the question sessions.
623 * @param array $questions The questions for which sessions are to be restored or
624 * created.
625 * @param object $cmoptions
626 * @param object $attempt The attempt for which the question sessions are
627 * to be restored or created.
628 * @param mixed either the id of a previous attempt, if this attmpt is
629 * building on a previous one, or false for a clean attempt.
631 function get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) {
632 global $CFG, $QTYPES;
634 // get the question ids
635 $ids = array_keys($questions);
636 $questionlist = implode(',', $ids);
638 // The question field must be listed first so that it is used as the
639 // array index in the array returned by get_records_sql
640 $statefields = 'n.questionid as question, s.*, n.sumpenalty, n.manualcomment';
641 // Load the newest states for the questions
642 $sql = "SELECT $statefields".
643 " FROM {$CFG->prefix}question_states s,".
644 " {$CFG->prefix}question_sessions n".
645 " WHERE s.id = n.newest".
646 " AND n.attemptid = '$attempt->uniqueid'".
647 " AND n.questionid IN ($questionlist)";
648 $states = get_records_sql($sql);
650 // Load the newest graded states for the questions
651 $sql = "SELECT $statefields".
652 " FROM {$CFG->prefix}question_states s,".
653 " {$CFG->prefix}question_sessions n".
654 " WHERE s.id = n.newgraded".
655 " AND n.attemptid = '$attempt->uniqueid'".
656 " AND n.questionid IN ($questionlist)";
657 $gradedstates = get_records_sql($sql);
659 // loop through all questions and set the last_graded states
660 foreach ($ids as $i) {
661 if (isset($states[$i])) {
662 restore_question_state($questions[$i], $states[$i]);
663 if (isset($gradedstates[$i])) {
664 restore_question_state($questions[$i], $gradedstates[$i]);
665 $states[$i]->last_graded = $gradedstates[$i];
666 } else {
667 $states[$i]->last_graded = clone($states[$i]);
669 } else {
670 // If the new attempt is to be based on a previous attempt get it and clean things
671 // Having lastattemptid filled implies that (should we double check?):
672 // $attempt->attempt > 1 and $cmoptions->attemptonlast and !$attempt->preview
673 if ($lastattemptid) {
674 // find the responses from the previous attempt and save them to the new session
676 // Load the last graded state for the question
677 $statefields = 'n.questionid as question, s.*, n.sumpenalty';
678 $sql = "SELECT $statefields".
679 " FROM {$CFG->prefix}question_states s,".
680 " {$CFG->prefix}question_sessions n".
681 " WHERE s.id = n.newgraded".
682 " AND n.attemptid = '$lastattemptid'".
683 " AND n.questionid = '$i'";
684 if (!$laststate = get_record_sql($sql)) {
685 // Only restore previous responses that have been graded
686 continue;
688 // Restore the state so that the responses will be restored
689 restore_question_state($questions[$i], $laststate);
690 $states[$i] = clone($laststate);
691 } else {
692 // create a new empty state
693 $states[$i] = new object;
694 $states[$i]->question = $i;
695 $states[$i]->responses = array('' => '');
696 $states[$i]->raw_grade = 0;
699 // now fill/overide initial values
700 $states[$i]->attempt = $attempt->uniqueid;
701 $states[$i]->seq_number = 0;
702 $states[$i]->timestamp = $attempt->timestart;
703 $states[$i]->event = ($attempt->timefinish) ? QUESTION_EVENTCLOSE : QUESTION_EVENTOPEN;
704 $states[$i]->grade = 0;
705 $states[$i]->penalty = 0;
706 $states[$i]->sumpenalty = 0;
707 $states[$i]->manualcomment = '';
709 // Prevent further changes to the session from incrementing the
710 // sequence number
711 $states[$i]->changed = true;
713 if ($lastattemptid) {
714 // prepare the previous responses for new processing
715 $action = new stdClass;
716 $action->responses = $laststate->responses;
717 $action->timestamp = $laststate->timestamp;
718 $action->event = QUESTION_EVENTSAVE; //emulate save of questions from all pages MDL-7631
720 // Process these responses ...
721 question_process_responses($questions[$i], $states[$i], $action, $cmoptions, $attempt);
723 // Fix for Bug #5506: When each attempt is built on the last one,
724 // preserve the options from any previous attempt.
725 if ( isset($laststate->options) ) {
726 $states[$i]->options = $laststate->options;
728 } else {
729 // Create the empty question type specific information
730 if (!$QTYPES[$questions[$i]->qtype]->create_session_and_responses(
731 $questions[$i], $states[$i], $cmoptions, $attempt)) {
732 return false;
735 $states[$i]->last_graded = clone($states[$i]);
738 return $states;
743 * Creates the run-time fields for the states
745 * Extends the state objects for a question by calling
746 * {@link restore_session_and_responses()}
747 * @param object $question The question for which the state is needed
748 * @param object $state The state as loaded from the database
749 * @return boolean Represents success or failure
751 function restore_question_state(&$question, &$state) {
752 global $QTYPES;
754 // initialise response to the value in the answer field
755 $state->responses = array('' => addslashes($state->answer));
756 unset($state->answer);
757 $state->manualcomment = isset($state->manualcomment) ? addslashes($state->manualcomment) : '';
759 // Set the changed field to false; any code which changes the
760 // question session must set this to true and must increment
761 // ->seq_number. The save_question_session
762 // function will save the new state object to the database if the field is
763 // set to true.
764 $state->changed = false;
766 // Load the question type specific data
767 return $QTYPES[$question->qtype]
768 ->restore_session_and_responses($question, $state);
773 * Saves the current state of the question session to the database
775 * The state object representing the current state of the session for the
776 * question is saved to the question_states table with ->responses[''] saved
777 * to the answer field of the database table. The information in the
778 * question_sessions table is updated.
779 * The question type specific data is then saved.
780 * @return mixed The id of the saved or updated state or false
781 * @param object $question The question for which session is to be saved.
782 * @param object $state The state information to be saved. In particular the
783 * most recent responses are in ->responses. The object
784 * is updated to hold the new ->id.
786 function save_question_session(&$question, &$state) {
787 global $QTYPES;
788 // Check if the state has changed
789 if (!$state->changed && isset($state->id)) {
790 return $state->id;
792 // Set the legacy answer field
793 $state->answer = isset($state->responses['']) ? $state->responses[''] : '';
795 // Save the state
796 if (!empty($state->update)) { // this forces the old state record to be overwritten
797 update_record('question_states', $state);
798 } else {
799 if (!$state->id = insert_record('question_states', $state)) {
800 unset($state->id);
801 unset($state->answer);
802 return false;
806 // create or update the session
807 if (!$session = get_record('question_sessions', 'attemptid',
808 $state->attempt, 'questionid', $question->id)) {
809 $session->attemptid = $state->attempt;
810 $session->questionid = $question->id;
811 $session->newest = $state->id;
812 // The following may seem weird, but the newgraded field needs to be set
813 // already even if there is no graded state yet.
814 $session->newgraded = $state->id;
815 $session->sumpenalty = $state->sumpenalty;
816 $session->manualcomment = $state->manualcomment;
817 if (!insert_record('question_sessions', $session)) {
818 error('Could not insert entry in question_sessions');
820 } else {
821 $session->newest = $state->id;
822 if (question_state_is_graded($state) or $state->event == QUESTION_EVENTOPEN) {
823 // this state is graded or newly opened, so it goes into the lastgraded field as well
824 $session->newgraded = $state->id;
825 $session->sumpenalty = $state->sumpenalty;
826 $session->manualcomment = $state->manualcomment;
827 } else {
828 $session->manualcomment = addslashes($session->manualcomment);
830 update_record('question_sessions', $session);
833 unset($state->answer);
835 // Save the question type specific state information and responses
836 if (!$QTYPES[$question->qtype]->save_session_and_responses(
837 $question, $state)) {
838 return false;
840 // Reset the changed flag
841 $state->changed = false;
842 return $state->id;
846 * Determines whether a state has been graded by looking at the event field
848 * @return boolean true if the state has been graded
849 * @param object $state
851 function question_state_is_graded($state) {
852 return ($state->event == QUESTION_EVENTGRADE
853 or $state->event == QUESTION_EVENTCLOSEANDGRADE
854 or $state->event == QUESTION_EVENTMANUALGRADE);
858 * Determines whether a state has been closed by looking at the event field
860 * @return boolean true if the state has been closed
861 * @param object $state
863 function question_state_is_closed($state) {
864 return ($state->event == QUESTION_EVENTCLOSE
865 or $state->event == QUESTION_EVENTCLOSEANDGRADE
866 or $state->event == QUESTION_EVENTMANUALGRADE);
871 * Extracts responses from submitted form
873 * This can extract the responses given to one or several questions present on a page
874 * It returns an array with one entry for each question, indexed by question id
875 * Each entry is an object with the properties
876 * ->event The event that has triggered the submission. This is determined by which button
877 * the user has pressed.
878 * ->responses An array holding the responses to an individual question, indexed by the
879 * name of the corresponding form element.
880 * ->timestamp A unix timestamp
881 * @return array array of action objects, indexed by question ids.
882 * @param array $questions an array containing at least all questions that are used on the form
883 * @param array $formdata the data submitted by the form on the question page
884 * @param integer $defaultevent the event type used if no 'mark' or 'validate' is submitted
886 function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE) {
888 $time = time();
889 $actions = array();
890 foreach ($formdata as $key => $response) {
891 // Get the question id from the response name
892 if (false !== ($quid = question_get_id_from_name_prefix($key))) {
893 // check if this is a valid id
894 if (!isset($questions[$quid])) {
895 error('Form contained question that is not in questionids');
898 // Remove the name prefix from the name
899 //decrypt trying
900 $key = substr($key, strlen($questions[$quid]->name_prefix));
901 if (false === $key) {
902 $key = '';
904 // Check for question validate and mark buttons & set events
905 if ($key === 'validate') {
906 $actions[$quid]->event = QUESTION_EVENTVALIDATE;
907 } else if ($key === 'submit') {
908 $actions[$quid]->event = QUESTION_EVENTSUBMIT;
909 } else {
910 $actions[$quid]->event = $defaultevent;
913 // Update the state with the new response
914 $actions[$quid]->responses[$key] = $response;
916 // Set the timestamp
917 $actions[$quid]->timestamp = $time;
920 foreach ($actions as $quid => $notused) {
921 ksort($actions[$quid]->responses);
923 return $actions;
928 * Returns the html for question feedback image.
929 * @param float $fraction value representing the correctness of the user's
930 * response to a question.
931 * @param boolean $selected whether or not the answer is the one that the
932 * user picked.
933 * @return string
935 function question_get_feedback_image($fraction, $selected=true) {
937 global $CFG;
939 if ($fraction >= 1.0) {
940 if ($selected) {
941 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_green_big.gif" '.
942 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
943 } else {
944 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_green_small.gif" '.
945 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
947 } else if ($fraction > 0.0 && $fraction < 1.0) {
948 if ($selected) {
949 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_amber_big.gif" '.
950 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
951 } else {
952 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_amber_small.gif" '.
953 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
955 } else {
956 if ($selected) {
957 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/cross_red_big.gif" '.
958 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
959 } else {
960 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/cross_red_small.gif" '.
961 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
964 return $feedbackimg;
969 * Returns the class name for question feedback.
970 * @param float $fraction value representing the correctness of the user's
971 * response to a question.
972 * @return string
974 function question_get_feedback_class($fraction) {
976 global $CFG;
978 if ($fraction >= 1.0) {
979 $class = 'correct';
980 } else if ($fraction > 0.0 && $fraction < 1.0) {
981 $class = 'partiallycorrect';
982 } else {
983 $class = 'incorrect';
985 return $class;
990 * For a given question in an attempt we walk the complete history of states
991 * and recalculate the grades as we go along.
993 * This is used when a question is changed and old student
994 * responses need to be marked with the new version of a question.
996 * TODO: Make sure this is not quiz-specific
998 * @return boolean Indicates whether the grade has changed
999 * @param object $question A question object
1000 * @param object $attempt The attempt, in which the question needs to be regraded.
1001 * @param object $cmoptions
1002 * @param boolean $verbose Optional. Whether to print progress information or not.
1004 function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false) {
1006 // load all states for this question in this attempt, ordered in sequence
1007 if ($states = get_records_select('question_states',
1008 "attempt = '{$attempt->uniqueid}' AND question = '{$question->id}'",
1009 'seq_number ASC')) {
1010 $states = array_values($states);
1012 // Subtract the grade for the latest state from $attempt->sumgrades to get the
1013 // sumgrades for the attempt without this question.
1014 $attempt->sumgrades -= $states[count($states)-1]->grade;
1016 // Initialise the replaystate
1017 $state = clone($states[0]);
1018 $state->manualcomment = get_field('question_sessions', 'manualcomment', 'attemptid',
1019 $attempt->uniqueid, 'questionid', $question->id);
1020 restore_question_state($question, $state);
1021 $state->sumpenalty = 0.0;
1022 $replaystate = clone($state);
1023 $replaystate->last_graded = $state;
1025 $changed = false;
1026 for($j = 1; $j < count($states); $j++) {
1027 restore_question_state($question, $states[$j]);
1028 $action = new stdClass;
1029 $action->responses = $states[$j]->responses;
1030 $action->timestamp = $states[$j]->timestamp;
1032 // Change event to submit so that it will be reprocessed
1033 if (QUESTION_EVENTCLOSE == $states[$j]->event
1034 or QUESTION_EVENTGRADE == $states[$j]->event
1035 or QUESTION_EVENTCLOSEANDGRADE == $states[$j]->event) {
1036 $action->event = QUESTION_EVENTSUBMIT;
1038 // By default take the event that was saved in the database
1039 } else {
1040 $action->event = $states[$j]->event;
1043 if ($action->event == QUESTION_EVENTMANUALGRADE) {
1044 question_process_comment($question, $replaystate, $attempt,
1045 $replaystate->manualcomment, $states[$j]->grade);
1046 } else {
1048 // Reprocess (regrade) responses
1049 if (!question_process_responses($question, $replaystate,
1050 $action, $cmoptions, $attempt)) {
1051 $verbose && notify("Couldn't regrade state #{$state->id}!");
1055 // We need rounding here because grades in the DB get truncated
1056 // e.g. 0.33333 != 0.3333333, but we want them to be equal here
1057 if ((round((float)$replaystate->raw_grade, 5) != round((float)$states[$j]->raw_grade, 5))
1058 or (round((float)$replaystate->penalty, 5) != round((float)$states[$j]->penalty, 5))
1059 or (round((float)$replaystate->grade, 5) != round((float)$states[$j]->grade, 5))) {
1060 $changed = true;
1063 $replaystate->id = $states[$j]->id;
1064 $replaystate->changed = true;
1065 $replaystate->update = true; // This will ensure that the existing database entry is updated rather than a new one created
1066 save_question_session($question, $replaystate);
1068 if ($changed) {
1069 // TODO, call a method in quiz to do this, where 'quiz' comes from
1070 // the question_attempts table.
1071 update_record('quiz_attempts', $attempt);
1074 return $changed;
1076 return false;
1080 * Processes an array of student responses, grading and saving them as appropriate
1082 * @return boolean Indicates success/failure
1083 * @param object $question Full question object, passed by reference
1084 * @param object $state Full state object, passed by reference
1085 * @param object $action object with the fields ->responses which
1086 * is an array holding the student responses,
1087 * ->action which specifies the action, e.g., QUESTION_EVENTGRADE,
1088 * and ->timestamp which is a timestamp from when the responses
1089 * were submitted by the student.
1090 * @param object $cmoptions
1091 * @param object $attempt The attempt is passed by reference so that
1092 * during grading its ->sumgrades field can be updated
1094 function question_process_responses(&$question, &$state, $action, $cmoptions, &$attempt) {
1095 global $QTYPES;
1097 // if no responses are set initialise to empty response
1098 if (!isset($action->responses)) {
1099 $action->responses = array('' => '');
1102 // make sure these are gone!
1103 unset($action->responses['submit'], $action->responses['validate']);
1105 // Check the question session is still open
1106 if (question_state_is_closed($state)) {
1107 return true;
1110 // If $action->event is not set that implies saving
1111 if (! isset($action->event)) {
1112 debugging('Ambiguous action in question_process_responses.' , DEBUG_DEVELOPER);
1113 $action->event = QUESTION_EVENTSAVE;
1115 // If submitted then compare against last graded
1116 // responses, not last given responses in this case
1117 if (question_isgradingevent($action->event)) {
1118 $state->responses = $state->last_graded->responses;
1121 // Check for unchanged responses (exactly unchanged, not equivalent).
1122 // We also have to catch questions that the student has not yet attempted
1123 $sameresponses = $QTYPES[$question->qtype]->compare_responses($question, $action, $state);
1124 if (!empty($state->last_graded) && $state->last_graded->event == QUESTION_EVENTOPEN &&
1125 question_isgradingevent($action->event)) {
1126 $sameresponses = false;
1129 // If the response has not been changed then we do not have to process it again
1130 // unless the attempt is closing or validation is requested
1131 if ($sameresponses and QUESTION_EVENTCLOSE != $action->event
1132 and QUESTION_EVENTVALIDATE != $action->event) {
1133 return true;
1136 // Roll back grading information to last graded state and set the new
1137 // responses
1138 $newstate = clone($state->last_graded);
1139 $newstate->responses = $action->responses;
1140 $newstate->seq_number = $state->seq_number + 1;
1141 $newstate->changed = true; // will assure that it gets saved to the database
1142 $newstate->last_graded = clone($state->last_graded);
1143 $newstate->timestamp = $action->timestamp;
1144 $state = $newstate;
1146 // Set the event to the action we will perform. The question type specific
1147 // grading code may override this by setting it to QUESTION_EVENTCLOSE if the
1148 // attempt at the question causes the session to close
1149 $state->event = $action->event;
1151 if (!question_isgradingevent($action->event)) {
1152 // Grade the response but don't update the overall grade
1153 $QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions);
1155 // Temporary hack because question types are not given enough control over what is going
1156 // on. Used by Opaque questions.
1157 // TODO fix this code properly.
1158 if (!empty($state->believeevent)) {
1159 // If the state was graded we need to ...
1160 if (question_state_is_graded($state)) {
1161 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1163 // update the attempt grade
1164 $attempt->sumgrades -= (float)$state->last_graded->grade;
1165 $attempt->sumgrades += (float)$state->grade;
1167 // and update the last_graded field.
1168 unset($state->last_graded);
1169 $state->last_graded = clone($state);
1170 unset($state->last_graded->changed);
1172 } else {
1173 // Don't allow the processing to change the event type
1174 $state->event = $action->event;
1177 } else { // grading event
1179 // Unless the attempt is closing, we want to work out if the current responses
1180 // (or equivalent responses) were already given in the last graded attempt.
1181 if(QUESTION_EVENTCLOSE != $action->event && QUESTION_EVENTOPEN != $state->last_graded->event &&
1182 $QTYPES[$question->qtype]->compare_responses($question, $state, $state->last_graded)) {
1183 $state->event = QUESTION_EVENTDUPLICATE;
1186 // If we did not find a duplicate or if the attempt is closing, perform grading
1187 if ((!$sameresponses and QUESTION_EVENTDUPLICATE != $state->event) or
1188 QUESTION_EVENTCLOSE == $action->event) {
1190 $QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions);
1191 // Calculate overall grade using correct penalty method
1192 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1195 // If the state was graded we need to ...
1196 if (question_state_is_graded($state)) {
1197 // update the attempt grade
1198 $attempt->sumgrades -= (float)$state->last_graded->grade;
1199 $attempt->sumgrades += (float)$state->grade;
1201 // and update the last_graded field.
1202 unset($state->last_graded);
1203 $state->last_graded = clone($state);
1204 unset($state->last_graded->changed);
1207 $attempt->timemodified = $action->timestamp;
1209 return true;
1213 * Determine if event requires grading
1215 function question_isgradingevent($event) {
1216 return (QUESTION_EVENTSUBMIT == $event || QUESTION_EVENTCLOSE == $event);
1220 * Applies the penalty from the previous graded responses to the raw grade
1221 * for the current responses
1223 * The grade for the question in the current state is computed by subtracting the
1224 * penalty accumulated over the previous graded responses at the question from the
1225 * raw grade. If the timestamp is more than 1 minute beyond the end of the attempt
1226 * the grade is set to zero. The ->grade field of the state object is modified to
1227 * reflect the new grade but is never allowed to decrease.
1228 * @param object $question The question for which the penalty is to be applied.
1229 * @param object $state The state for which the grade is to be set from the
1230 * raw grade and the cumulative penalty from the last
1231 * graded state. The ->grade field is updated by applying
1232 * the penalty scheme determined in $cmoptions to the ->raw_grade and
1233 * ->last_graded->penalty fields.
1234 * @param object $cmoptions The options set by the course module.
1235 * The ->penaltyscheme field determines whether penalties
1236 * for incorrect earlier responses are subtracted.
1238 function question_apply_penalty_and_timelimit(&$question, &$state, $attempt, $cmoptions) {
1239 // TODO. Quiz dependancy. The fact that the attempt that is passed in here
1240 // is from quiz_attempts, and we use things like $cmoptions->timelimit.
1242 // deal with penalty
1243 if ($cmoptions->penaltyscheme) {
1244 $state->grade = $state->raw_grade - $state->sumpenalty;
1245 $state->sumpenalty += (float) $state->penalty;
1246 } else {
1247 $state->grade = $state->raw_grade;
1250 // deal with timelimit
1251 if ($cmoptions->timelimit) {
1252 // We allow for 5% uncertainty in the following test
1253 if ($state->timestamp - $attempt->timestart > $cmoptions->timelimit * 63) {
1254 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id);
1255 if (!has_capability('mod/quiz:ignoretimelimits', get_context_instance(CONTEXT_MODULE, $cm->id),
1256 $attempt->userid, false)) {
1257 $state->grade = 0;
1262 // deal with closing time
1263 if ($cmoptions->timeclose and $state->timestamp > ($cmoptions->timeclose + 60) // allowing 1 minute lateness
1264 and !$attempt->preview) { // ignore closing time for previews
1265 $state->grade = 0;
1268 // Ensure that the grade does not go down
1269 $state->grade = max($state->grade, $state->last_graded->grade);
1273 * Print the icon for the question type
1275 * @param object $question The question object for which the icon is required
1276 * @param boolean $return If true the functions returns the link as a string
1278 function print_question_icon($question, $return = false) {
1279 global $QTYPES, $CFG;
1281 $namestr = $QTYPES[$question->qtype]->menu_name();
1282 $html = '<img src="' . $CFG->wwwroot . '/question/type/' .
1283 $question->qtype . '/icon.gif" alt="' .
1284 $namestr . '" title="' . $namestr . '" />';
1285 if ($return) {
1286 return $html;
1287 } else {
1288 echo $html;
1293 * Returns a html link to the question image if there is one
1295 * @return string The html image tag or the empy string if there is no image.
1296 * @param object $question The question object
1298 function get_question_image($question, $courseid) {
1300 global $CFG;
1301 $img = '';
1303 if ($question->image) {
1305 if (substr(strtolower($question->image), 0, 7) == 'http://') {
1306 $img .= $question->image;
1308 } else if ($CFG->slasharguments) { // Use this method if possible for better caching
1309 $img .= "$CFG->wwwroot/file.php/$courseid/$question->image";
1311 } else {
1312 $img .= "$CFG->wwwroot/file.php?file=/$courseid/$question->image";
1315 return $img;
1318 function question_print_comment_box($question, $state, $attempt, $url) {
1319 global $CFG;
1321 $prefix = 'response';
1322 $usehtmleditor = can_use_richtext_editor();
1323 $grade = round($state->last_graded->grade, 3);
1324 echo '<form method="post" action="'.$url.'">';
1325 include($CFG->dirroot.'/question/comment.html');
1326 echo '<input type="hidden" name="attempt" value="'.$attempt->uniqueid.'" />';
1327 echo '<input type="hidden" name="question" value="'.$question->id.'" />';
1328 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1329 echo '<input type="submit" name="submit" value="'.get_string('save', 'quiz').'" />';
1330 echo '</form>';
1332 if ($usehtmleditor) {
1333 use_html_editor();
1337 function question_process_comment($question, &$state, &$attempt, $comment, $grade) {
1339 // Update the comment and save it in the database
1340 $state->manualcomment = $comment;
1341 if (!set_field('question_sessions', 'manualcomment', $comment, 'attemptid', $attempt->uniqueid, 'questionid', $question->id)) {
1342 error("Cannot save comment");
1345 // Update the attempt if the score has changed.
1346 if (abs($state->last_graded->grade - $grade) > 0.002) {
1347 $attempt->sumgrades = $attempt->sumgrades - $state->last_graded->grade + $grade;
1348 $attempt->timemodified = time();
1349 if (!update_record('quiz_attempts', $attempt)) {
1350 error('Failed to save the current quiz attempt!');
1354 // Update the state if either the score has changed, or this is the first
1355 // manual grade event.
1356 // We don't need to store the modified state in the database, we just need
1357 // to set the $state->changed flag.
1358 if (abs($state->last_graded->grade - $grade) > 0.002 ||
1359 $state->last_graded->event != QUESTION_EVENTMANUALGRADE) {
1361 // We want to update existing state (rather than creating new one) if it
1362 // was itself created by a manual grading event.
1363 $state->update = ($state->event == QUESTION_EVENTMANUALGRADE) ? 1 : 0;
1365 // Update the other parts of the state object.
1366 $state->raw_grade = $grade;
1367 $state->grade = $grade;
1368 $state->penalty = 0;
1369 $state->timestamp = time();
1370 $state->seq_number++;
1371 $state->event = QUESTION_EVENTMANUALGRADE;
1373 // Update the last graded state (don't simplify!)
1374 unset($state->last_graded);
1375 $state->last_graded = clone($state);
1377 // We need to indicate that the state has changed in order for it to be saved.
1378 $state->changed = 1;
1384 * Construct name prefixes for question form element names
1386 * Construct the name prefix that should be used for example in the
1387 * names of form elements created by questions.
1388 * This is called by {@link get_question_options()}
1389 * to set $question->name_prefix.
1390 * This name prefix includes the question id which can be
1391 * extracted from it with {@link question_get_id_from_name_prefix()}.
1393 * @return string
1394 * @param integer $id The question id
1396 function question_make_name_prefix($id) {
1397 return 'resp' . $id . '_';
1401 * Extract question id from the prefix of form element names
1403 * @return integer The question id
1404 * @param string $name The name that contains a prefix that was
1405 * constructed with {@link question_make_name_prefix()}
1407 function question_get_id_from_name_prefix($name) {
1408 if (!preg_match('/^resp([0-9]+)_/', $name, $matches))
1409 return false;
1410 return (integer) $matches[1];
1414 * Returns the unique id for a new attempt
1416 * Every module can keep their own attempts table with their own sequential ids but
1417 * the question code needs to also have a unique id by which to identify all these
1418 * attempts. Hence a module, when creating a new attempt, calls this function and
1419 * stores the return value in the 'uniqueid' field of its attempts table.
1421 function question_new_attempt_uniqueid($modulename='quiz') {
1422 global $CFG;
1423 $attempt = new stdClass;
1424 $attempt->modulename = $modulename;
1425 if (!$id = insert_record('question_attempts', $attempt)) {
1426 error('Could not create new entry in question_attempts table');
1428 return $id;
1432 * Creates a stamp that uniquely identifies this version of the question
1434 * In future we want this to use a hash of the question data to guarantee that
1435 * identical versions have the same version stamp.
1437 * @param object $question
1438 * @return string A unique version stamp
1440 function question_hash($question) {
1441 return make_unique_id_code();
1445 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
1447 * Get the HTML that needs to be included in the head tag when the
1448 * questions in $questionlist are printed in the gives states.
1450 * @param array $questionlist a list of questionids of the questions what will appear on this page.
1451 * @param array $questions an array of question objects, whose keys are question ids.
1452 * Must contain all the questions in $questionlist
1453 * @param array $states an array of question state objects, whose keys are question ids.
1454 * Must contain the state of all the questions in $questionlist
1456 * @return string some HTML code that can go inside the head tag.
1458 function get_html_head_contributions(&$questionlist, &$questions, &$states) {
1459 global $QTYPES;
1461 $contributions = array();
1462 foreach ($questionlist as $questionid) {
1463 $question = $questions[$questionid];
1464 $contributions = array_merge($contributions,
1465 $QTYPES[$question->qtype]->get_html_head_contributions(
1466 $question, $states[$questionid]));
1468 return implode("\n", array_unique($contributions));
1472 * Prints a question
1474 * Simply calls the question type specific print_question() method.
1475 * @param object $question The question to be rendered.
1476 * @param object $state The state to render the question in.
1477 * @param integer $number The number for this question.
1478 * @param object $cmoptions The options specified by the course module
1479 * @param object $options An object specifying the rendering options.
1481 function print_question(&$question, &$state, $number, $cmoptions, $options=null) {
1482 global $QTYPES;
1484 $QTYPES[$question->qtype]->print_question($question, $state, $number,
1485 $cmoptions, $options);
1488 * Saves question options
1490 * Simply calls the question type specific save_question_options() method.
1492 function save_question_options($question) {
1493 global $QTYPES;
1495 $QTYPES[$question->qtype]->save_question_options($question);
1499 * Gets all teacher stored answers for a given question
1501 * Simply calls the question type specific get_all_responses() method.
1503 // ULPGC ecastro
1504 function get_question_responses($question, $state) {
1505 global $QTYPES;
1506 $r = $QTYPES[$question->qtype]->get_all_responses($question, $state);
1507 return $r;
1512 * Gets the response given by the user in a particular state
1514 * Simply calls the question type specific get_actual_response() method.
1516 // ULPGC ecastro
1517 function get_question_actual_response($question, $state) {
1518 global $QTYPES;
1520 $r = $QTYPES[$question->qtype]->get_actual_response($question, $state);
1521 return $r;
1525 * TODO: document this
1527 // ULPGc ecastro
1528 function get_question_fraction_grade($question, $state) {
1529 global $QTYPES;
1531 $r = $QTYPES[$question->qtype]->get_fractional_grade($question, $state);
1532 return $r;
1536 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1539 * returns the categories with their names ordered following parent-child relationships
1540 * finally it tries to return pending categories (those being orphaned, whose parent is
1541 * incorrect) to avoid missing any category from original array.
1543 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1544 $children = array();
1545 $keys = array_keys($categories);
1547 foreach ($keys as $key) {
1548 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1549 $children[$key] = $categories[$key];
1550 $categories[$key]->processed = true;
1551 $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1);
1554 //If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too
1555 if ($level == 1) {
1556 foreach ($keys as $key) {
1557 //If not processed and it's a good candidate to start (because its parent doesn't exist in the course)
1558 if (!isset($categories[$key]->processed) && !record_exists('question_categories', 'course', $categories[$key]->course, 'id', $categories[$key]->parent)) {
1559 $children[$key] = $categories[$key];
1560 $categories[$key]->processed = true;
1561 $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1);
1565 return $children;
1569 * Private method, only for the use of add_indented_names().
1571 * Recursively adds an indentedname field to each category, starting with the category
1572 * with id $id, and dealing with that category and all its children, and
1573 * return a new array, with those categories in the right order.
1575 * @param array $categories an array of categories which has had childids
1576 * fields added by flatten_category_tree(). Passed by reference for
1577 * performance only. It is not modfied.
1578 * @param int $id the category to start the indenting process from.
1579 * @param int $depth the indent depth. Used in recursive calls.
1580 * @return array a new array of categories, in the right order for the tree.
1582 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1584 // Indent the name of this category.
1585 $newcategories = array();
1586 $newcategories[$id] = $categories[$id];
1587 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) . $categories[$id]->name;
1589 // Recursively indent the children.
1590 foreach ($categories[$id]->childids as $childid) {
1591 if ($childid != $nochildrenof){
1592 $newcategories = $newcategories + flatten_category_tree($categories, $childid, $depth + 1, $nochildrenof);
1596 // Remove the childids array that were temporarily added.
1597 unset($newcategories[$id]->childids);
1599 return $newcategories;
1603 * Format categories into an indented list reflecting the tree structure.
1605 * @param array $categories An array of category objects, for example from the.
1606 * @return array The formatted list of categories.
1608 function add_indented_names($categories, $nochildrenof = -1) {
1610 // Add an array to each category to hold the child category ids. This array will be removed
1611 // again by flatten_category_tree(). It should not be used outside these two functions.
1612 foreach (array_keys($categories) as $id) {
1613 $categories[$id]->childids = array();
1616 // Build the tree structure, and record which categories are top-level.
1617 // We have to be careful, because the categories array may include published
1618 // categories from other courses, but not their parents.
1619 $toplevelcategoryids = array();
1620 foreach (array_keys($categories) as $id) {
1621 if (!empty($categories[$id]->parent) && array_key_exists($categories[$id]->parent, $categories)) {
1622 $categories[$categories[$id]->parent]->childids[] = $id;
1623 } else {
1624 $toplevelcategoryids[] = $id;
1628 // Flatten the tree to and add the indents.
1629 $newcategories = array();
1630 foreach ($toplevelcategoryids as $id) {
1631 $newcategories = $newcategories + flatten_category_tree($categories, $id, 0, $nochildrenof);
1634 return $newcategories;
1638 * Output a select menu of question categories.
1640 * Categories from this course and (optionally) published categories from other courses
1641 * are included. Optionally, only categories the current user may edit can be included.
1643 * @param integer $courseid the id of the course to get the categories for.
1644 * @param integer $published if true, include publised categories from other courses.
1645 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1646 * @param integer $selected optionally, the id of a category to be selected by default in the dropdown.
1648 function question_category_select_menu($contexts, $top = false, $currentcat = 0, $selected = "", $nochildrenof = -1) {
1649 $categoriesarray = question_category_options($contexts, $top, $currentcat, false, $nochildrenof);
1650 if ($selected) {
1651 $nothing = '';
1652 } else {
1653 $nothing = 'choose';
1655 choose_from_menu_nested($categoriesarray, 'category', $selected, $nothing);
1659 * Get all the category objects, including a count of the number of questions in that category,
1660 * for all the categories in the lists $contexts.
1662 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1663 * @param string $sortorder used as the ORDER BY clause in the select statement.
1664 * @return array of category objects.
1666 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1667 global $CFG;
1668 return get_records_sql("
1669 SELECT *, (SELECT count(1) FROM {$CFG->prefix}question q
1670 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') as questioncount
1671 FROM {$CFG->prefix}question_categories as c
1672 WHERE c.contextid IN ($contexts)
1673 ORDER BY $sortorder");
1677 * Output an array of question categories.
1679 function question_category_options($contexts, $top = false, $currentcat = 0, $popupform = false, $nochildrenof = -1) {
1680 global $CFG;
1681 $pcontexts = array();
1682 foreach($contexts as $context){
1683 $pcontexts[] = $context->id;
1685 $contextslist = join($pcontexts, ', ');
1687 $categories = get_categories_for_contexts($contextslist);
1689 $categories = question_add_context_in_key($categories);
1691 if ($top){
1692 $categories = question_add_tops($categories, $pcontexts);
1694 $categories = add_indented_names($categories, $nochildrenof);
1696 //sort cats out into different contexts
1697 $categoriesarray = array();
1698 foreach ($pcontexts as $pcontext){
1699 $contextstring = print_context_name(get_context_instance_by_id($pcontext), true, true);
1700 foreach ($categories as $category) {
1701 if ($category->contextid == $pcontext){
1702 $cid = $category->id;
1703 if ($currentcat!= $cid || $currentcat==0) {
1704 $countstring = (!empty($category->questioncount))?" ($category->questioncount)":'';
1705 $categoriesarray[$contextstring][$cid] = $category->indentedname.$countstring;
1710 if ($popupform){
1711 $popupcats = array();
1712 foreach ($categoriesarray as $contextstring => $optgroup){
1713 $popupcats[] = '--'.$contextstring;
1714 $popupcats = array_merge($popupcats, $optgroup);
1715 $popupcats[] = '--';
1717 return $popupcats;
1718 } else {
1719 return $categoriesarray;
1723 function question_add_context_in_key($categories){
1724 $newcatarray = array();
1725 foreach ($categories as $id => $category) {
1726 $category->parent = "$category->parent,$category->contextid";
1727 $category->id = "$category->id,$category->contextid";
1728 $newcatarray["$id,$category->contextid"] = $category;
1730 return $newcatarray;
1732 function question_add_tops($categories, $pcontexts){
1733 $topcats = array();
1734 foreach ($pcontexts as $context){
1735 $newcat = new object();
1736 $newcat->id = "0,$context";
1737 $newcat->name = get_string('top');
1738 $newcat->parent = -1;
1739 $newcat->contextid = $context;
1740 $topcats["0,$context"] = $newcat;
1742 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1743 return array_merge($topcats, $categories);
1747 * Returns a comma separated list of ids of the category and all subcategories
1749 function question_categorylist($categoryid) {
1750 // returns a comma separated list of ids of the category and all subcategories
1751 $categorylist = $categoryid;
1752 if ($subcategories = get_records('question_categories', 'parent', $categoryid, 'sortorder ASC', 'id, id')) {
1753 foreach ($subcategories as $subcategory) {
1754 $categorylist .= ','. question_categorylist($subcategory->id);
1757 return $categorylist;
1763 //===========================
1764 // Import/Export Functions
1765 //===========================
1768 * Get list of available import or export formats
1769 * @param string $type 'import' if import list, otherwise export list assumed
1770 * @return array sorted list of import/export formats available
1772 function get_import_export_formats( $type ) {
1774 global $CFG;
1775 $fileformats = get_list_of_plugins("question/format");
1777 $fileformatname=array();
1778 require_once( "{$CFG->dirroot}/question/format.php" );
1779 foreach ($fileformats as $key => $fileformat) {
1780 $format_file = $CFG->dirroot . "/question/format/$fileformat/format.php";
1781 if (file_exists( $format_file ) ) {
1782 require_once( $format_file );
1784 else {
1785 continue;
1787 $classname = "qformat_$fileformat";
1788 $format_class = new $classname();
1789 if ($type=='import') {
1790 $provided = $format_class->provide_import();
1792 else {
1793 $provided = $format_class->provide_export();
1795 if ($provided) {
1796 $formatname = get_string($fileformat, 'quiz');
1797 if ($formatname == "[[$fileformat]]") {
1798 $formatname = $fileformat; // Just use the raw folder name
1800 $fileformatnames[$fileformat] = $formatname;
1803 natcasesort($fileformatnames);
1805 return $fileformatnames;
1810 * Create default export filename
1812 * @return string default export filename
1813 * @param object $course
1814 * @param object $category
1816 function default_export_filename($course,$category) {
1817 //Take off some characters in the filename !!
1818 $takeoff = array(" ", ":", "/", "\\", "|");
1819 $export_word = str_replace($takeoff,"_",moodle_strtolower(get_string("exportfilename","quiz")));
1820 //If non-translated, use "export"
1821 if (substr($export_word,0,1) == "[") {
1822 $export_word= "export";
1825 //Calculate the date format string
1826 $export_date_format = str_replace(" ","_",get_string("exportnameformat","quiz"));
1827 //If non-translated, use "%Y%m%d-%H%M"
1828 if (substr($export_date_format,0,1) == "[") {
1829 $export_date_format = "%%Y%%m%%d-%%H%%M";
1832 //Calculate the shortname
1833 $export_shortname = clean_filename($course->shortname);
1834 if (empty($export_shortname) or $export_shortname == '_' ) {
1835 $export_shortname = $course->id;
1838 //Calculate the category name
1839 $export_categoryname = clean_filename($category->name);
1841 //Calculate the final export filename
1842 //The export word
1843 $export_name = $export_word."-";
1844 //The shortname
1845 $export_name .= moodle_strtolower($export_shortname)."-";
1846 //The category name
1847 $export_name .= moodle_strtolower($export_categoryname)."-";
1848 //The date format
1849 $export_name .= userdate(time(),$export_date_format,99,false);
1850 //The extension - no extension, supplied by format
1851 // $export_name .= ".txt";
1853 return $export_name;
1855 class context_to_string_translator{
1857 * @var array used to translate between contextids and strings for this context.
1859 var $contexttostringarray = array();
1861 function context_to_string_translator($contexts){
1862 $this->generate_context_to_string_array($contexts);
1865 function context_to_string($contextid){
1866 return $this->contexttostringarray[$contextid];
1869 function string_to_context($contextname){
1870 $contextid = array_search($contextname, $this->contexttostringarray);
1871 return $contextid;
1874 function generate_context_to_string_array($contexts){
1875 if (!$this->contexttostringarray){
1876 $catno = 1;
1877 foreach ($contexts as $context){
1878 switch ($context->contextlevel){
1879 case CONTEXT_MODULE :
1880 $contextstring = 'module';
1881 break;
1882 case CONTEXT_COURSE :
1883 $contextstring = 'course';
1884 break;
1885 case CONTEXT_COURSECAT :
1886 $contextstring = "cat$catno";
1887 $catno++;
1888 break;
1889 case CONTEXT_SYSTEM :
1890 $contextstring = 'system';
1891 break;
1893 $this->contexttostringarray[$context->id] = $contextstring;
1902 * Check capability on category
1903 * @param mixed $question object or id
1904 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1905 * @param integer $cachecat useful to cache all question records in a category
1906 * @return boolean this user has the capability $cap for this question $question?
1908 function question_has_capability_on($question, $cap, $cachecat = -1){
1909 global $USER;
1910 // these are capabilities on existing questions capabilties are
1911 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1912 $question_questioncaps = array('edit', 'view', 'use', 'move');
1913 static $questions = array();
1914 static $categories = array();
1915 static $cachedcat = array();
1916 if ($cachecat != -1 && (array_search($cachecat, $cachedcat)===FALSE)){
1917 $questions += get_records('question', 'category', $cachecat);
1918 $cachedcat[] = $cachecat;
1920 if (!is_object($question)){
1921 if (!isset($questions[$question])){
1922 if (!$questions[$question] = get_record('question', 'id', $question)){
1923 print_error('invalidcategory', 'quiz');
1926 $question = $questions[$question];
1928 if (!isset($categories[$question->category])){
1929 if (!$categories[$question->category] = get_record('question_categories', 'id', $question->category)){
1930 print_error('invalidcategory', 'quiz');
1933 $category = $categories[$question->category];
1935 if (array_search($cap, $question_questioncaps)!== FALSE){
1936 if (!has_capability('moodle/question:'.$cap.'all', get_context_instance_by_id($category->contextid))){
1937 if ($question->createdby == $USER->id){
1938 return has_capability('moodle/question:'.$cap.'mine', get_context_instance_by_id($category->contextid));
1939 } else {
1940 return false;
1942 } else {
1943 return true;
1945 } else {
1946 return has_capability('moodle/question:'.$cap, get_context_instance_by_id($category->contextid));
1952 * Require capability on question.
1954 function question_require_capability_on($question, $cap){
1955 if (!question_has_capability_on($question, $cap)){
1956 print_error('nopermissions', '', '', $cap);
1958 return true;
1961 function question_file_links_base_url($courseid){
1962 global $CFG;
1963 $baseurl = preg_quote("$CFG->wwwroot/file.php", '!');
1964 $baseurl .= '('.preg_quote('?file=', '!').')?';//may or may not
1965 //be using slasharguments, accept either
1966 $baseurl .= "/$courseid/";//course directory
1967 return $baseurl;
1971 * Find all course / site files linked to in a piece of html.
1972 * @param string html the html to search
1973 * @param int course search for files for courseid course or set to siteid for
1974 * finding site files.
1975 * @return array files with keys being files.
1977 function question_find_file_links_from_html($html, $courseid){
1978 global $CFG;
1979 $baseurl = question_file_links_base_url($courseid);
1980 $searchfor = '!'.
1981 '(<\s*(a|img)\s[^>]*(href|src)\s*=\s*")'.$baseurl.'([^"]*)"'.
1982 '|'.
1983 '(<\s*(a|img)\s[^>]*(href|src)\s*=\s*\')'.$baseurl.'([^\']*)\''.
1984 '!i';
1985 $matches = array();
1986 $no = preg_match_all($searchfor, $html, $matches);
1987 if ($no){
1988 $rawurls = array_filter(array_merge($matches[5], $matches[10]));//array_filter removes empty elements
1989 //remove any links that point somewhere they shouldn't
1990 foreach (array_keys($rawurls) as $rawurlkey){
1991 if (!$cleanedurl = question_url_check($rawurls[$rawurlkey])){
1992 unset($rawurls[$rawurlkey]);
1993 } else {
1994 $rawurls[$rawurlkey] = $cleanedurl;
1998 $urls = array_flip($rawurls);// array_flip removes duplicate files
1999 // and when we merge arrays will continue to automatically remove duplicates
2000 } else {
2001 $urls = array();
2003 return $urls;
2006 * Check that url doesn't point anywhere it shouldn't
2008 * @param $url string relative url within course files directory
2009 * @return mixed boolean false if not OK or cleaned URL as string if OK
2011 function question_url_check($url){
2012 global $CFG;
2013 if ((substr(strtolower($url), 0, strlen($CFG->moddata)) == strtolower($CFG->moddata)) ||
2014 (substr(strtolower($url), 0, 10) == 'backupdata')){
2015 return false;
2016 } else {
2017 return clean_param($url, PARAM_PATH);
2022 * Find all course / site files linked to in a piece of html.
2023 * @param string html the html to search
2024 * @param int course search for files for courseid course or set to siteid for
2025 * finding site files.
2026 * @return array files with keys being files.
2028 function question_replace_file_links_in_html($html, $fromcourseid, $tocourseid, $url, $destination, &$changed){
2029 global $CFG;
2030 if ($CFG->slasharguments) { // Use this method if possible for better caching
2031 $tourl = "$CFG->wwwroot/file.php/$tocourseid/$destination";
2033 } else {
2034 $tourl = "$CFG->wwwroot/file.php?file=/$tocourseid/$destination";
2036 $fromurl = question_file_links_base_url($fromcourseid).preg_quote($url, '!');
2037 $searchfor = array('!(<\s*(a|img)\s[^>]*(href|src)\s*=\s*")'.$fromurl.'(")!i',
2038 '!(<\s*(a|img)\s[^>]*(href|src)\s*=\s*\')'.$fromurl.'(\')!i');
2039 $newhtml = preg_replace($searchfor, '\\1'.$tourl.'\\5', $html);
2040 if ($newhtml != $html){
2041 $changed = true;
2043 return $newhtml;
2046 function get_filesdir_from_context($context){
2047 switch ($context->contextlevel){
2048 case CONTEXT_COURSE :
2049 $courseid = $context->instanceid;
2050 break;
2051 case CONTEXT_MODULE :
2052 $courseid = get_field('course_modules', 'course', 'id', $context->instanceid);
2053 break;
2054 case CONTEXT_COURSECAT :
2055 case CONTEXT_SYSTEM :
2056 $courseid = SITEID;
2057 break;
2058 default :
2059 error('Unsupported contextlevel in category record!');
2061 return $courseid;