MDL-10240:
[moodle-linuxchix.git] / lib / questionlib.php
blobbb86cd72f51df0850053e2ea1581ddbd9753cc29
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 /**#@-*/
92 /// QTYPES INITIATION //////////////////
93 // These variables get initialised via calls to question_register_questiontype
94 // as the question type classes are included.
95 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
96 /**
97 * Array holding question type objects
99 $QTYPES = array();
101 * Array of question types names translated to the user's language
103 * The $QTYPE_MENU array holds the names of all the question types that the user should
104 * be able to create directly. Some internal question types like random questions are excluded.
105 * The complete list of question types can be found in {@link $QTYPES}.
107 $QTYPE_MENU = array();
109 * String in the format "'type1','type2'" that can be used in SQL clauses like
110 * "WHERE q.type IN ($QTYPE_MANUAL)".
112 $QTYPE_MANUAL = '';
114 * String in the format "'type1','type2'" that can be used in SQL clauses like
115 * "WHERE q.type NOT IN ($QTYPE_EXCLUDE_FROM_RANDOM)".
117 $QTYPE_EXCLUDE_FROM_RANDOM = '';
120 * Add a new question type to the various global arrays above.
122 * @param object $qtype An instance of the new question type class.
124 function question_register_questiontype($qtype) {
125 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
127 $name = $qtype->name();
128 $QTYPES[$name] = $qtype;
129 $menuname = $qtype->menu_name();
130 if ($menuname) {
131 $QTYPE_MENU[$name] = $menuname;
133 if ($qtype->is_manual_graded()) {
134 if ($QTYPE_MANUAL) {
135 $QTYPE_MANUAL .= ',';
137 $QTYPE_MANUAL .= "'$name'";
139 if (!$qtype->is_usable_by_random()) {
140 if ($QTYPE_EXCLUDE_FROM_RANDOM) {
141 $QTYPE_EXCLUDE_FROM_RANDOM .= ',';
143 $QTYPE_EXCLUDE_FROM_RANDOM .= "'$name'";
147 require_once("$CFG->dirroot/question/type/questiontype.php");
149 // Load the questiontype.php file for each question type
150 // These files in turn call question_register_questiontype()
151 // with a new instance of each qtype class.
152 $qtypenames= get_list_of_plugins('question/type');
153 foreach($qtypenames as $qtypename) {
154 // Instanciates all plug-in question types
155 $qtypefilepath= "$CFG->dirroot/question/type/$qtypename/questiontype.php";
157 // echo "Loading $qtypename<br/>"; // Uncomment for debugging
158 if (is_readable($qtypefilepath)) {
159 require_once($qtypefilepath);
163 /// OTHER CLASSES /////////////////////////////////////////////////////////
166 * This holds the options that are set by the course module
168 class cmoptions {
170 * Whether a new attempt should be based on the previous one. If true
171 * then a new attempt will start in a state where all responses are set
172 * to the last responses from the previous attempt.
174 var $attemptonlast = false;
177 * Various option flags. The flags are accessed via bitwise operations
178 * using the constants defined in the CONSTANTS section above.
180 var $optionflags = QUESTION_ADAPTIVE;
183 * Determines whether in the calculation of the score for a question
184 * penalties for earlier wrong responses within the same attempt will
185 * be subtracted.
187 var $penaltyscheme = true;
190 * The maximum time the user is allowed to answer the questions withing
191 * an attempt. This is measured in minutes so needs to be multiplied by
192 * 60 before compared to timestamps. If set to 0 no timelimit will be applied
194 var $timelimit = 0;
197 * Timestamp for the closing time. Responses submitted after this time will
198 * be saved but no credit will be given for them.
200 var $timeclose = 9999999999;
203 * The id of the course from withing which the question is currently being used
205 var $course = SITEID;
208 * Whether the answers in a multiple choice question should be randomly
209 * shuffled when a new attempt is started.
211 var $shuffleanswers = true;
214 * The number of decimals to be shown when scores are printed
216 var $decimalpoints = 2;
220 /// FUNCTIONS //////////////////////////////////////////////////////
223 * Returns an array of names of activity modules that use this question
225 * @param object $questionid
226 * @return array of strings
228 function question_list_instances($questionid) {
229 $instances = array();
230 $modules = get_records('modules');
231 foreach ($modules as $module) {
232 $fn = $module->name.'_question_list_instances';
233 if (function_exists($fn)) {
234 $instances = $instances + $fn($questionid);
237 return $instances;
242 * Returns list of 'allowed' grades for grade selection
243 * formatted suitably for dropdown box function
244 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
246 function get_grade_options() {
247 // define basic array of grades
248 $grades = array(
250 0.9,
251 0.8,
252 0.75,
253 0.70,
254 0.66666,
255 0.60,
256 0.50,
257 0.40,
258 0.33333,
259 0.30,
260 0.25,
261 0.20,
262 0.16666,
263 0.142857,
264 0.125,
265 0.11111,
266 0.10,
267 0.05,
270 // iterate through grades generating full range of options
271 $gradeoptionsfull = array();
272 $gradeoptions = array();
273 foreach ($grades as $grade) {
274 $percentage = 100 * $grade;
275 $neggrade = -$grade;
276 $gradeoptions["$grade"] = "$percentage %";
277 $gradeoptionsfull["$grade"] = "$percentage %";
278 $gradeoptionsfull["$neggrade"] = -$percentage." %";
280 $gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
282 // sort lists
283 arsort($gradeoptions, SORT_NUMERIC);
284 arsort($gradeoptionsfull, SORT_NUMERIC);
286 // construct return object
287 $grades = new stdClass;
288 $grades->gradeoptions = $gradeoptions;
289 $grades->gradeoptionsfull = $gradeoptionsfull;
291 return $grades;
295 * match grade options
296 * if no match return error or match nearest
297 * @param array $gradeoptionsfull list of valid options
298 * @param int $grade grade to be tested
299 * @param string $matchgrades 'error' or 'nearest'
300 * @return mixed either 'fixed' value or false if erro
302 function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
303 // if we just need an error...
304 if ($matchgrades=='error') {
305 foreach($gradeoptionsfull as $value => $option) {
306 // slightly fuzzy test, never check floats for equality :-)
307 if (abs($grade-$value)<0.00001) {
308 return $grade;
311 // didn't find a match so that's an error
312 return false;
314 // work out nearest value
315 else if ($matchgrades=='nearest') {
316 $hownear = array();
317 foreach($gradeoptionsfull as $value => $option) {
318 if ($grade==$value) {
319 return $grade;
321 $hownear[ $value ] = abs( $grade - $value );
323 // reverse sort list of deltas and grab the last (smallest)
324 asort( $hownear, SORT_NUMERIC );
325 reset( $hownear );
326 return key( $hownear );
328 else {
329 return false;
334 * Tests whether a category is in use by any activity module
336 * @return boolean
337 * @param integer $categoryid
338 * @param boolean $recursive Whether to examine category children recursively
340 function question_category_isused($categoryid, $recursive = false) {
342 //Look at each question in the category
343 if ($questions = get_records('question', 'category', $categoryid)) {
344 foreach ($questions as $question) {
345 if (count(question_list_instances($question->id))) {
346 return true;
351 //Look under child categories recursively
352 if ($recursive) {
353 if ($children = get_records('question_categories', 'parent', $categoryid)) {
354 foreach ($children as $child) {
355 if (question_category_isused($child->id, $recursive)) {
356 return true;
362 return false;
366 * Deletes all data associated to an attempt from the database
368 * @param integer $attemptid The id of the attempt being deleted
370 function delete_attempt($attemptid) {
371 global $QTYPES;
373 $states = get_records('question_states', 'attempt', $attemptid);
374 if ($states) {
375 $stateslist = implode(',', array_keys($states));
377 // delete question-type specific data
378 foreach ($QTYPES as $qtype) {
379 $qtype->delete_states($stateslist);
383 // delete entries from all other question tables
384 // It is important that this is done only after calling the questiontype functions
385 delete_records("question_states", "attempt", $attemptid);
386 delete_records("question_sessions", "attemptid", $attemptid);
387 delete_records("question_attempts", "id", $attemptid);
391 * Deletes question and all associated data from the database
393 * It will not delete a question if it is used by an activity module
394 * @param object $question The question being deleted
396 function delete_question($questionid) {
397 global $QTYPES;
399 // Do not delete a question if it is used by an activity module
400 if (count(question_list_instances($questionid))) {
401 return;
404 // delete questiontype-specific data
405 if ($question = get_record('question', 'id', $questionid)) {
406 if (isset($QTYPES[$question->qtype])) {
407 $QTYPES[$question->qtype]->delete_question($questionid);
409 } else {
410 echo "Question with id $questionid does not exist.<br />";
413 if ($states = get_records('question_states', 'question', $questionid)) {
414 $stateslist = implode(',', array_keys($states));
416 // delete questiontype-specific data
417 foreach ($QTYPES as $qtype) {
418 $qtype->delete_states($stateslist);
422 // delete entries from all other question tables
423 // It is important that this is done only after calling the questiontype functions
424 delete_records("question_answers", "question", $questionid);
425 delete_records("question_states", "question", $questionid);
426 delete_records("question_sessions", "questionid", $questionid);
428 // Now recursively delete all child questions
429 if ($children = get_records('question', 'parent', $questionid)) {
430 foreach ($children as $child) {
431 if ($child->id != $questionid) {
432 delete_question($child->id);
437 // Finally delete the question record itself
438 delete_records('question', 'id', $questionid);
440 return;
444 * All non-used question categories and their questions are deleted and
445 * categories still used by other courses are moved to the site course.
447 * @param object $course an object representing the course
448 * @param boolean $feedback to specify if the process must output a summary of its work
449 * @return boolean
451 function question_delete_course($course, $feedback=true) {
453 global $CFG, $QTYPES;
455 //To detect if we have created the "container category"
456 $concatid = 0;
458 //The "container" category we'll create if we need if
459 $contcat = new object;
461 //To temporary store changes performed with parents
462 $parentchanged = array();
464 //To store feedback to be showed at the end of the process
465 $feedbackdata = array();
467 //Cache some strings
468 $strcatcontainer=get_string('containercategorycreated', 'quiz');
469 $strcatmoved = get_string('usedcategorymoved', 'quiz');
470 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
472 if ($categories = get_records('question_categories', 'course', $course->id, 'parent', 'id, parent, name, course')) {
474 //Sort categories following their tree (parent-child) relationships
475 $categories = sort_categories_by_tree($categories);
477 foreach ($categories as $cat) {
479 //Get the full record
480 $category = get_record('question_categories', 'id', $cat->id);
482 //Check if the category is being used anywhere
483 if(question_category_isused($category->id, true)) {
484 //It's being used. Cannot delete it, so:
485 //Create a container category in SITEID course if it doesn't exist
486 if (!$concatid) {
487 $concat = new stdClass;
488 $concat->course = SITEID;
489 if (!isset($course->shortname)) {
490 $course->shortname = 'id=' . $course->id;
492 $concat->name = get_string('savedfromdeletedcourse', 'quiz', format_string($course->shortname));
493 $concat->info = $concat->name;
494 $concat->publish = 1;
495 $concat->stamp = make_unique_id_code();
496 $concatid = insert_record('question_categories', $concat);
498 //Fill feedback
499 $feedbackdata[] = array($concat->name, $strcatcontainer);
501 //Move the category to the container category in SITEID course
502 $category->course = SITEID;
503 //Assign to container if the category hasn't parent or if the parent is wrong (not belongs to the course)
504 if (!$category->parent || !isset($categories[$category->parent])) {
505 $category->parent = $concatid;
507 //If it's being used, its publish field should be 1
508 $category->publish = 1;
509 //Let's update it
510 update_record('question_categories', $category);
512 //Save this parent change for future use
513 $parentchanged[$category->id] = $category->parent;
515 //Fill feedback
516 $feedbackdata[] = array($category->name, $strcatmoved);
518 } else {
519 //Category isn't being used so:
520 //Delete it completely (questions and category itself)
521 //deleting questions
522 if ($questions = get_records("question", "category", $category->id)) {
523 foreach ($questions as $question) {
524 delete_question($question->id);
526 delete_records("question", "category", $category->id);
528 //delete the category
529 delete_records('question_categories', 'id', $category->id);
531 //Save this parent change for future use
532 if (!empty($category->parent)) {
533 $parentchanged[$category->id] = $category->parent;
534 } else {
535 $parentchanged[$category->id] = $concatid;
538 //Update all its child categories to re-parent them to grandparent.
539 set_field ('question_categories', 'parent', $parentchanged[$category->id], 'parent', $category->id);
541 //Fill feedback
542 $feedbackdata[] = array($category->name, $strcatdeleted);
545 //Inform about changes performed if feedback is enabled
546 if ($feedback) {
547 $table = new stdClass;
548 $table->head = array(get_string('category','quiz'), get_string('action'));
549 $table->data = $feedbackdata;
550 print_table($table);
553 return true;
556 function questionbank_navigation_tabs(&$row, $context, $querystring) {
557 global $CFG;
558 if (has_capability('moodle/question:manage', $context)) {
559 $row[] = new tabobject('questions', "$CFG->wwwroot/question/edit.php?$querystring", get_string('questions', 'quiz'), get_string('editquestions', "quiz"));
562 if (has_capability('moodle/question:managecategory', $context)) {
563 $row[] = new tabobject('categories', "$CFG->wwwroot/question/category.php?$querystring", get_string('categories', 'quiz'), get_string('editqcats', 'quiz'));
566 if (has_capability('moodle/question:import', $context)) {
567 $row[] = new tabobject('import', "$CFG->wwwroot/question/import.php?$querystring", get_string('import', 'quiz'), get_string('importquestions', 'quiz'));
570 if (has_capability('moodle/question:export', $context)) {
571 $row[] = new tabobject('export', "$CFG->wwwroot/question/export.php?$querystring", get_string('export', 'quiz'), get_string('exportquestions', 'quiz'));
576 * Private function to factor common code out of get_question_options().
578 * @param object $question the question to tidy.
579 * @return boolean true if successful, else false.
581 function _tidy_question(&$question) {
582 global $QTYPES;
583 if (!array_key_exists($question->qtype, $QTYPES)) {
584 $question->qtype = 'missingtype';
585 $question->questiontext = '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext;
587 $question->name_prefix = question_make_name_prefix($question->id);
588 return $QTYPES[$question->qtype]->get_question_options($question);
592 * Updates the question objects with question type specific
593 * information by calling {@link get_question_options()}
595 * Can be called either with an array of question objects or with a single
596 * question object.
598 * @param mixed $questions Either an array of question objects to be updated
599 * or just a single question object
600 * @return bool Indicates success or failure.
602 function get_question_options(&$questions) {
603 if (is_array($questions)) { // deal with an array of questions
604 foreach ($questions as $i => $notused) {
605 if (!_tidy_question($questions[$i])) {
606 return false;
609 return true;
610 } else { // deal with single question
611 return _tidy_question($questions);
616 * Loads the most recent state of each question session from the database
617 * or create new one.
619 * For each question the most recent session state for the current attempt
620 * is loaded from the question_states table and the question type specific data and
621 * responses are added by calling {@link restore_question_state()} which in turn
622 * calls {@link restore_session_and_responses()} for each question.
623 * If no states exist for the question instance an empty state object is
624 * created representing the start of a session and empty question
625 * type specific information and responses are created by calling
626 * {@link create_session_and_responses()}.
628 * @return array An array of state objects representing the most recent
629 * states of the question sessions.
630 * @param array $questions The questions for which sessions are to be restored or
631 * created.
632 * @param object $cmoptions
633 * @param object $attempt The attempt for which the question sessions are
634 * to be restored or created.
635 * @param mixed either the id of a previous attempt, if this attmpt is
636 * building on a previous one, or false for a clean attempt.
638 function get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) {
639 global $CFG, $QTYPES;
641 // get the question ids
642 $ids = array_keys($questions);
643 $questionlist = implode(',', $ids);
645 // The question field must be listed first so that it is used as the
646 // array index in the array returned by get_records_sql
647 $statefields = 'n.questionid as question, s.*, n.sumpenalty, n.manualcomment';
648 // Load the newest states for the questions
649 $sql = "SELECT $statefields".
650 " FROM {$CFG->prefix}question_states s,".
651 " {$CFG->prefix}question_sessions n".
652 " WHERE s.id = n.newest".
653 " AND n.attemptid = '$attempt->uniqueid'".
654 " AND n.questionid IN ($questionlist)";
655 $states = get_records_sql($sql);
657 // Load the newest graded states for the questions
658 $sql = "SELECT $statefields".
659 " FROM {$CFG->prefix}question_states s,".
660 " {$CFG->prefix}question_sessions n".
661 " WHERE s.id = n.newgraded".
662 " AND n.attemptid = '$attempt->uniqueid'".
663 " AND n.questionid IN ($questionlist)";
664 $gradedstates = get_records_sql($sql);
666 // loop through all questions and set the last_graded states
667 foreach ($ids as $i) {
668 if (isset($states[$i])) {
669 restore_question_state($questions[$i], $states[$i]);
670 if (isset($gradedstates[$i])) {
671 restore_question_state($questions[$i], $gradedstates[$i]);
672 $states[$i]->last_graded = $gradedstates[$i];
673 } else {
674 $states[$i]->last_graded = clone($states[$i]);
676 } else {
677 // If the new attempt is to be based on a previous attempt get it and clean things
678 // Having lastattemptid filled implies that (should we double check?):
679 // $attempt->attempt > 1 and $cmoptions->attemptonlast and !$attempt->preview
680 if ($lastattemptid) {
681 // find the responses from the previous attempt and save them to the new session
683 // Load the last graded state for the question
684 $statefields = 'n.questionid as question, s.*, n.sumpenalty';
685 $sql = "SELECT $statefields".
686 " FROM {$CFG->prefix}question_states s,".
687 " {$CFG->prefix}question_sessions n".
688 " WHERE s.id = n.newgraded".
689 " AND n.attemptid = '$lastattemptid'".
690 " AND n.questionid = '$i'";
691 if (!$laststate = get_record_sql($sql)) {
692 // Only restore previous responses that have been graded
693 continue;
695 // Restore the state so that the responses will be restored
696 restore_question_state($questions[$i], $laststate);
697 $states[$i] = clone ($laststate);
698 } else {
699 // create a new empty state
700 $states[$i] = new object;
703 // now fill/overide initial values
704 $states[$i]->attempt = $attempt->uniqueid;
705 $states[$i]->question = (int) $i;
706 $states[$i]->seq_number = 0;
707 $states[$i]->timestamp = $attempt->timestart;
708 $states[$i]->event = ($attempt->timefinish) ? QUESTION_EVENTCLOSE : QUESTION_EVENTOPEN;
709 $states[$i]->grade = 0;
710 $states[$i]->raw_grade = 0;
711 $states[$i]->penalty = 0;
712 $states[$i]->sumpenalty = 0;
713 $states[$i]->manualcomment = '';
715 // if building on last attempt we want to preserve responses
716 if (!$lastattemptid) {
717 $states[$i]->responses = array('' => '');
719 // Prevent further changes to the session from incrementing the
720 // sequence number
721 $states[$i]->changed = true;
723 if ($lastattemptid) {
724 // prepare the previous responses for new processing
725 $action = new stdClass;
726 $action->responses = $laststate->responses;
727 $action->timestamp = $laststate->timestamp;
728 $action->event = QUESTION_EVENTSAVE; //emulate save of questions from all pages MDL-7631
730 // Process these responses ...
731 question_process_responses($questions[$i], $states[$i], $action, $cmoptions, $attempt);
733 // Fix for Bug #5506: When each attempt is built on the last one,
734 // preserve the options from any previous attempt.
735 if ( isset($laststate->options) ) {
736 $states[$i]->options = $laststate->options;
738 } else {
739 // Create the empty question type specific information
740 if (!$QTYPES[$questions[$i]->qtype]->create_session_and_responses(
741 $questions[$i], $states[$i], $cmoptions, $attempt)) {
742 return false;
745 $states[$i]->last_graded = clone($states[$i]);
748 return $states;
753 * Creates the run-time fields for the states
755 * Extends the state objects for a question by calling
756 * {@link restore_session_and_responses()}
757 * @param object $question The question for which the state is needed
758 * @param object $state The state as loaded from the database
759 * @return boolean Represents success or failure
761 function restore_question_state(&$question, &$state) {
762 global $QTYPES;
764 // initialise response to the value in the answer field
765 $state->responses = array('' => addslashes($state->answer));
766 unset($state->answer);
767 $state->manualcomment = isset($state->manualcomment) ? addslashes($state->manualcomment) : '';
769 // Set the changed field to false; any code which changes the
770 // question session must set this to true and must increment
771 // ->seq_number. The save_question_session
772 // function will save the new state object to the database if the field is
773 // set to true.
774 $state->changed = false;
776 // Load the question type specific data
777 return $QTYPES[$question->qtype]
778 ->restore_session_and_responses($question, $state);
783 * Saves the current state of the question session to the database
785 * The state object representing the current state of the session for the
786 * question is saved to the question_states table with ->responses[''] saved
787 * to the answer field of the database table. The information in the
788 * question_sessions table is updated.
789 * The question type specific data is then saved.
790 * @return mixed The id of the saved or updated state or false
791 * @param object $question The question for which session is to be saved.
792 * @param object $state The state information to be saved. In particular the
793 * most recent responses are in ->responses. The object
794 * is updated to hold the new ->id.
796 function save_question_session(&$question, &$state) {
797 global $QTYPES;
798 // Check if the state has changed
799 if (!$state->changed && isset($state->id)) {
800 return $state->id;
802 // Set the legacy answer field
803 $state->answer = isset($state->responses['']) ? $state->responses[''] : '';
805 // Save the state
806 if (!empty($state->update)) { // this forces the old state record to be overwritten
807 update_record('question_states', $state);
808 } else {
809 if (!$state->id = insert_record('question_states', $state)) {
810 unset($state->id);
811 unset($state->answer);
812 return false;
816 // create or update the session
817 if (!$session = get_record('question_sessions', 'attemptid',
818 $state->attempt, 'questionid', $question->id)) {
819 $session->attemptid = $state->attempt;
820 $session->questionid = $question->id;
821 $session->newest = $state->id;
822 // The following may seem weird, but the newgraded field needs to be set
823 // already even if there is no graded state yet.
824 $session->newgraded = $state->id;
825 $session->sumpenalty = $state->sumpenalty;
826 $session->manualcomment = $state->manualcomment;
827 if (!insert_record('question_sessions', $session)) {
828 error('Could not insert entry in question_sessions');
830 } else {
831 $session->newest = $state->id;
832 if (question_state_is_graded($state) or $state->event == QUESTION_EVENTOPEN) {
833 // this state is graded or newly opened, so it goes into the lastgraded field as well
834 $session->newgraded = $state->id;
835 $session->sumpenalty = $state->sumpenalty;
836 $session->manualcomment = $state->manualcomment;
837 } else {
838 $session->manualcomment = addslashes($session->manualcomment);
840 update_record('question_sessions', $session);
843 unset($state->answer);
845 // Save the question type specific state information and responses
846 if (!$QTYPES[$question->qtype]->save_session_and_responses(
847 $question, $state)) {
848 return false;
850 // Reset the changed flag
851 $state->changed = false;
852 return $state->id;
856 * Determines whether a state has been graded by looking at the event field
858 * @return boolean true if the state has been graded
859 * @param object $state
861 function question_state_is_graded($state) {
862 return ($state->event == QUESTION_EVENTGRADE
863 or $state->event == QUESTION_EVENTCLOSEANDGRADE
864 or $state->event == QUESTION_EVENTMANUALGRADE);
868 * Determines whether a state has been closed by looking at the event field
870 * @return boolean true if the state has been closed
871 * @param object $state
873 function question_state_is_closed($state) {
874 return ($state->event == QUESTION_EVENTCLOSE
875 or $state->event == QUESTION_EVENTCLOSEANDGRADE
876 or $state->event == QUESTION_EVENTMANUALGRADE);
881 * Extracts responses from submitted form
883 * This can extract the responses given to one or several questions present on a page
884 * It returns an array with one entry for each question, indexed by question id
885 * Each entry is an object with the properties
886 * ->event The event that has triggered the submission. This is determined by which button
887 * the user has pressed.
888 * ->responses An array holding the responses to an individual question, indexed by the
889 * name of the corresponding form element.
890 * ->timestamp A unix timestamp
891 * @return array array of action objects, indexed by question ids.
892 * @param array $questions an array containing at least all questions that are used on the form
893 * @param array $formdata the data submitted by the form on the question page
894 * @param integer $defaultevent the event type used if no 'mark' or 'validate' is submitted
896 function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE) {
898 $time = time();
899 $actions = array();
900 foreach ($formdata as $key => $response) {
901 // Get the question id from the response name
902 if (false !== ($quid = question_get_id_from_name_prefix($key))) {
903 // check if this is a valid id
904 if (!isset($questions[$quid])) {
905 error('Form contained question that is not in questionids');
908 // Remove the name prefix from the name
909 //decrypt trying
910 $key = substr($key, strlen($questions[$quid]->name_prefix));
911 if (false === $key) {
912 $key = '';
914 // Check for question validate and mark buttons & set events
915 if ($key === 'validate') {
916 $actions[$quid]->event = QUESTION_EVENTVALIDATE;
917 } else if ($key === 'submit') {
918 $actions[$quid]->event = QUESTION_EVENTSUBMIT;
919 } else {
920 $actions[$quid]->event = $defaultevent;
923 // Update the state with the new response
924 $actions[$quid]->responses[$key] = $response;
926 // Set the timestamp
927 $actions[$quid]->timestamp = $time;
930 foreach ($actions as $quid => $notused) {
931 ksort($actions[$quid]->responses);
933 return $actions;
938 * Returns the html for question feedback image.
939 * @param float $fraction value representing the correctness of the user's
940 * response to a question.
941 * @param boolean $selected whether or not the answer is the one that the
942 * user picked.
943 * @return string
945 function question_get_feedback_image($fraction, $selected=true) {
947 global $CFG;
949 if ($fraction >= 1.0) {
950 if ($selected) {
951 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_green_big.gif" '.
952 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
953 } else {
954 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_green_small.gif" '.
955 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
957 } else if ($fraction > 0.0 && $fraction < 1.0) {
958 if ($selected) {
959 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_amber_big.gif" '.
960 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
961 } else {
962 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_amber_small.gif" '.
963 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
965 } else {
966 if ($selected) {
967 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/cross_red_big.gif" '.
968 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
969 } else {
970 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/cross_red_small.gif" '.
971 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
974 return $feedbackimg;
979 * Returns the class name for question feedback.
980 * @param float $fraction value representing the correctness of the user's
981 * response to a question.
982 * @return string
984 function question_get_feedback_class($fraction) {
986 global $CFG;
988 if ($fraction >= 1.0) {
989 $class = 'correct';
990 } else if ($fraction > 0.0 && $fraction < 1.0) {
991 $class = 'partiallycorrect';
992 } else {
993 $class = 'incorrect';
995 return $class;
1000 * For a given question in an attempt we walk the complete history of states
1001 * and recalculate the grades as we go along.
1003 * This is used when a question is changed and old student
1004 * responses need to be marked with the new version of a question.
1006 * TODO: Make sure this is not quiz-specific
1008 * @return boolean Indicates whether the grade has changed
1009 * @param object $question A question object
1010 * @param object $attempt The attempt, in which the question needs to be regraded.
1011 * @param object $cmoptions
1012 * @param boolean $verbose Optional. Whether to print progress information or not.
1014 function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false) {
1016 // load all states for this question in this attempt, ordered in sequence
1017 if ($states = get_records_select('question_states',
1018 "attempt = '{$attempt->uniqueid}' AND question = '{$question->id}'",
1019 'seq_number ASC')) {
1020 $states = array_values($states);
1022 // Subtract the grade for the latest state from $attempt->sumgrades to get the
1023 // sumgrades for the attempt without this question.
1024 $attempt->sumgrades -= $states[count($states)-1]->grade;
1026 // Initialise the replaystate
1027 $state = clone($states[0]);
1028 $state->manualcomment = get_field('question_sessions', 'manualcomment', 'attemptid',
1029 $attempt->uniqueid, 'questionid', $question->id);
1030 restore_question_state($question, $state);
1031 $state->sumpenalty = 0.0;
1032 $replaystate = clone($state);
1033 $replaystate->last_graded = $state;
1035 $changed = false;
1036 for($j = 1; $j < count($states); $j++) {
1037 restore_question_state($question, $states[$j]);
1038 $action = new stdClass;
1039 $action->responses = $states[$j]->responses;
1040 $action->timestamp = $states[$j]->timestamp;
1042 // Change event to submit so that it will be reprocessed
1043 if (QUESTION_EVENTCLOSE == $states[$j]->event
1044 or QUESTION_EVENTGRADE == $states[$j]->event
1045 or QUESTION_EVENTCLOSEANDGRADE == $states[$j]->event) {
1046 $action->event = QUESTION_EVENTSUBMIT;
1048 // By default take the event that was saved in the database
1049 } else {
1050 $action->event = $states[$j]->event;
1053 if ($action->event == QUESTION_EVENTMANUALGRADE) {
1054 question_process_comment($question, $replaystate, $attempt,
1055 $replaystate->manualcomment, $states[$j]->grade);
1056 } else {
1058 // Reprocess (regrade) responses
1059 if (!question_process_responses($question, $replaystate,
1060 $action, $cmoptions, $attempt)) {
1061 $verbose && notify("Couldn't regrade state #{$state->id}!");
1065 // We need rounding here because grades in the DB get truncated
1066 // e.g. 0.33333 != 0.3333333, but we want them to be equal here
1067 if ((round((float)$replaystate->raw_grade, 5) != round((float)$states[$j]->raw_grade, 5))
1068 or (round((float)$replaystate->penalty, 5) != round((float)$states[$j]->penalty, 5))
1069 or (round((float)$replaystate->grade, 5) != round((float)$states[$j]->grade, 5))) {
1070 $changed = true;
1073 $replaystate->id = $states[$j]->id;
1074 $replaystate->changed = true;
1075 $replaystate->update = true; // This will ensure that the existing database entry is updated rather than a new one created
1076 save_question_session($question, $replaystate);
1078 if ($changed) {
1079 // TODO, call a method in quiz to do this, where 'quiz' comes from
1080 // the question_attempts table.
1081 update_record('quiz_attempts', $attempt);
1084 return $changed;
1086 return false;
1090 * Processes an array of student responses, grading and saving them as appropriate
1092 * @return boolean Indicates success/failure
1093 * @param object $question Full question object, passed by reference
1094 * @param object $state Full state object, passed by reference
1095 * @param object $action object with the fields ->responses which
1096 * is an array holding the student responses,
1097 * ->action which specifies the action, e.g., QUESTION_EVENTGRADE,
1098 * and ->timestamp which is a timestamp from when the responses
1099 * were submitted by the student.
1100 * @param object $cmoptions
1101 * @param object $attempt The attempt is passed by reference so that
1102 * during grading its ->sumgrades field can be updated
1104 function question_process_responses(&$question, &$state, $action, $cmoptions, &$attempt) {
1105 global $QTYPES;
1107 // if no responses are set initialise to empty response
1108 if (!isset($action->responses)) {
1109 $action->responses = array('' => '');
1112 // make sure these are gone!
1113 unset($action->responses['submit'], $action->responses['validate']);
1115 // Check the question session is still open
1116 if (question_state_is_closed($state)) {
1117 return true;
1120 // If $action->event is not set that implies saving
1121 if (! isset($action->event)) {
1122 debugging('Ambiguous action in question_process_responses.' , DEBUG_DEVELOPER);
1123 $action->event = QUESTION_EVENTSAVE;
1125 // If submitted then compare against last graded
1126 // responses, not last given responses in this case
1127 if (question_isgradingevent($action->event)) {
1128 $state->responses = $state->last_graded->responses;
1131 // Check for unchanged responses (exactly unchanged, not equivalent).
1132 // We also have to catch questions that the student has not yet attempted
1133 $sameresponses = $QTYPES[$question->qtype]->compare_responses($question, $action, $state);
1134 if ($state->last_graded->event == QUESTION_EVENTOPEN && question_isgradingevent($action->event)) {
1135 $sameresponses = false;
1138 // If the response has not been changed then we do not have to process it again
1139 // unless the attempt is closing or validation is requested
1140 if ($sameresponses and QUESTION_EVENTCLOSE != $action->event
1141 and QUESTION_EVENTVALIDATE != $action->event) {
1142 return true;
1145 // Roll back grading information to last graded state and set the new
1146 // responses
1147 $newstate = clone($state->last_graded);
1148 $newstate->responses = $action->responses;
1149 $newstate->seq_number = $state->seq_number + 1;
1150 $newstate->changed = true; // will assure that it gets saved to the database
1151 $newstate->last_graded = clone($state->last_graded);
1152 $newstate->timestamp = $action->timestamp;
1153 $state = $newstate;
1155 // Set the event to the action we will perform. The question type specific
1156 // grading code may override this by setting it to QUESTION_EVENTCLOSE if the
1157 // attempt at the question causes the session to close
1158 $state->event = $action->event;
1160 if (!question_isgradingevent($action->event)) {
1161 // Grade the response but don't update the overall grade
1162 $QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions);
1164 // Temporary hack because question types are not given enough control over what is going
1165 // on. Used by Opaque questions.
1166 // TODO fix this code properly.
1167 if (!empty($state->believeevent)) {
1168 // If the state was graded we need to ...
1169 if (question_state_is_graded($state)) {
1170 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1172 // update the attempt grade
1173 $attempt->sumgrades -= (float)$state->last_graded->grade;
1174 $attempt->sumgrades += (float)$state->grade;
1176 // and update the last_graded field.
1177 unset($state->last_graded);
1178 $state->last_graded = clone($state);
1179 unset($state->last_graded->changed);
1181 } else {
1182 // Don't allow the processing to change the event type
1183 $state->event = $action->event;
1186 } else { // grading event
1188 // Unless the attempt is closing, we want to work out if the current responses
1189 // (or equivalent responses) were already given in the last graded attempt.
1190 if(QUESTION_EVENTCLOSE != $action->event && QUESTION_EVENTOPEN != $state->last_graded->event &&
1191 $QTYPES[$question->qtype]->compare_responses($question, $state, $state->last_graded)) {
1192 $state->event = QUESTION_EVENTDUPLICATE;
1195 // If we did not find a duplicate or if the attempt is closing, perform grading
1196 if ((!$sameresponses and QUESTION_EVENTDUPLICATE != $state->event) or
1197 QUESTION_EVENTCLOSE == $action->event) {
1199 $QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions);
1200 // Calculate overall grade using correct penalty method
1201 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1204 // If the state was graded we need to ...
1205 if (question_state_is_graded($state)) {
1206 // update the attempt grade
1207 $attempt->sumgrades -= (float)$state->last_graded->grade;
1208 $attempt->sumgrades += (float)$state->grade;
1210 // and update the last_graded field.
1211 unset($state->last_graded);
1212 $state->last_graded = clone($state);
1213 unset($state->last_graded->changed);
1216 $attempt->timemodified = $action->timestamp;
1218 return true;
1222 * Determine if event requires grading
1224 function question_isgradingevent($event) {
1225 return (QUESTION_EVENTSUBMIT == $event || QUESTION_EVENTCLOSE == $event);
1229 * Applies the penalty from the previous graded responses to the raw grade
1230 * for the current responses
1232 * The grade for the question in the current state is computed by subtracting the
1233 * penalty accumulated over the previous graded responses at the question from the
1234 * raw grade. If the timestamp is more than 1 minute beyond the end of the attempt
1235 * the grade is set to zero. The ->grade field of the state object is modified to
1236 * reflect the new grade but is never allowed to decrease.
1237 * @param object $question The question for which the penalty is to be applied.
1238 * @param object $state The state for which the grade is to be set from the
1239 * raw grade and the cumulative penalty from the last
1240 * graded state. The ->grade field is updated by applying
1241 * the penalty scheme determined in $cmoptions to the ->raw_grade and
1242 * ->last_graded->penalty fields.
1243 * @param object $cmoptions The options set by the course module.
1244 * The ->penaltyscheme field determines whether penalties
1245 * for incorrect earlier responses are subtracted.
1247 function question_apply_penalty_and_timelimit(&$question, &$state, $attempt, $cmoptions) {
1248 // TODO. Quiz dependancy. The fact that the attempt that is passed in here
1249 // is from quiz_attempts, and we use things like $cmoptions->timelimit.
1251 // deal with penalty
1252 if ($cmoptions->penaltyscheme) {
1253 $state->grade = $state->raw_grade - $state->sumpenalty;
1254 $state->sumpenalty += (float) $state->penalty;
1255 } else {
1256 $state->grade = $state->raw_grade;
1259 // deal with timelimit
1260 if ($cmoptions->timelimit) {
1261 // We allow for 5% uncertainty in the following test
1262 if ($state->timestamp - $attempt->timestart > $cmoptions->timelimit * 63) {
1263 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id);
1264 if (!has_capability('mod/quiz:ignoretimelimits', get_context_instance(CONTEXT_MODULE, $cm->id),
1265 $attempt->userid, false)) {
1266 $state->grade = 0;
1271 // deal with closing time
1272 if ($cmoptions->timeclose and $state->timestamp > ($cmoptions->timeclose + 60) // allowing 1 minute lateness
1273 and !$attempt->preview) { // ignore closing time for previews
1274 $state->grade = 0;
1277 // Ensure that the grade does not go down
1278 $state->grade = max($state->grade, $state->last_graded->grade);
1282 * Print the icon for the question type
1284 * @param object $question The question object for which the icon is required
1285 * @param boolean $return If true the functions returns the link as a string
1287 function print_question_icon($question, $return = false) {
1288 global $QTYPES, $CFG;
1290 $namestr = $QTYPES[$question->qtype]->menu_name();
1291 $html = '<img src="' . $CFG->wwwroot . '/question/type/' .
1292 $question->qtype . '/icon.gif" alt="' .
1293 $namestr . '" title="' . $namestr . '" />';
1294 if ($return) {
1295 return $html;
1296 } else {
1297 echo $html;
1302 * Returns a html link to the question image if there is one
1304 * @return string The html image tag or the empy string if there is no image.
1305 * @param object $question The question object
1307 function get_question_image($question, $courseid) {
1309 global $CFG;
1310 $img = '';
1312 if ($question->image) {
1314 if (substr(strtolower($question->image), 0, 7) == 'http://') {
1315 $img .= $question->image;
1317 } else if ($CFG->slasharguments) { // Use this method if possible for better caching
1318 $img .= "$CFG->wwwroot/file.php/$courseid/$question->image";
1320 } else {
1321 $img .= "$CFG->wwwroot/file.php?file=/$courseid/$question->image";
1324 return $img;
1327 function question_print_comment_box($question, $state, $attempt, $url) {
1328 global $CFG;
1330 $prefix = 'response';
1331 $usehtmleditor = can_use_richtext_editor();
1332 $grade = round($state->last_graded->grade, 3);
1333 echo '<form method="post" action="'.$url.'">';
1334 include($CFG->dirroot.'/question/comment.html');
1335 echo '<input type="hidden" name="attempt" value="'.$attempt->uniqueid.'" />';
1336 echo '<input type="hidden" name="question" value="'.$question->id.'" />';
1337 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1338 echo '<input type="submit" name="submit" value="'.get_string('save', 'quiz').'" />';
1339 echo '</form>';
1341 if ($usehtmleditor) {
1342 use_html_editor();
1346 function question_process_comment($question, &$state, &$attempt, $comment, $grade) {
1348 // Update the comment and save it in the database
1349 $state->manualcomment = $comment;
1350 if (!set_field('question_sessions', 'manualcomment', $comment, 'attemptid', $attempt->uniqueid, 'questionid', $question->id)) {
1351 error("Cannot save comment");
1354 // Update the attempt if the score has changed.
1355 if (abs($state->last_graded->grade - $grade) > 0.002) {
1356 $attempt->sumgrades = $attempt->sumgrades - $state->last_graded->grade + $grade;
1357 $attempt->timemodified = time();
1358 if (!update_record('quiz_attempts', $attempt)) {
1359 error('Failed to save the current quiz attempt!');
1363 // Update the state if either the score has changed, or this is the first
1364 // manual grade event.
1365 // We don't need to store the modified state in the database, we just need
1366 // to set the $state->changed flag.
1367 if (abs($state->last_graded->grade - $grade) > 0.002 ||
1368 $state->last_graded->event != QUESTION_EVENTMANUALGRADE) {
1370 // We want to update existing state (rather than creating new one) if it
1371 // was itself created by a manual grading event.
1372 $state->update = ($state->event == QUESTION_EVENTMANUALGRADE) ? 1 : 0;
1374 // Update the other parts of the state object.
1375 $state->raw_grade = $grade;
1376 $state->grade = $grade;
1377 $state->penalty = 0;
1378 $state->timestamp = time();
1379 $state->seq_number++;
1380 $state->event = QUESTION_EVENTMANUALGRADE;
1382 // Update the last graded state (don't simplify!)
1383 unset($state->last_graded);
1384 $state->last_graded = clone($state);
1386 // We need to indicate that the state has changed in order for it to be saved.
1387 $state->changed = 1;
1393 * Construct name prefixes for question form element names
1395 * Construct the name prefix that should be used for example in the
1396 * names of form elements created by questions.
1397 * This is called by {@link get_question_options()}
1398 * to set $question->name_prefix.
1399 * This name prefix includes the question id which can be
1400 * extracted from it with {@link question_get_id_from_name_prefix()}.
1402 * @return string
1403 * @param integer $id The question id
1405 function question_make_name_prefix($id) {
1406 return 'resp' . $id . '_';
1410 * Extract question id from the prefix of form element names
1412 * @return integer The question id
1413 * @param string $name The name that contains a prefix that was
1414 * constructed with {@link question_make_name_prefix()}
1416 function question_get_id_from_name_prefix($name) {
1417 if (!preg_match('/^resp([0-9]+)_/', $name, $matches))
1418 return false;
1419 return (integer) $matches[1];
1423 * Returns the unique id for a new attempt
1425 * Every module can keep their own attempts table with their own sequential ids but
1426 * the question code needs to also have a unique id by which to identify all these
1427 * attempts. Hence a module, when creating a new attempt, calls this function and
1428 * stores the return value in the 'uniqueid' field of its attempts table.
1430 function question_new_attempt_uniqueid($modulename='quiz') {
1431 global $CFG;
1432 $attempt = new stdClass;
1433 $attempt->modulename = $modulename;
1434 if (!$id = insert_record('question_attempts', $attempt)) {
1435 error('Could not create new entry in question_attempts table');
1437 return $id;
1441 * Creates a stamp that uniquely identifies this version of the question
1443 * In future we want this to use a hash of the question data to guarantee that
1444 * identical versions have the same version stamp.
1446 * @param object $question
1447 * @return string A unique version stamp
1449 function question_hash($question) {
1450 return make_unique_id_code();
1454 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
1456 * Get the HTML that needs to be included in the head tag when the
1457 * questions in $questionlist are printed in the gives states.
1459 * @param array $questionlist a list of questionids of the questions what will appear on this page.
1460 * @param array $questions an array of question objects, whose keys are question ids.
1461 * Must contain all the questions in $questionlist
1462 * @param array $states an array of question state objects, whose keys are question ids.
1463 * Must contain the state of all the questions in $questionlist
1465 * @return string some HTML code that can go inside the head tag.
1467 function get_html_head_contributions(&$questionlist, &$questions, &$states) {
1468 global $QTYPES;
1470 $contributions = array();
1471 foreach ($questionlist as $questionid) {
1472 $question = $questions[$questionid];
1473 $contributions = array_merge($contributions,
1474 $QTYPES[$question->qtype]->get_html_head_contributions(
1475 $question, $states[$questionid]));
1477 return implode("\n", array_unique($contributions));
1481 * Prints a question
1483 * Simply calls the question type specific print_question() method.
1484 * @param object $question The question to be rendered.
1485 * @param object $state The state to render the question in.
1486 * @param integer $number The number for this question.
1487 * @param object $cmoptions The options specified by the course module
1488 * @param object $options An object specifying the rendering options.
1490 function print_question(&$question, &$state, $number, $cmoptions, $options=null) {
1491 global $QTYPES;
1493 $QTYPES[$question->qtype]->print_question($question, $state, $number,
1494 $cmoptions, $options);
1497 * Saves question options
1499 * Simply calls the question type specific save_question_options() method.
1501 function save_question_options($question) {
1502 global $QTYPES;
1504 $QTYPES[$question->qtype]->save_question_options($question);
1508 * Gets all teacher stored answers for a given question
1510 * Simply calls the question type specific get_all_responses() method.
1512 // ULPGC ecastro
1513 function get_question_responses($question, $state) {
1514 global $QTYPES;
1515 $r = $QTYPES[$question->qtype]->get_all_responses($question, $state);
1516 return $r;
1521 * Gets the response given by the user in a particular state
1523 * Simply calls the question type specific get_actual_response() method.
1525 // ULPGC ecastro
1526 function get_question_actual_response($question, $state) {
1527 global $QTYPES;
1529 $r = $QTYPES[$question->qtype]->get_actual_response($question, $state);
1530 return $r;
1534 * TODO: document this
1536 // ULPGc ecastro
1537 function get_question_fraction_grade($question, $state) {
1538 global $QTYPES;
1540 $r = $QTYPES[$question->qtype]->get_fractional_grade($question, $state);
1541 return $r;
1545 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1548 * returns the categories with their names ordered following parent-child relationships
1549 * finally it tries to return pending categories (those being orphaned, whose parent is
1550 * incorrect) to avoid missing any category from original array.
1552 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1553 $children = array();
1554 $keys = array_keys($categories);
1556 foreach ($keys as $key) {
1557 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1558 $children[$key] = $categories[$key];
1559 $categories[$key]->processed = true;
1560 $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1);
1563 //If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too
1564 if ($level == 1) {
1565 foreach ($keys as $key) {
1566 //If not processed and it's a good candidate to start (because its parent doesn't exist in the course)
1567 if (!isset($categories[$key]->processed) && !record_exists('question_categories', 'course', $categories[$key]->course, 'id', $categories[$key]->parent)) {
1568 $children[$key] = $categories[$key];
1569 $categories[$key]->processed = true;
1570 $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1);
1574 return $children;
1578 * Private method, only for the use of add_indented_names().
1580 * Recursively adds an indentedname field to each category, starting with the category
1581 * with id $id, and dealing with that category and all its children, and
1582 * return a new array, with those categories in the right order.
1584 * @param array $categories an array of categories which has had childids
1585 * fields added by flatten_category_tree(). Passed by reference for
1586 * performance only. It is not modfied.
1587 * @param int $id the category to start the indenting process from.
1588 * @param int $depth the indent depth. Used in recursive calls.
1589 * @return array a new array of categories, in the right order for the tree.
1591 function flatten_category_tree(&$categories, $id, $depth = 0) {
1593 // Indent the name of this category.
1594 $newcategories = array();
1595 $newcategories[$id] = $categories[$id];
1596 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) . $categories[$id]->name;
1598 // Recursively indent the children.
1599 foreach ($categories[$id]->childids as $childid) {
1600 $newcategories = $newcategories + flatten_category_tree($categories, $childid, $depth + 1);
1603 // Remove the childids array that were temporarily added.
1604 unset($newcategories[$id]->childids);
1606 return $newcategories;
1610 * Format categories into an indented list reflecting the tree structure.
1612 * @param array $categories An array of category objects, for example from the.
1613 * @return array The formatted list of categories.
1615 function add_indented_names($categories) {
1617 // Add an array to each category to hold the child category ids. This array will be removed
1618 // again by flatten_category_tree(). It should not be used outside these two functions.
1619 foreach (array_keys($categories) as $id) {
1620 $categories[$id]->childids = array();
1623 // Build the tree structure, and record which categories are top-level.
1624 // We have to be careful, because the categories array may include published
1625 // categories from other courses, but not their parents.
1626 $toplevelcategoryids = array();
1627 foreach (array_keys($categories) as $id) {
1628 if (!empty($categories[$id]->parent) && array_key_exists($categories[$id]->parent, $categories)) {
1629 $categories[$categories[$id]->parent]->childids[] = $id;
1630 } else {
1631 $toplevelcategoryids[] = $id;
1635 // Flatten the tree to and add the indents.
1636 $newcategories = array();
1637 foreach ($toplevelcategoryids as $id) {
1638 $newcategories = $newcategories + flatten_category_tree($categories, $id);
1641 return $newcategories;
1645 * Output a select menu of question categories.
1647 * Categories from this course and (optionally) published categories from other courses
1648 * are included. Optionally, only categories the current user may edit can be included.
1650 * @param integer $courseid the id of the course to get the categories for.
1651 * @param integer $published if true, include publised categories from other courses.
1652 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1653 * @param integer $selected optionally, the id of a category to be selected by default in the dropdown.
1655 function question_category_select_menu($courseid, $published = false, $only_editable = false, $selected = "") {
1656 $categoriesarray = question_category_options($courseid, $published, $only_editable);
1657 if ($selected) {
1658 $nothing = '';
1659 } else {
1660 $nothing = 'choose';
1662 choose_from_menu($categoriesarray, 'category', $selected, $nothing);
1666 * Output an array of question categories.
1668 * Categories from this course and (optionally) published categories from other courses
1669 * are included. Optionally, only categories the current user may edit can be included.
1671 * @param integer $courseid the id of the course to get the categories for.
1672 * @param integer $published if true, include publised categories from other courses.
1673 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1674 * @return array The list of categories.
1676 function question_category_options($courseid, $published = false, $only_editable = false) {
1677 global $CFG;
1679 // get sql fragment for published
1680 $publishsql="";
1681 if ($published) {
1682 $publishsql = " OR publish = 1";
1685 $categories = get_records_sql("
1686 SELECT cat.*, c.shortname AS coursename
1687 FROM {$CFG->prefix}question_categories cat, {$CFG->prefix}course c
1688 WHERE c.id = cat.course AND (cat.course = $courseid $publishsql)
1689 ORDER BY (CASE WHEN cat.course = $courseid THEN 0 ELSE 1 END), cat.parent, cat.sortorder, cat.name ASC");
1690 $categories = add_indented_names($categories);
1692 $categoriesarray = array();
1693 foreach ($categories as $category) {
1694 $cid = $category->id;
1695 $cname = question_category_coursename($category, $courseid);
1696 if ((!$only_editable) || has_capability('moodle/question:managecategory', get_context_instance(CONTEXT_COURSE, $category->course))) {
1697 $categoriesarray[$cid] = $cname;
1700 return $categoriesarray;
1704 * If the category is not from this course, and it is a published category,
1705 * then return the course category name with the course shortname appended in
1706 * brackets. Otherwise, just return the category name.
1708 function question_category_coursename($category, $courseid = 0) {
1709 $cname = (isset($category->indentedname)) ? $category->indentedname : $category->name;
1710 if ($category->course != $courseid && $category->publish) {
1711 if (!empty($category->coursename)) {
1712 $coursename = $category->coursename;
1713 } else {
1714 $coursename = get_field('course', 'shortname', 'id', $category->course);
1716 $cname .= " ($coursename)";
1718 return $cname;
1722 * Returns a comma separated list of ids of the category and all subcategories
1724 function question_categorylist($categoryid) {
1725 // returns a comma separated list of ids of the category and all subcategories
1726 $categorylist = $categoryid;
1727 if ($subcategories = get_records('question_categories', 'parent', $categoryid, 'sortorder ASC', 'id, id')) {
1728 foreach ($subcategories as $subcategory) {
1729 $categorylist .= ','. question_categorylist($subcategory->id);
1732 return $categorylist;
1736 * find and/or create the category described by a delimited list
1737 * e.g. tom/dick/harry
1738 * @param string catpath delimited category path
1739 * @param string delimiter path delimiting character
1740 * @param int courseid course to search for categories
1741 * @return mixed category object or null if fails
1743 function create_category_path( $catpath, $delimiter='/', $courseid=0 ) {
1744 $catpath = clean_param( $catpath,PARAM_PATH );
1745 $catnames = explode( $delimiter, $catpath );
1746 $parent = 0;
1747 $category = null;
1748 foreach ($catnames as $catname) {
1749 if ($category = get_record( 'question_categories', 'name', $catname, 'course', $courseid, 'parent', $parent )) {
1750 $parent = $category->id;
1752 else {
1753 // create the new category
1754 $category = new object;
1755 $category->course = $courseid;
1756 $category->name = $catname;
1757 $category->info = '';
1758 $category->publish = false;
1759 $category->parent = $parent;
1760 $category->sortorder = 999;
1761 $category->stamp = make_unique_id_code();
1762 if (!($id = insert_record( 'question_categories', $category ))) {
1763 error( "cannot create new category - $catname" );
1765 $category->id = $id;
1766 $parent = $id;
1769 return $category;
1773 * get the category as a path (e.g., tom/dick/harry)
1774 * @param int id the id of the most nested catgory
1775 * @param string delimiter the delimiter you want
1776 * @return string the path
1778 function get_category_path( $id, $delimiter='/' ) {
1779 $path = '';
1780 do {
1781 if (!$category = get_record( 'question_categories','id',$id )) {
1782 print_error( "Error reading category record - $id" );
1784 $name = $category->name;
1785 $id = $category->parent;
1786 if (!empty($path)) {
1787 $path = "{$name}{$delimiter}{$path}";
1789 else {
1790 $path = $name;
1792 } while ($id != 0);
1794 return $path;
1797 //===========================
1798 // Import/Export Functions
1799 //===========================
1802 * Get list of available import or export formats
1803 * @param string $type 'import' if import list, otherwise export list assumed
1804 * @return array sorted list of import/export formats available
1806 function get_import_export_formats( $type ) {
1808 global $CFG;
1809 $fileformats = get_list_of_plugins("question/format");
1811 $fileformatname=array();
1812 require_once( "{$CFG->dirroot}/question/format.php" );
1813 foreach ($fileformats as $key => $fileformat) {
1814 $format_file = $CFG->dirroot . "/question/format/$fileformat/format.php";
1815 if (file_exists( $format_file ) ) {
1816 require_once( $format_file );
1818 else {
1819 continue;
1821 $classname = "qformat_$fileformat";
1822 $format_class = new $classname();
1823 if ($type=='import') {
1824 $provided = $format_class->provide_import();
1826 else {
1827 $provided = $format_class->provide_export();
1829 if ($provided) {
1830 $formatname = get_string($fileformat, 'quiz');
1831 if ($formatname == "[[$fileformat]]") {
1832 $formatname = $fileformat; // Just use the raw folder name
1834 $fileformatnames[$fileformat] = $formatname;
1837 natcasesort($fileformatnames);
1839 return $fileformatnames;
1844 * Create default export filename
1846 * @return string default export filename
1847 * @param object $course
1848 * @param object $category
1850 function default_export_filename($course,$category) {
1851 //Take off some characters in the filename !!
1852 $takeoff = array(" ", ":", "/", "\\", "|");
1853 $export_word = str_replace($takeoff,"_",moodle_strtolower(get_string("exportfilename","quiz")));
1854 //If non-translated, use "export"
1855 if (substr($export_word,0,1) == "[") {
1856 $export_word= "export";
1859 //Calculate the date format string
1860 $export_date_format = str_replace(" ","_",get_string("exportnameformat","quiz"));
1861 //If non-translated, use "%Y%m%d-%H%M"
1862 if (substr($export_date_format,0,1) == "[") {
1863 $export_date_format = "%%Y%%m%%d-%%H%%M";
1866 //Calculate the shortname
1867 $export_shortname = clean_filename($course->shortname);
1868 if (empty($export_shortname) or $export_shortname == '_' ) {
1869 $export_shortname = $course->id;
1872 //Calculate the category name
1873 $export_categoryname = clean_filename($category->name);
1875 //Calculate the final export filename
1876 //The export word
1877 $export_name = $export_word."-";
1878 //The shortname
1879 $export_name .= moodle_strtolower($export_shortname)."-";
1880 //The category name
1881 $export_name .= moodle_strtolower($export_categoryname)."-";
1882 //The date format
1883 $export_name .= userdate(time(),$export_date_format,99,false);
1884 //The extension - no extension, supplied by format
1885 // $export_name .= ".txt";
1887 return $export_name;