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
21 /// CONSTANTS ///////////////////////////////////
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
37 define('QUESTION_EVENTS_GRADED', QUESTION_EVENTGRADE
.','.
38 QUESTION_EVENTCLOSEANDGRADE
.','.
39 QUESTION_EVENTMANUALGRADE
);
43 * The core question types.
45 define("SHORTANSWER", "shortanswer");
46 define("TRUEFALSE", "truefalse");
47 define("MULTICHOICE", "multichoice");
48 define("RANDOM", "random");
49 define("MATCH", "match");
50 define("RANDOMSAMATCH", "randomsamatch");
51 define("DESCRIPTION", "description");
52 define("NUMERICAL", "numerical");
53 define("MULTIANSWER", "multianswer");
54 define("CALCULATED", "calculated");
55 define("ESSAY", "essay");
59 * Constant determines the number of answer boxes supplied in the editing
60 * form for multiple choice and similar question types.
62 define("QUESTION_NUMANS", "10");
65 * Constant determines the number of answer boxes supplied in the editing
66 * form for multiple choice and similar question types to start with, with
67 * the option of adding QUESTION_NUMANS_ADD more answers.
69 define("QUESTION_NUMANS_START", 3);
72 * Constant determines the number of answer boxes to add in the editing
73 * form for multiple choice and similar question types when the user presses
74 * 'add form fields button'.
76 define("QUESTION_NUMANS_ADD", 3);
79 * The options used when popping up a question preview window in Javascript.
81 define('QUESTION_PREVIEW_POPUP_OPTIONS', 'scrollbars=yes,resizable=yes,width=700,height=540');
84 * Option flags for ->optionflags
85 * The options are read out via bitwise operation using these constants
88 * Whether the questions is to be run in adaptive mode. If this is not set then
89 * a question closes immediately after the first submission of responses. This
90 * is how question is Moodle always worked before version 1.5
92 define('QUESTION_ADAPTIVE', 1);
95 * options used in forms that move files.
98 define('QUESTION_FILENOTHINGSELECTED', 0);
99 define('QUESTION_FILEDONOTHING', 1);
100 define('QUESTION_FILECOPY', 2);
101 define('QUESTION_FILEMOVE', 3);
102 define('QUESTION_FILEMOVELINKSONLY', 4);
106 /// QTYPES INITIATION //////////////////
107 // These variables get initialised via calls to question_register_questiontype
108 // as the question type classes are included.
109 global $QTYPES, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
111 * Array holding question type objects
115 * String in the format "'type1','type2'" that can be used in SQL clauses like
116 * "WHERE q.type IN ($QTYPE_MANUAL)".
120 * String in the format "'type1','type2'" that can be used in SQL clauses like
121 * "WHERE q.type NOT IN ($QTYPE_EXCLUDE_FROM_RANDOM)".
123 $QTYPE_EXCLUDE_FROM_RANDOM = '';
126 * Add a new question type to the various global arrays above.
128 * @param object $qtype An instance of the new question type class.
130 function question_register_questiontype($qtype) {
131 global $QTYPES, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
133 $name = $qtype->name();
134 $QTYPES[$name] = $qtype;
135 if ($qtype->is_manual_graded()) {
137 $QTYPE_MANUAL .= ',';
139 $QTYPE_MANUAL .= "'$name'";
141 if (!$qtype->is_usable_by_random()) {
142 if ($QTYPE_EXCLUDE_FROM_RANDOM) {
143 $QTYPE_EXCLUDE_FROM_RANDOM .= ',';
145 $QTYPE_EXCLUDE_FROM_RANDOM .= "'$name'";
149 require_once("$CFG->dirroot/question/type/questiontype.php");
151 // Load the questiontype.php file for each question type
152 // These files in turn call question_register_questiontype()
153 // with a new instance of each qtype class.
154 $qtypenames= get_list_of_plugins('question/type');
155 foreach($qtypenames as $qtypename) {
156 // Instanciates all plug-in question types
157 $qtypefilepath= "$CFG->dirroot/question/type/$qtypename/questiontype.php";
159 // echo "Loading $qtypename<br/>"; // Uncomment for debugging
160 if (is_readable($qtypefilepath)) {
161 require_once($qtypefilepath);
166 * An array of question type names translated to the user's language, suitable for use when
167 * creating a drop-down menu of options.
169 * Long-time Moodle programmers will realise that this replaces the old $QTYPE_MENU array.
170 * The array returned will only hold the names of all the question types that the user should
171 * be able to create directly. Some internal question types like random questions are excluded.
173 * @return array an array of question type names translated to the user's language.
175 function question_type_menu() {
177 static $menu_options = null;
178 if (is_null($menu_options)) {
179 $menu_options = array();
180 foreach ($QTYPES as $name => $qtype) {
181 $menuname = $qtype->menu_name();
183 $menu_options[$name] = $menuname;
187 return $menu_options;
190 /// OTHER CLASSES /////////////////////////////////////////////////////////
193 * This holds the options that are set by the course module
197 * Whether a new attempt should be based on the previous one. If true
198 * then a new attempt will start in a state where all responses are set
199 * to the last responses from the previous attempt.
201 var $attemptonlast = false;
204 * Various option flags. The flags are accessed via bitwise operations
205 * using the constants defined in the CONSTANTS section above.
207 var $optionflags = QUESTION_ADAPTIVE
;
210 * Determines whether in the calculation of the score for a question
211 * penalties for earlier wrong responses within the same attempt will
214 var $penaltyscheme = true;
217 * The maximum time the user is allowed to answer the questions withing
218 * an attempt. This is measured in minutes so needs to be multiplied by
219 * 60 before compared to timestamps. If set to 0 no timelimit will be applied
224 * Timestamp for the closing time. Responses submitted after this time will
225 * be saved but no credit will be given for them.
227 var $timeclose = 9999999999;
230 * The id of the course from withing which the question is currently being used
232 var $course = SITEID
;
235 * Whether the answers in a multiple choice question should be randomly
236 * shuffled when a new attempt is started.
238 var $shuffleanswers = true;
241 * The number of decimals to be shown when scores are printed
243 var $decimalpoints = 2;
247 /// FUNCTIONS //////////////////////////////////////////////////////
250 * Returns an array of names of activity modules that use this question
252 * @param object $questionid
253 * @return array of strings
255 function question_list_instances($questionid) {
257 $instances = array();
258 $modules = get_records('modules');
259 foreach ($modules as $module) {
260 $fullmod = $CFG->dirroot
. '/mod/' . $module->name
;
261 if (file_exists($fullmod . '/lib.php')) {
262 include_once($fullmod . '/lib.php');
263 $fn = $module->name
.'_question_list_instances';
264 if (function_exists($fn)) {
265 $instances = $instances +
$fn($questionid);
273 * Determine whether there arey any questions belonging to this context, that is whether any of its
274 * question categories contain any questions. This will return true even if all the questions are
277 * @param mixed $context either a context object, or a context id.
278 * @return boolean whether any of the question categories beloning to this context have
279 * any questions in them.
281 function question_context_has_any_questions($context) {
283 if (is_object($context)) {
284 $contextid = $context->id
;
285 } else if (is_numeric($context)) {
286 $contextid = $context;
288 print_error('invalidcontextinhasanyquestions', 'question');
290 return record_exists_sql('SELECT * FROM ' . $CFG->prefix
. 'question q ' .
291 'JOIN ' . $CFG->prefix
. 'question_categories qc ON qc.id = q.category ' .
292 "WHERE qc.contextid = $contextid AND q.parent = 0");
296 * Returns list of 'allowed' grades for grade selection
297 * formatted suitably for dropdown box function
298 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
300 function get_grade_options() {
301 // define basic array of grades
324 // iterate through grades generating full range of options
325 $gradeoptionsfull = array();
326 $gradeoptions = array();
327 foreach ($grades as $grade) {
328 $percentage = 100 * $grade;
330 $gradeoptions["$grade"] = "$percentage %";
331 $gradeoptionsfull["$grade"] = "$percentage %";
332 $gradeoptionsfull["$neggrade"] = -$percentage." %";
334 $gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
337 arsort($gradeoptions, SORT_NUMERIC
);
338 arsort($gradeoptionsfull, SORT_NUMERIC
);
340 // construct return object
341 $grades = new stdClass
;
342 $grades->gradeoptions
= $gradeoptions;
343 $grades->gradeoptionsfull
= $gradeoptionsfull;
349 * match grade options
350 * if no match return error or match nearest
351 * @param array $gradeoptionsfull list of valid options
352 * @param int $grade grade to be tested
353 * @param string $matchgrades 'error' or 'nearest'
354 * @return mixed either 'fixed' value or false if erro
356 function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
357 // if we just need an error...
358 if ($matchgrades=='error') {
359 foreach($gradeoptionsfull as $value => $option) {
360 // slightly fuzzy test, never check floats for equality :-)
361 if (abs($grade-$value)<0.00001) {
365 // didn't find a match so that's an error
368 // work out nearest value
369 else if ($matchgrades=='nearest') {
371 foreach($gradeoptionsfull as $value => $option) {
372 if ($grade==$value) {
375 $hownear[ $value ] = abs( $grade - $value );
377 // reverse sort list of deltas and grab the last (smallest)
378 asort( $hownear, SORT_NUMERIC
);
380 return key( $hownear );
388 * Tests whether a category is in use by any activity module
391 * @param integer $categoryid
392 * @param boolean $recursive Whether to examine category children recursively
394 function question_category_isused($categoryid, $recursive = false) {
396 //Look at each question in the category
397 if ($questions = get_records('question', 'category', $categoryid)) {
398 foreach ($questions as $question) {
399 if (count(question_list_instances($question->id
))) {
405 //Look under child categories recursively
407 if ($children = get_records('question_categories', 'parent', $categoryid)) {
408 foreach ($children as $child) {
409 if (question_category_isused($child->id
, $recursive)) {
420 * Deletes all data associated to an attempt from the database
422 * @param integer $attemptid The id of the attempt being deleted
424 function delete_attempt($attemptid) {
427 $states = get_records('question_states', 'attempt', $attemptid);
429 $stateslist = implode(',', array_keys($states));
431 // delete question-type specific data
432 foreach ($QTYPES as $qtype) {
433 $qtype->delete_states($stateslist);
437 // delete entries from all other question tables
438 // It is important that this is done only after calling the questiontype functions
439 delete_records("question_states", "attempt", $attemptid);
440 delete_records("question_sessions", "attemptid", $attemptid);
441 delete_records("question_attempts", "id", $attemptid);
445 * Deletes question and all associated data from the database
447 * It will not delete a question if it is used by an activity module
448 * @param object $question The question being deleted
450 function delete_question($questionid) {
453 // Do not delete a question if it is used by an activity module
454 if (count(question_list_instances($questionid))) {
458 // delete questiontype-specific data
459 $question = get_record('question', 'id', $questionid);
460 question_require_capability_on($question, 'edit');
462 if (isset($QTYPES[$question->qtype
])) {
463 $QTYPES[$question->qtype
]->delete_question($questionid);
466 echo "Question with id $questionid does not exist.<br />";
469 if ($states = get_records('question_states', 'question', $questionid)) {
470 $stateslist = implode(',', array_keys($states));
472 // delete questiontype-specific data
473 foreach ($QTYPES as $qtype) {
474 $qtype->delete_states($stateslist);
478 // delete entries from all other question tables
479 // It is important that this is done only after calling the questiontype functions
480 delete_records("question_answers", "question", $questionid);
481 delete_records("question_states", "question", $questionid);
482 delete_records("question_sessions", "questionid", $questionid);
484 // Now recursively delete all child questions
485 if ($children = get_records('question', 'parent', $questionid)) {
486 foreach ($children as $child) {
487 if ($child->id
!= $questionid) {
488 delete_question($child->id
);
493 // Finally delete the question record itself
494 delete_records('question', 'id', $questionid);
500 * All question categories and their questions are deleted for this course.
502 * @param object $mod an object representing the activity
503 * @param boolean $feedback to specify if the process must output a summary of its work
506 function question_delete_course($course, $feedback=true) {
507 //To store feedback to be showed at the end of the process
508 $feedbackdata = array();
511 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
512 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
513 $categoriescourse = get_records('question_categories', 'contextid', $coursecontext->id
, 'parent', 'id, parent, name');
515 if ($categoriescourse) {
517 //Sort categories following their tree (parent-child) relationships
518 //this will make the feedback more readable
519 $categoriescourse = sort_categories_by_tree($categoriescourse);
521 foreach ($categoriescourse as $category) {
523 //Delete it completely (questions and category itself)
525 if ($questions = get_records("question", "category", $category->id
)) {
526 foreach ($questions as $question) {
527 delete_question($question->id
);
529 delete_records("question", "category", $category->id
);
531 //delete the category
532 delete_records('question_categories', 'id', $category->id
);
535 $feedbackdata[] = array($category->name
, $strcatdeleted);
537 //Inform about changes performed if feedback is enabled
539 $table = new stdClass
;
540 $table->head
= array(get_string('category','quiz'), get_string('action'));
541 $table->data
= $feedbackdata;
549 * Category is about to be deleted,
550 * 1/ All question categories and their questions are deleted for this course category.
551 * 2/ All questions are moved to new category
553 * @param object $category course category object
554 * @param object $newcategory empty means everything deleted, otherwise id of category where content moved
555 * @param boolean $feedback to specify if the process must output a summary of its work
558 function question_delete_course_category($category, $newcategory, $feedback=true) {
559 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
560 if (empty($newcategory)) {
561 $feedbackdata = array(); // To store feedback to be showed at the end of the process
562 $rescueqcategory = null; // See the code around the call to question_save_from_deletion.
563 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
565 // Loop over question categories.
566 if ($categories = get_records('question_categories', 'contextid', $context->id
, 'parent', 'id, parent, name')) {
567 foreach ($categories as $category) {
569 // Deal with any questions in the category.
570 if ($questions = get_records('question', 'category', $category->id
)) {
572 // Try to delete each question.
573 foreach ($questions as $question) {
574 delete_question($question->id
);
577 // Check to see if there were any questions that were kept because they are
578 // still in use somehow, even though quizzes in courses in this category will
579 // already have been deteted. This could happen, for example, if questions are
580 // added to a course, and then that course is moved to another category (MDL-14802).
581 $questionids = get_records_select_menu('question', 'category = ' . $category->id
, '', 'id,1');
582 if (!empty($questionids)) {
583 if (!$rescueqcategory = question_save_from_deletion(implode(',', array_keys($questionids)),
584 get_parent_contextid($context), print_context_name($context), $rescueqcategory)) {
587 $feedbackdata[] = array($category->name
, get_string('questionsmovedto', 'question', $rescueqcategory->name
));
591 // Now delete the category.
592 if (!delete_records('question_categories', 'id', $category->id
)) {
595 $feedbackdata[] = array($category->name
, $strcatdeleted);
597 } // End loop over categories.
600 // Output feedback if requested.
601 if ($feedback and $feedbackdata) {
602 $table = new stdClass
;
603 $table->head
= array(get_string('questioncategory','question'), get_string('action'));
604 $table->data
= $feedbackdata;
609 // Move question categories ot the new context.
610 if (!$newcontext = get_context_instance(CONTEXT_COURSECAT
, $newcategory->id
)) {
613 if (!set_field('question_categories', 'contextid', $newcontext->id
, 'contextid', $context->id
)) {
618 $a->oldplace
= print_context_name($context);
619 $a->newplace
= print_context_name($newcontext);
620 notify(get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
628 * Enter description here...
630 * @param string $questionids list of questionids
631 * @param object $newcontext the context to create the saved category in.
632 * @param string $oldplace a textual description of the think being deleted, e.g. from get_context_name
633 * @param object $newcategory
634 * @return mixed false on
636 function question_save_from_deletion($questionids, $newcontextid, $oldplace, $newcategory = null) {
637 // Make a category in the parent context to move the questions to.
638 if (is_null($newcategory)) {
639 $newcategory = new object();
640 $newcategory->parent
= 0;
641 $newcategory->contextid
= $newcontextid;
642 $newcategory->name
= addslashes(get_string('questionsrescuedfrom', 'question', $oldplace));
643 $newcategory->info
= addslashes(get_string('questionsrescuedfrominfo', 'question', $oldplace));
644 $newcategory->sortorder
= 999;
645 $newcategory->stamp
= make_unique_id_code();
646 if (!$newcategory->id
= insert_record('question_categories', $newcategory)) {
651 // Move any remaining questions to the 'saved' category.
652 if (!question_move_questions_to_category($questionids, $newcategory->id
)) {
659 * All question categories and their questions are deleted for this activity.
661 * @param object $cm the course module object representing the activity
662 * @param boolean $feedback to specify if the process must output a summary of its work
665 function question_delete_activity($cm, $feedback=true) {
666 //To store feedback to be showed at the end of the process
667 $feedbackdata = array();
670 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
671 $modcontext = get_context_instance(CONTEXT_MODULE
, $cm->id
);
672 if ($categoriesmods = get_records('question_categories', 'contextid', $modcontext->id
, 'parent', 'id, parent, name')){
673 //Sort categories following their tree (parent-child) relationships
674 //this will make the feedback more readable
675 $categoriesmods = sort_categories_by_tree($categoriesmods);
677 foreach ($categoriesmods as $category) {
679 //Delete it completely (questions and category itself)
681 if ($questions = get_records("question", "category", $category->id
)) {
682 foreach ($questions as $question) {
683 delete_question($question->id
);
685 delete_records("question", "category", $category->id
);
687 //delete the category
688 delete_records('question_categories', 'id', $category->id
);
691 $feedbackdata[] = array($category->name
, $strcatdeleted);
693 //Inform about changes performed if feedback is enabled
695 $table = new stdClass
;
696 $table->head
= array(get_string('category','quiz'), get_string('action'));
697 $table->data
= $feedbackdata;
705 * This function should be considered private to the question bank, it is called from
706 * question/editlib.php question/contextmoveq.php and a few similar places to to the work of
707 * acutally moving questions and associated data. However, callers of this function also have to
708 * do other work, which is why you should not call this method directly from outside the questionbank.
710 * @param string $questionids a comma-separated list of question ids.
711 * @param integer $newcategory the id of the category to move to.
713 function question_move_questions_to_category($questionids, $newcategory) {
716 // Move the questions themselves.
717 $result = $result && set_field_select('question', 'category', $newcategory, "id IN ($questionids)");
719 // Move any subquestions belonging to them.
720 $result = $result && set_field_select('question', 'category', $newcategory, "parent IN ($questionids)");
722 // TODO Deal with datasets.
728 * @param array $row tab objects
729 * @param question_edit_contexts $contexts object representing contexts available from this context
730 * @param string $querystring to append to urls
732 function questionbank_navigation_tabs(&$row, $contexts, $querystring) {
733 global $CFG, $QUESTION_EDITTABCAPS;
735 'questions' =>array("$CFG->wwwroot/question/edit.php?$querystring", get_string('questions', 'quiz'), get_string('editquestions', 'quiz')),
736 'categories' =>array("$CFG->wwwroot/question/category.php?$querystring", get_string('categories', 'quiz'), get_string('editqcats', 'quiz')),
737 'import' =>array("$CFG->wwwroot/question/import.php?$querystring", get_string('import', 'quiz'), get_string('importquestions', 'quiz')),
738 'export' =>array("$CFG->wwwroot/question/export.php?$querystring", get_string('export', 'quiz'), get_string('exportquestions', 'quiz')));
739 foreach ($tabs as $tabname => $tabparams){
740 if ($contexts->have_one_edit_tab_cap($tabname)) {
741 $row[] = new tabobject($tabname, $tabparams[0], $tabparams[1], $tabparams[2]);
747 * Private function to factor common code out of get_question_options().
749 * @param object $question the question to tidy.
750 * @return boolean true if successful, else false.
752 function _tidy_question(&$question) {
754 if (!array_key_exists($question->qtype
, $QTYPES)) {
755 $question->qtype
= 'missingtype';
756 $question->questiontext
= '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext
;
758 $question->name_prefix
= question_make_name_prefix($question->id
);
759 return $QTYPES[$question->qtype
]->get_question_options($question);
763 * Updates the question objects with question type specific
764 * information by calling {@link get_question_options()}
766 * Can be called either with an array of question objects or with a single
769 * @param mixed $questions Either an array of question objects to be updated
770 * or just a single question object
771 * @return bool Indicates success or failure.
773 function get_question_options(&$questions) {
774 if (is_array($questions)) { // deal with an array of questions
775 foreach ($questions as $i => $notused) {
776 if (!_tidy_question($questions[$i])) {
781 } else { // deal with single question
782 return _tidy_question($questions);
787 * Loads the most recent state of each question session from the database
790 * For each question the most recent session state for the current attempt
791 * is loaded from the question_states table and the question type specific data and
792 * responses are added by calling {@link restore_question_state()} which in turn
793 * calls {@link restore_session_and_responses()} for each question.
794 * If no states exist for the question instance an empty state object is
795 * created representing the start of a session and empty question
796 * type specific information and responses are created by calling
797 * {@link create_session_and_responses()}.
799 * @return array An array of state objects representing the most recent
800 * states of the question sessions.
801 * @param array $questions The questions for which sessions are to be restored or
803 * @param object $cmoptions
804 * @param object $attempt The attempt for which the question sessions are
805 * to be restored or created.
806 * @param mixed either the id of a previous attempt, if this attmpt is
807 * building on a previous one, or false for a clean attempt.
809 function get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) {
810 global $CFG, $QTYPES;
812 // get the question ids
813 $ids = array_keys($questions);
814 $questionlist = implode(',', $ids);
816 // The question field must be listed first so that it is used as the
817 // array index in the array returned by get_records_sql
818 $statefields = 'n.questionid as question, s.*, n.sumpenalty, n.manualcomment';
819 // Load the newest states for the questions
820 $sql = "SELECT $statefields".
821 " FROM {$CFG->prefix}question_states s,".
822 " {$CFG->prefix}question_sessions n".
823 " WHERE s.id = n.newest".
824 " AND n.attemptid = '$attempt->uniqueid'".
825 " AND n.questionid IN ($questionlist)";
826 $states = get_records_sql($sql);
828 // Load the newest graded states for the questions
829 $sql = "SELECT $statefields".
830 " FROM {$CFG->prefix}question_states s,".
831 " {$CFG->prefix}question_sessions n".
832 " WHERE s.id = n.newgraded".
833 " AND n.attemptid = '$attempt->uniqueid'".
834 " AND n.questionid IN ($questionlist)";
835 $gradedstates = get_records_sql($sql);
837 // loop through all questions and set the last_graded states
838 foreach ($ids as $i) {
839 if (isset($states[$i])) {
840 restore_question_state($questions[$i], $states[$i]);
841 if (isset($gradedstates[$i])) {
842 restore_question_state($questions[$i], $gradedstates[$i]);
843 $states[$i]->last_graded
= $gradedstates[$i];
845 $states[$i]->last_graded
= clone($states[$i]);
848 // If the new attempt is to be based on a previous attempt get it and clean things
849 // Having lastattemptid filled implies that (should we double check?):
850 // $attempt->attempt > 1 and $cmoptions->attemptonlast and !$attempt->preview
851 if ($lastattemptid) {
852 // find the responses from the previous attempt and save them to the new session
854 // Load the last graded state for the question
855 $statefields = 'n.questionid as question, s.*, n.sumpenalty';
856 $sql = "SELECT $statefields".
857 " FROM {$CFG->prefix}question_states s,".
858 " {$CFG->prefix}question_sessions n".
859 " WHERE s.id = n.newgraded".
860 " AND n.attemptid = '$lastattemptid'".
861 " AND n.questionid = '$i'";
862 if (!$laststate = get_record_sql($sql)) {
863 // Only restore previous responses that have been graded
866 // Restore the state so that the responses will be restored
867 restore_question_state($questions[$i], $laststate);
868 $states[$i] = clone($laststate);
869 unset($states[$i]->id
);
871 // create a new empty state
872 $states[$i] = new object;
873 $states[$i]->question
= $i;
874 $states[$i]->responses
= array('' => '');
875 $states[$i]->raw_grade
= 0;
878 // now fill/overide initial values
879 $states[$i]->attempt
= $attempt->uniqueid
;
880 $states[$i]->seq_number
= 0;
881 $states[$i]->timestamp
= $attempt->timestart
;
882 $states[$i]->event
= ($attempt->timefinish
) ? QUESTION_EVENTCLOSE
: QUESTION_EVENTOPEN
;
883 $states[$i]->grade
= 0;
884 $states[$i]->penalty
= 0;
885 $states[$i]->sumpenalty
= 0;
886 $states[$i]->manualcomment
= '';
888 // Prevent further changes to the session from incrementing the
890 $states[$i]->changed
= true;
892 if ($lastattemptid) {
893 // prepare the previous responses for new processing
894 $action = new stdClass
;
895 $action->responses
= $laststate->responses
;
896 $action->timestamp
= $laststate->timestamp
;
897 $action->event
= QUESTION_EVENTSAVE
; //emulate save of questions from all pages MDL-7631
899 // Process these responses ...
900 question_process_responses($questions[$i], $states[$i], $action, $cmoptions, $attempt);
902 // Fix for Bug #5506: When each attempt is built on the last one,
903 // preserve the options from any previous attempt.
904 if ( isset($laststate->options
) ) {
905 $states[$i]->options
= $laststate->options
;
908 // Create the empty question type specific information
909 if (!$QTYPES[$questions[$i]->qtype
]->create_session_and_responses(
910 $questions[$i], $states[$i], $cmoptions, $attempt)) {
914 $states[$i]->last_graded
= clone($states[$i]);
922 * Creates the run-time fields for the states
924 * Extends the state objects for a question by calling
925 * {@link restore_session_and_responses()}
926 * @param object $question The question for which the state is needed
927 * @param object $state The state as loaded from the database
928 * @return boolean Represents success or failure
930 function restore_question_state(&$question, &$state) {
933 // initialise response to the value in the answer field
934 $state->responses
= array('' => addslashes($state->answer
));
935 unset($state->answer
);
936 $state->manualcomment
= isset($state->manualcomment
) ?
addslashes($state->manualcomment
) : '';
938 // Set the changed field to false; any code which changes the
939 // question session must set this to true and must increment
940 // ->seq_number. The save_question_session
941 // function will save the new state object to the database if the field is
943 $state->changed
= false;
945 // Load the question type specific data
946 return $QTYPES[$question->qtype
]
947 ->restore_session_and_responses($question, $state);
952 * Saves the current state of the question session to the database
954 * The state object representing the current state of the session for the
955 * question is saved to the question_states table with ->responses[''] saved
956 * to the answer field of the database table. The information in the
957 * question_sessions table is updated.
958 * The question type specific data is then saved.
959 * @return mixed The id of the saved or updated state or false
960 * @param object $question The question for which session is to be saved.
961 * @param object $state The state information to be saved. In particular the
962 * most recent responses are in ->responses. The object
963 * is updated to hold the new ->id.
965 function save_question_session(&$question, &$state) {
967 // Check if the state has changed
968 if (!$state->changed
&& isset($state->id
)) {
971 // Set the legacy answer field
972 $state->answer
= isset($state->responses
['']) ?
$state->responses
[''] : '';
975 if (!empty($state->update
)) { // this forces the old state record to be overwritten
976 update_record('question_states', $state);
978 if (!$state->id
= insert_record('question_states', $state)) {
980 unset($state->answer
);
985 // create or update the session
986 if (!$session = get_record('question_sessions', 'attemptid',
987 $state->attempt
, 'questionid', $question->id
)) {
988 $session->attemptid
= $state->attempt
;
989 $session->questionid
= $question->id
;
990 $session->newest
= $state->id
;
991 // The following may seem weird, but the newgraded field needs to be set
992 // already even if there is no graded state yet.
993 $session->newgraded
= $state->id
;
994 $session->sumpenalty
= $state->sumpenalty
;
995 $session->manualcomment
= $state->manualcomment
;
996 if (!insert_record('question_sessions', $session)) {
997 error('Could not insert entry in question_sessions');
1000 $session->newest
= $state->id
;
1001 if (question_state_is_graded($state) or $state->event
== QUESTION_EVENTOPEN
) {
1002 // this state is graded or newly opened, so it goes into the lastgraded field as well
1003 $session->newgraded
= $state->id
;
1004 $session->sumpenalty
= $state->sumpenalty
;
1005 $session->manualcomment
= $state->manualcomment
;
1007 $session->manualcomment
= addslashes($session->manualcomment
);
1009 update_record('question_sessions', $session);
1012 unset($state->answer
);
1014 // Save the question type specific state information and responses
1015 if (!$QTYPES[$question->qtype
]->save_session_and_responses(
1016 $question, $state)) {
1019 // Reset the changed flag
1020 $state->changed
= false;
1025 * Determines whether a state has been graded by looking at the event field
1027 * @return boolean true if the state has been graded
1028 * @param object $state
1030 function question_state_is_graded($state) {
1031 $gradedevents = explode(',', QUESTION_EVENTS_GRADED
);
1032 return (in_array($state->event
, $gradedevents));
1036 * Determines whether a state has been closed by looking at the event field
1038 * @return boolean true if the state has been closed
1039 * @param object $state
1041 function question_state_is_closed($state) {
1042 return ($state->event
== QUESTION_EVENTCLOSE
1043 or $state->event
== QUESTION_EVENTCLOSEANDGRADE
1044 or $state->event
== QUESTION_EVENTMANUALGRADE
);
1049 * Extracts responses from submitted form
1051 * This can extract the responses given to one or several questions present on a page
1052 * It returns an array with one entry for each question, indexed by question id
1053 * Each entry is an object with the properties
1054 * ->event The event that has triggered the submission. This is determined by which button
1055 * the user has pressed.
1056 * ->responses An array holding the responses to an individual question, indexed by the
1057 * name of the corresponding form element.
1058 * ->timestamp A unix timestamp
1059 * @return array array of action objects, indexed by question ids.
1060 * @param array $questions an array containing at least all questions that are used on the form
1061 * @param array $formdata the data submitted by the form on the question page
1062 * @param integer $defaultevent the event type used if no 'mark' or 'validate' is submitted
1064 function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE
) {
1068 foreach ($formdata as $key => $response) {
1069 // Get the question id from the response name
1070 if (false !== ($quid = question_get_id_from_name_prefix($key))) {
1071 // check if this is a valid id
1072 if (!isset($questions[$quid])) {
1073 error('Form contained question that is not in questionids');
1076 // Remove the name prefix from the name
1078 $key = substr($key, strlen($questions[$quid]->name_prefix
));
1079 if (false === $key) {
1082 // Check for question validate and mark buttons & set events
1083 if ($key === 'validate') {
1084 $actions[$quid]->event
= QUESTION_EVENTVALIDATE
;
1085 } else if ($key === 'submit') {
1086 $actions[$quid]->event
= QUESTION_EVENTSUBMIT
;
1088 $actions[$quid]->event
= $defaultevent;
1091 // Update the state with the new response
1092 $actions[$quid]->responses
[$key] = $response;
1094 // Set the timestamp
1095 $actions[$quid]->timestamp
= $time;
1098 foreach ($actions as $quid => $notused) {
1099 ksort($actions[$quid]->responses
);
1106 * Returns the html for question feedback image.
1107 * @param float $fraction value representing the correctness of the user's
1108 * response to a question.
1109 * @param boolean $selected whether or not the answer is the one that the
1113 function question_get_feedback_image($fraction, $selected=true) {
1117 if ($fraction >= 1.0) {
1119 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_green_big.gif" '.
1120 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
1122 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_green_small.gif" '.
1123 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
1125 } else if ($fraction > 0.0 && $fraction < 1.0) {
1127 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_amber_big.gif" '.
1128 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
1130 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_amber_small.gif" '.
1131 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
1135 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/cross_red_big.gif" '.
1136 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
1138 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/cross_red_small.gif" '.
1139 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
1142 return $feedbackimg;
1147 * Returns the class name for question feedback.
1148 * @param float $fraction value representing the correctness of the user's
1149 * response to a question.
1152 function question_get_feedback_class($fraction) {
1156 if ($fraction >= 1.0) {
1158 } else if ($fraction > 0.0 && $fraction < 1.0) {
1159 $class = 'partiallycorrect';
1161 $class = 'incorrect';
1168 * For a given question in an attempt we walk the complete history of states
1169 * and recalculate the grades as we go along.
1171 * This is used when a question is changed and old student
1172 * responses need to be marked with the new version of a question.
1174 * TODO: Make sure this is not quiz-specific
1176 * @return boolean Indicates whether the grade has changed
1177 * @param object $question A question object
1178 * @param object $attempt The attempt, in which the question needs to be regraded.
1179 * @param object $cmoptions
1180 * @param boolean $verbose Optional. Whether to print progress information or not.
1182 function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false) {
1184 // load all states for this question in this attempt, ordered in sequence
1185 if ($states = get_records_select('question_states',
1186 "attempt = '{$attempt->uniqueid}' AND question = '{$question->id}'",
1187 'seq_number ASC')) {
1188 $states = array_values($states);
1190 // Subtract the grade for the latest state from $attempt->sumgrades to get the
1191 // sumgrades for the attempt without this question.
1192 $attempt->sumgrades
-= $states[count($states)-1]->grade
;
1194 // Initialise the replaystate
1195 $state = clone($states[0]);
1196 $state->manualcomment
= get_field('question_sessions', 'manualcomment', 'attemptid',
1197 $attempt->uniqueid
, 'questionid', $question->id
);
1198 restore_question_state($question, $state);
1199 $state->sumpenalty
= 0.0;
1200 $replaystate = clone($state);
1201 $replaystate->last_graded
= $state;
1204 for($j = 1; $j < count($states); $j++
) {
1205 restore_question_state($question, $states[$j]);
1206 $action = new stdClass
;
1207 $action->responses
= $states[$j]->responses
;
1208 $action->timestamp
= $states[$j]->timestamp
;
1210 // Change event to submit so that it will be reprocessed
1211 if (QUESTION_EVENTCLOSE
== $states[$j]->event
1212 or QUESTION_EVENTGRADE
== $states[$j]->event
1213 or QUESTION_EVENTCLOSEANDGRADE
== $states[$j]->event
) {
1214 $action->event
= QUESTION_EVENTSUBMIT
;
1216 // By default take the event that was saved in the database
1218 $action->event
= $states[$j]->event
;
1221 if ($action->event
== QUESTION_EVENTMANUALGRADE
) {
1222 // Ensure that the grade is in range - in the past this was not checked,
1223 // but now it is (MDL-14835) - so we need to ensure the data is valid before
1225 if ($states[$j]->grade
< 0) {
1226 $states[$j]->grade
= 0;
1227 } else if ($states[$j]->grade
> $question->maxgrade
) {
1228 $states[$j]->grade
= $question->maxgrade
;
1230 $error = question_process_comment($question, $replaystate, $attempt,
1231 $replaystate->manualcomment
, $states[$j]->grade
);
1232 if (is_string($error)) {
1237 // Reprocess (regrade) responses
1238 if (!question_process_responses($question, $replaystate,
1239 $action, $cmoptions, $attempt)) {
1240 $verbose && notify("Couldn't regrade state #{$state->id}!");
1244 // We need rounding here because grades in the DB get truncated
1245 // e.g. 0.33333 != 0.3333333, but we want them to be equal here
1246 if ((round((float)$replaystate->raw_grade
, 5) != round((float)$states[$j]->raw_grade
, 5))
1247 or (round((float)$replaystate->penalty
, 5) != round((float)$states[$j]->penalty
, 5))
1248 or (round((float)$replaystate->grade
, 5) != round((float)$states[$j]->grade
, 5))) {
1252 $replaystate->id
= $states[$j]->id
;
1253 $replaystate->changed
= true;
1254 $replaystate->update
= true; // This will ensure that the existing database entry is updated rather than a new one created
1255 save_question_session($question, $replaystate);
1258 // TODO, call a method in quiz to do this, where 'quiz' comes from
1259 // the question_attempts table.
1260 update_record('quiz_attempts', $attempt);
1269 * Processes an array of student responses, grading and saving them as appropriate
1271 * @param object $question Full question object, passed by reference
1272 * @param object $state Full state object, passed by reference
1273 * @param object $action object with the fields ->responses which
1274 * is an array holding the student responses,
1275 * ->action which specifies the action, e.g., QUESTION_EVENTGRADE,
1276 * and ->timestamp which is a timestamp from when the responses
1277 * were submitted by the student.
1278 * @param object $cmoptions
1279 * @param object $attempt The attempt is passed by reference so that
1280 * during grading its ->sumgrades field can be updated
1281 * @return boolean Indicates success/failure
1283 function question_process_responses(&$question, &$state, $action, $cmoptions, &$attempt) {
1286 // if no responses are set initialise to empty response
1287 if (!isset($action->responses
)) {
1288 $action->responses
= array('' => '');
1291 // make sure these are gone!
1292 unset($action->responses
['submit'], $action->responses
['validate']);
1294 // Check the question session is still open
1295 if (question_state_is_closed($state)) {
1299 // If $action->event is not set that implies saving
1300 if (! isset($action->event
)) {
1301 debugging('Ambiguous action in question_process_responses.' , DEBUG_DEVELOPER
);
1302 $action->event
= QUESTION_EVENTSAVE
;
1304 // If submitted then compare against last graded
1305 // responses, not last given responses in this case
1306 if (question_isgradingevent($action->event
)) {
1307 $state->responses
= $state->last_graded
->responses
;
1310 // Check for unchanged responses (exactly unchanged, not equivalent).
1311 // We also have to catch questions that the student has not yet attempted
1312 $sameresponses = $QTYPES[$question->qtype
]->compare_responses($question, $action, $state);
1313 if (!empty($state->last_graded
) && $state->last_graded
->event
== QUESTION_EVENTOPEN
&&
1314 question_isgradingevent($action->event
)) {
1315 $sameresponses = false;
1318 // If the response has not been changed then we do not have to process it again
1319 // unless the attempt is closing or validation is requested
1320 if ($sameresponses and QUESTION_EVENTCLOSE
!= $action->event
1321 and QUESTION_EVENTVALIDATE
!= $action->event
) {
1325 // Roll back grading information to last graded state and set the new
1327 $newstate = clone($state->last_graded
);
1328 $newstate->responses
= $action->responses
;
1329 $newstate->seq_number
= $state->seq_number +
1;
1330 $newstate->changed
= true; // will assure that it gets saved to the database
1331 $newstate->last_graded
= clone($state->last_graded
);
1332 $newstate->timestamp
= $action->timestamp
;
1335 // Set the event to the action we will perform. The question type specific
1336 // grading code may override this by setting it to QUESTION_EVENTCLOSE if the
1337 // attempt at the question causes the session to close
1338 $state->event
= $action->event
;
1340 if (!question_isgradingevent($action->event
)) {
1341 // Grade the response but don't update the overall grade
1342 if (!$QTYPES[$question->qtype
]->grade_responses($question, $state, $cmoptions)) {
1346 // Temporary hack because question types are not given enough control over what is going
1347 // on. Used by Opaque questions.
1348 // TODO fix this code properly.
1349 if (!empty($state->believeevent
)) {
1350 // If the state was graded we need to ...
1351 if (question_state_is_graded($state)) {
1352 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1354 // update the attempt grade
1355 $attempt->sumgrades
-= (float)$state->last_graded
->grade
;
1356 $attempt->sumgrades +
= (float)$state->grade
;
1358 // and update the last_graded field.
1359 unset($state->last_graded
);
1360 $state->last_graded
= clone($state);
1361 unset($state->last_graded
->changed
);
1364 // Don't allow the processing to change the event type
1365 $state->event
= $action->event
;
1368 } else { // grading event
1370 // Unless the attempt is closing, we want to work out if the current responses
1371 // (or equivalent responses) were already given in the last graded attempt.
1372 if(QUESTION_EVENTCLOSE
!= $action->event
&& QUESTION_EVENTOPEN
!= $state->last_graded
->event
&&
1373 $QTYPES[$question->qtype
]->compare_responses($question, $state, $state->last_graded
)) {
1374 $state->event
= QUESTION_EVENTDUPLICATE
;
1377 // If we did not find a duplicate or if the attempt is closing, perform grading
1378 if ((!$sameresponses and QUESTION_EVENTDUPLICATE
!= $state->event
) or
1379 QUESTION_EVENTCLOSE
== $action->event
) {
1380 if (!$QTYPES[$question->qtype
]->grade_responses($question, $state, $cmoptions)) {
1384 // Calculate overall grade using correct penalty method
1385 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1388 // If the state was graded we need to ...
1389 if (question_state_is_graded($state)) {
1390 // update the attempt grade
1391 $attempt->sumgrades
-= (float)$state->last_graded
->grade
;
1392 $attempt->sumgrades +
= (float)$state->grade
;
1394 // and update the last_graded field.
1395 unset($state->last_graded
);
1396 $state->last_graded
= clone($state);
1397 unset($state->last_graded
->changed
);
1400 $attempt->timemodified
= $action->timestamp
;
1406 * Determine if event requires grading
1408 function question_isgradingevent($event) {
1409 return (QUESTION_EVENTSUBMIT
== $event || QUESTION_EVENTCLOSE
== $event);
1413 * Applies the penalty from the previous graded responses to the raw grade
1414 * for the current responses
1416 * The grade for the question in the current state is computed by subtracting the
1417 * penalty accumulated over the previous graded responses at the question from the
1418 * raw grade. If the timestamp is more than 1 minute beyond the end of the attempt
1419 * the grade is set to zero. The ->grade field of the state object is modified to
1420 * reflect the new grade but is never allowed to decrease.
1421 * @param object $question The question for which the penalty is to be applied.
1422 * @param object $state The state for which the grade is to be set from the
1423 * raw grade and the cumulative penalty from the last
1424 * graded state. The ->grade field is updated by applying
1425 * the penalty scheme determined in $cmoptions to the ->raw_grade and
1426 * ->last_graded->penalty fields.
1427 * @param object $cmoptions The options set by the course module.
1428 * The ->penaltyscheme field determines whether penalties
1429 * for incorrect earlier responses are subtracted.
1431 function question_apply_penalty_and_timelimit(&$question, &$state, $attempt, $cmoptions) {
1432 // TODO. Quiz dependancy. The fact that the attempt that is passed in here
1433 // is from quiz_attempts, and we use things like $cmoptions->timelimit.
1435 // deal with penalty
1436 if ($cmoptions->penaltyscheme
) {
1437 $state->grade
= $state->raw_grade
- $state->sumpenalty
;
1438 $state->sumpenalty +
= (float) $state->penalty
;
1440 $state->grade
= $state->raw_grade
;
1443 // deal with timelimit
1444 if ($cmoptions->timelimit
) {
1445 // We allow for 5% uncertainty in the following test
1446 if ($state->timestamp
- $attempt->timestart
> $cmoptions->timelimit
* 63) {
1447 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id
);
1448 if (!has_capability('mod/quiz:ignoretimelimits', get_context_instance(CONTEXT_MODULE
, $cm->id
),
1449 $attempt->userid
, false)) {
1455 // deal with closing time
1456 if ($cmoptions->timeclose
and $state->timestamp
> ($cmoptions->timeclose +
60) // allowing 1 minute lateness
1457 and !$attempt->preview
) { // ignore closing time for previews
1461 // Ensure that the grade does not go down
1462 $state->grade
= max($state->grade
, $state->last_graded
->grade
);
1466 * Print the icon for the question type
1468 * @param object $question The question object for which the icon is required
1469 * @param boolean $return If true the functions returns the link as a string
1471 function print_question_icon($question, $return = false) {
1472 global $QTYPES, $CFG;
1474 if (array_key_exists($question->qtype
, $QTYPES)) {
1475 $namestr = $QTYPES[$question->qtype
]->menu_name();
1477 $namestr = 'missingtype';
1479 $html = '<img src="' . $CFG->wwwroot
. '/question/type/' .
1480 $question->qtype
. '/icon.gif" alt="' .
1481 $namestr . '" title="' . $namestr . '" />';
1490 * Returns a html link to the question image if there is one
1492 * @return string The html image tag or the empy string if there is no image.
1493 * @param object $question The question object
1495 function get_question_image($question) {
1500 if (!$category = get_record('question_categories', 'id', $question->category
)){
1501 error('invalid category id '.$question->category
);
1503 $coursefilesdir = get_filesdir_from_context(get_context_instance_by_id($category->contextid
));
1505 if ($question->image
) {
1507 if (substr(strtolower($question->image
), 0, 7) == 'http://') {
1508 $img .= $question->image
;
1511 require_once($CFG->libdir
.'/filelib.php');
1512 $img = get_file_url("$coursefilesdir/{$question->image}");
1518 function question_print_comment_box($question, $state, $attempt, $url) {
1521 $prefix = 'response';
1522 $usehtmleditor = can_use_richtext_editor();
1523 $grade = round($state->last_graded
->grade
, 3);
1524 echo '<form method="post" action="'.$url.'">';
1525 include($CFG->dirroot
.'/question/comment.html');
1526 echo '<input type="hidden" name="attempt" value="'.$attempt->uniqueid
.'" />';
1527 echo '<input type="hidden" name="question" value="'.$question->id
.'" />';
1528 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1529 echo '<input type="submit" name="submit" value="'.get_string('save', 'quiz').'" />';
1532 if ($usehtmleditor) {
1538 * Process a manual grading action. That is, use $comment and $grade to update
1539 * $state and $attempt. The attempt and the comment text are stored in the
1540 * database. $state is only updated in memory, it is up to the call to store
1541 * that, if appropriate.
1543 * @param object $question the question
1544 * @param object $state the state to be updated.
1545 * @param object $attempt the attempt the state belongs to, to be updated.
1546 * @param string $comment the comment the teacher added
1547 * @param float $grade the grade the teacher assigned.
1548 * @return mixed true on success, a string error message if a problem is detected
1549 * (for example score out of range).
1551 function question_process_comment($question, &$state, &$attempt, $comment, $grade) {
1552 if ($grade < 0 ||
$grade > $question->maxgrade
) {
1555 $a->maxgrade
= $question->maxgrade
;
1556 $a->name
= $question->name
;
1557 return get_string('errormanualgradeoutofrange', 'question', $a);
1560 // Update the comment and save it in the database
1561 $comment = trim($comment);
1562 $state->manualcomment
= $comment;
1563 if (!set_field('question_sessions', 'manualcomment', $comment, 'attemptid', $attempt->uniqueid
, 'questionid', $question->id
)) {
1564 return get_string('errorsavingcomment', 'question', $question);
1567 // Update the attempt if the score has changed.
1568 if (abs($state->last_graded
->grade
- $grade) > 0.002) {
1569 $attempt->sumgrades
= $attempt->sumgrades
- $state->last_graded
->grade +
$grade;
1570 $attempt->timemodified
= time();
1571 if (!update_record('quiz_attempts', $attempt)) {
1572 return get_string('errorupdatingattempt', 'question', $attempt);
1576 // Update the state if either the score has changed, or this is the first
1577 // manual grade event and there is actually a grade of comment to process.
1578 // We don't need to store the modified state in the database, we just need
1579 // to set the $state->changed flag.
1580 if (abs($state->last_graded
->grade
- $grade) > 0.002 ||
1581 ($state->last_graded
->event
!= QUESTION_EVENTMANUALGRADE
&& ($grade > 0.002 ||
$comment != ''))) {
1583 // We want to update existing state (rather than creating new one) if it
1584 // was itself created by a manual grading event.
1585 $state->update
= ($state->event
== QUESTION_EVENTMANUALGRADE
) ?
1 : 0;
1587 // Update the other parts of the state object.
1588 $state->raw_grade
= $grade;
1589 $state->grade
= $grade;
1590 $state->penalty
= 0;
1591 $state->timestamp
= time();
1592 $state->seq_number++
;
1593 $state->event
= QUESTION_EVENTMANUALGRADE
;
1595 // Update the last graded state (don't simplify!)
1596 unset($state->last_graded
);
1597 $state->last_graded
= clone($state);
1599 // We need to indicate that the state has changed in order for it to be saved.
1600 $state->changed
= 1;
1607 * Construct name prefixes for question form element names
1609 * Construct the name prefix that should be used for example in the
1610 * names of form elements created by questions.
1611 * This is called by {@link get_question_options()}
1612 * to set $question->name_prefix.
1613 * This name prefix includes the question id which can be
1614 * extracted from it with {@link question_get_id_from_name_prefix()}.
1617 * @param integer $id The question id
1619 function question_make_name_prefix($id) {
1620 return 'resp' . $id . '_';
1624 * Extract question id from the prefix of form element names
1626 * @return integer The question id
1627 * @param string $name The name that contains a prefix that was
1628 * constructed with {@link question_make_name_prefix()}
1630 function question_get_id_from_name_prefix($name) {
1631 if (!preg_match('/^resp([0-9]+)_/', $name, $matches))
1633 return (integer) $matches[1];
1637 * Returns the unique id for a new attempt
1639 * Every module can keep their own attempts table with their own sequential ids but
1640 * the question code needs to also have a unique id by which to identify all these
1641 * attempts. Hence a module, when creating a new attempt, calls this function and
1642 * stores the return value in the 'uniqueid' field of its attempts table.
1644 function question_new_attempt_uniqueid($modulename='quiz') {
1646 $attempt = new stdClass
;
1647 $attempt->modulename
= $modulename;
1648 if (!$id = insert_record('question_attempts', $attempt)) {
1649 error('Could not create new entry in question_attempts table');
1655 * Creates a stamp that uniquely identifies this version of the question
1657 * In future we want this to use a hash of the question data to guarantee that
1658 * identical versions have the same version stamp.
1660 * @param object $question
1661 * @return string A unique version stamp
1663 function question_hash($question) {
1664 return make_unique_id_code();
1668 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
1670 * Get the HTML that needs to be included in the head tag when the
1671 * questions in $questionlist are printed in the gives states.
1673 * @param array $questionlist a list of questionids of the questions what will appear on this page.
1674 * @param array $questions an array of question objects, whose keys are question ids.
1675 * Must contain all the questions in $questionlist
1676 * @param array $states an array of question state objects, whose keys are question ids.
1677 * Must contain the state of all the questions in $questionlist
1679 * @return string some HTML code that can go inside the head tag.
1681 function get_html_head_contributions(&$questionlist, &$questions, &$states) {
1684 $contributions = array();
1685 foreach ($questionlist as $questionid) {
1686 $question = $questions[$questionid];
1687 $contributions = array_merge($contributions,
1688 $QTYPES[$question->qtype
]->get_html_head_contributions(
1689 $question, $states[$questionid]));
1691 return implode("\n", array_unique($contributions));
1697 * Simply calls the question type specific print_question() method.
1698 * @param object $question The question to be rendered.
1699 * @param object $state The state to render the question in.
1700 * @param integer $number The number for this question.
1701 * @param object $cmoptions The options specified by the course module
1702 * @param object $options An object specifying the rendering options.
1704 function print_question(&$question, &$state, $number, $cmoptions, $options=null) {
1707 $QTYPES[$question->qtype
]->print_question($question, $state, $number,
1708 $cmoptions, $options);
1711 * Saves question options
1713 * Simply calls the question type specific save_question_options() method.
1715 function save_question_options($question) {
1718 $QTYPES[$question->qtype
]->save_question_options($question);
1722 * Gets all teacher stored answers for a given question
1724 * Simply calls the question type specific get_all_responses() method.
1727 function get_question_responses($question, $state) {
1729 $r = $QTYPES[$question->qtype
]->get_all_responses($question, $state);
1735 * Gets the response given by the user in a particular state
1737 * Simply calls the question type specific get_actual_response() method.
1740 function get_question_actual_response($question, $state) {
1743 $r = $QTYPES[$question->qtype
]->get_actual_response($question, $state);
1748 * TODO: document this
1751 function get_question_fraction_grade($question, $state) {
1754 $r = $QTYPES[$question->qtype
]->get_fractional_grade($question, $state);
1759 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1762 * returns the categories with their names ordered following parent-child relationships
1763 * finally it tries to return pending categories (those being orphaned, whose parent is
1764 * incorrect) to avoid missing any category from original array.
1766 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1767 $children = array();
1768 $keys = array_keys($categories);
1770 foreach ($keys as $key) {
1771 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
1772 $children[$key] = $categories[$key];
1773 $categories[$key]->processed
= true;
1774 $children = $children +
sort_categories_by_tree($categories, $children[$key]->id
, $level+
1);
1777 //If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too
1779 foreach ($keys as $key) {
1780 //If not processed and it's a good candidate to start (because its parent doesn't exist in the course)
1781 if (!isset($categories[$key]->processed
) && !record_exists('question_categories', 'course', $categories[$key]->course
, 'id', $categories[$key]->parent
)) {
1782 $children[$key] = $categories[$key];
1783 $categories[$key]->processed
= true;
1784 $children = $children +
sort_categories_by_tree($categories, $children[$key]->id
, $level+
1);
1792 * Private method, only for the use of add_indented_names().
1794 * Recursively adds an indentedname field to each category, starting with the category
1795 * with id $id, and dealing with that category and all its children, and
1796 * return a new array, with those categories in the right order.
1798 * @param array $categories an array of categories which has had childids
1799 * fields added by flatten_category_tree(). Passed by reference for
1800 * performance only. It is not modfied.
1801 * @param int $id the category to start the indenting process from.
1802 * @param int $depth the indent depth. Used in recursive calls.
1803 * @return array a new array of categories, in the right order for the tree.
1805 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1807 // Indent the name of this category.
1808 $newcategories = array();
1809 $newcategories[$id] = $categories[$id];
1810 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) . $categories[$id]->name
;
1812 // Recursively indent the children.
1813 foreach ($categories[$id]->childids
as $childid) {
1814 if ($childid != $nochildrenof){
1815 $newcategories = $newcategories +
flatten_category_tree($categories, $childid, $depth +
1, $nochildrenof);
1819 // Remove the childids array that were temporarily added.
1820 unset($newcategories[$id]->childids
);
1822 return $newcategories;
1826 * Format categories into an indented list reflecting the tree structure.
1828 * @param array $categories An array of category objects, for example from the.
1829 * @return array The formatted list of categories.
1831 function add_indented_names($categories, $nochildrenof = -1) {
1833 // Add an array to each category to hold the child category ids. This array will be removed
1834 // again by flatten_category_tree(). It should not be used outside these two functions.
1835 foreach (array_keys($categories) as $id) {
1836 $categories[$id]->childids
= array();
1839 // Build the tree structure, and record which categories are top-level.
1840 // We have to be careful, because the categories array may include published
1841 // categories from other courses, but not their parents.
1842 $toplevelcategoryids = array();
1843 foreach (array_keys($categories) as $id) {
1844 if (!empty($categories[$id]->parent
) && array_key_exists($categories[$id]->parent
, $categories)) {
1845 $categories[$categories[$id]->parent
]->childids
[] = $id;
1847 $toplevelcategoryids[] = $id;
1851 // Flatten the tree to and add the indents.
1852 $newcategories = array();
1853 foreach ($toplevelcategoryids as $id) {
1854 $newcategories = $newcategories +
flatten_category_tree($categories, $id, 0, $nochildrenof);
1857 return $newcategories;
1861 * Output a select menu of question categories.
1863 * Categories from this course and (optionally) published categories from other courses
1864 * are included. Optionally, only categories the current user may edit can be included.
1866 * @param integer $courseid the id of the course to get the categories for.
1867 * @param integer $published if true, include publised categories from other courses.
1868 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1869 * @param integer $selected optionally, the id of a category to be selected by default in the dropdown.
1871 function question_category_select_menu($contexts, $top = false, $currentcat = 0, $selected = "", $nochildrenof = -1) {
1872 $categoriesarray = question_category_options($contexts, $top, $currentcat, false, $nochildrenof);
1876 $nothing = 'choose';
1878 choose_from_menu_nested($categoriesarray, 'category', $selected, $nothing);
1882 * Gets the default category in the most specific context.
1883 * If no categories exist yet then default ones are created in all contexts.
1885 * @param array $contexts The context objects for this context and all parent contexts.
1886 * @return object The default category - the category in the course context
1888 function question_make_default_categories($contexts) {
1890 // If it already exists, just return it.
1891 foreach ($contexts as $key => $context) {
1892 if (!$categoryrs = get_recordset_select("question_categories", "contextid = '{$context->id}'", 'sortorder, name', '*', '', 1)) {
1893 error('error getting category record');
1895 if (!$category = rs_fetch_record($categoryrs)){
1896 // Otherwise, we need to make one
1897 $category = new stdClass
;
1898 $contextname = print_context_name($context, false, true);
1899 $category->name
= addslashes(get_string('defaultfor', 'question', $contextname));
1900 $category->info
= addslashes(get_string('defaultinfofor', 'question', $contextname));
1901 $category->contextid
= $context->id
;
1902 $category->parent
= 0;
1903 $category->sortorder
= 999; // By default, all categories get this number, and are sorted alphabetically.
1904 $category->stamp
= make_unique_id_code();
1905 if (!$category->id
= insert_record('question_categories', $category)) {
1906 error('Error creating a default category for context '.print_context_name($context));
1910 if ($context->contextlevel
== CONTEXT_COURSE
){
1911 $toreturn = clone($category);
1920 * Get all the category objects, including a count of the number of questions in that category,
1921 * for all the categories in the lists $contexts.
1923 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1924 * @param string $sortorder used as the ORDER BY clause in the select statement.
1925 * @return array of category objects.
1927 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1929 return get_records_sql("
1930 SELECT *, (SELECT count(1) FROM {$CFG->prefix}question q
1931 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') as questioncount
1932 FROM {$CFG->prefix}question_categories c
1933 WHERE c.contextid IN ($contexts)
1934 ORDER BY $sortorder");
1938 * Output an array of question categories.
1940 function question_category_options($contexts, $top = false, $currentcat = 0, $popupform = false, $nochildrenof = -1) {
1942 $pcontexts = array();
1943 foreach($contexts as $context){
1944 $pcontexts[] = $context->id
;
1946 $contextslist = join($pcontexts, ', ');
1948 $categories = get_categories_for_contexts($contextslist);
1950 $categories = question_add_context_in_key($categories);
1953 $categories = question_add_tops($categories, $pcontexts);
1955 $categories = add_indented_names($categories, $nochildrenof);
1957 //sort cats out into different contexts
1958 $categoriesarray = array();
1959 foreach ($pcontexts as $pcontext){
1960 $contextstring = print_context_name(get_context_instance_by_id($pcontext), true, true);
1961 foreach ($categories as $category) {
1962 if ($category->contextid
== $pcontext){
1963 $cid = $category->id
;
1964 if ($currentcat!= $cid ||
$currentcat==0) {
1965 $countstring = (!empty($category->questioncount
))?
" ($category->questioncount)":'';
1966 $categoriesarray[$contextstring][$cid] = $category->indentedname
.$countstring;
1972 $popupcats = array();
1973 foreach ($categoriesarray as $contextstring => $optgroup){
1974 $popupcats[] = '--'.$contextstring;
1975 $popupcats = array_merge($popupcats, $optgroup);
1976 $popupcats[] = '--';
1980 return $categoriesarray;
1984 function question_add_context_in_key($categories){
1985 $newcatarray = array();
1986 foreach ($categories as $id => $category) {
1987 $category->parent
= "$category->parent,$category->contextid";
1988 $category->id
= "$category->id,$category->contextid";
1989 $newcatarray["$id,$category->contextid"] = $category;
1991 return $newcatarray;
1993 function question_add_tops($categories, $pcontexts){
1995 foreach ($pcontexts as $context){
1996 $newcat = new object();
1997 $newcat->id
= "0,$context";
1998 $newcat->name
= get_string('top');
1999 $newcat->parent
= -1;
2000 $newcat->contextid
= $context;
2001 $topcats["0,$context"] = $newcat;
2003 //put topcats in at beginning of array - they'll be sorted into different contexts later.
2004 return array_merge($topcats, $categories);
2008 * Returns a comma separated list of ids of the category and all subcategories
2010 function question_categorylist($categoryid) {
2011 // returns a comma separated list of ids of the category and all subcategories
2012 $categorylist = $categoryid;
2013 if ($subcategories = get_records('question_categories', 'parent', $categoryid, 'sortorder ASC', 'id, id')) {
2014 foreach ($subcategories as $subcategory) {
2015 $categorylist .= ','. question_categorylist($subcategory->id
);
2018 return $categorylist;
2024 //===========================
2025 // Import/Export Functions
2026 //===========================
2029 * Get list of available import or export formats
2030 * @param string $type 'import' if import list, otherwise export list assumed
2031 * @return array sorted list of import/export formats available
2033 function get_import_export_formats( $type ) {
2036 $fileformats = get_list_of_plugins("question/format");
2038 $fileformatname=array();
2039 require_once( "{$CFG->dirroot}/question/format.php" );
2040 foreach ($fileformats as $key => $fileformat) {
2041 $format_file = $CFG->dirroot
. "/question/format/$fileformat/format.php";
2042 if (file_exists( $format_file ) ) {
2043 require_once( $format_file );
2048 $classname = "qformat_$fileformat";
2049 $format_class = new $classname();
2050 if ($type=='import') {
2051 $provided = $format_class->provide_import();
2054 $provided = $format_class->provide_export();
2057 $formatname = get_string($fileformat, 'quiz');
2058 if ($formatname == "[[$fileformat]]") {
2059 $formatname = $fileformat; // Just use the raw folder name
2061 $fileformatnames[$fileformat] = $formatname;
2064 natcasesort($fileformatnames);
2066 return $fileformatnames;
2071 * Create default export filename
2073 * @return string default export filename
2074 * @param object $course
2075 * @param object $category
2077 function default_export_filename($course,$category) {
2078 //Take off some characters in the filename !!
2079 $takeoff = array(" ", ":", "/", "\\", "|");
2080 $export_word = str_replace($takeoff,"_",moodle_strtolower(get_string("exportfilename","quiz")));
2081 //If non-translated, use "export"
2082 if (substr($export_word,0,1) == "[") {
2083 $export_word= "export";
2086 //Calculate the date format string
2087 $export_date_format = str_replace(" ","_",get_string("exportnameformat","quiz"));
2088 //If non-translated, use "%Y%m%d-%H%M"
2089 if (substr($export_date_format,0,1) == "[") {
2090 $export_date_format = "%%Y%%m%%d-%%H%%M";
2093 //Calculate the shortname
2094 $export_shortname = clean_filename($course->shortname
);
2095 if (empty($export_shortname) or $export_shortname == '_' ) {
2096 $export_shortname = $course->id
;
2099 //Calculate the category name
2100 $export_categoryname = clean_filename($category->name
);
2102 //Calculate the final export filename
2104 $export_name = $export_word."-";
2106 $export_name .= moodle_strtolower($export_shortname)."-";
2108 $export_name .= moodle_strtolower($export_categoryname)."-";
2110 $export_name .= userdate(time(),$export_date_format,99,false);
2111 //Extension is supplied by format later.
2113 return $export_name;
2115 class context_to_string_translator
{
2117 * @var array used to translate between contextids and strings for this context.
2119 var $contexttostringarray = array();
2121 function context_to_string_translator($contexts){
2122 $this->generate_context_to_string_array($contexts);
2125 function context_to_string($contextid){
2126 return $this->contexttostringarray
[$contextid];
2129 function string_to_context($contextname){
2130 $contextid = array_search($contextname, $this->contexttostringarray
);
2134 function generate_context_to_string_array($contexts){
2135 if (!$this->contexttostringarray
){
2137 foreach ($contexts as $context){
2138 switch ($context->contextlevel
){
2139 case CONTEXT_MODULE
:
2140 $contextstring = 'module';
2142 case CONTEXT_COURSE
:
2143 $contextstring = 'course';
2145 case CONTEXT_COURSECAT
:
2146 $contextstring = "cat$catno";
2149 case CONTEXT_SYSTEM
:
2150 $contextstring = 'system';
2153 $this->contexttostringarray
[$context->id
] = $contextstring;
2162 * Check capability on category
2163 * @param mixed $question object or id
2164 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
2165 * @param integer $cachecat useful to cache all question records in a category
2166 * @return boolean this user has the capability $cap for this question $question?
2168 function question_has_capability_on($question, $cap, $cachecat = -1){
2170 // nicolasconnault@gmail.com In some cases I get $question === false. Since no such object exists, it can't be deleted, we can safely return true
2171 if ($question === false) {
2175 // these are capabilities on existing questions capabilties are
2176 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
2177 $question_questioncaps = array('edit', 'view', 'use', 'move');
2178 static $questions = array();
2179 static $categories = array();
2180 static $cachedcat = array();
2181 if ($cachecat != -1 && (array_search($cachecat, $cachedcat)===FALSE)){
2182 $questions +
= get_records('question', 'category', $cachecat);
2183 $cachedcat[] = $cachecat;
2185 if (!is_object($question)){
2186 if (!isset($questions[$question])){
2187 if (!$questions[$question] = get_record('question', 'id', $question)){
2188 print_error('questiondoesnotexist', 'question');
2191 $question = $questions[$question];
2193 if (!isset($categories[$question->category
])){
2194 if (!$categories[$question->category
] = get_record('question_categories', 'id', $question->category
)){
2195 print_error('invalidcategory', 'quiz');
2198 $category = $categories[$question->category
];
2200 if (array_search($cap, $question_questioncaps)!== FALSE){
2201 if (!has_capability('moodle/question:'.$cap.'all', get_context_instance_by_id($category->contextid
))){
2202 if ($question->createdby
== $USER->id
){
2203 return has_capability('moodle/question:'.$cap.'mine', get_context_instance_by_id($category->contextid
));
2211 return has_capability('moodle/question:'.$cap, get_context_instance_by_id($category->contextid
));
2217 * Require capability on question.
2219 function question_require_capability_on($question, $cap){
2220 if (!question_has_capability_on($question, $cap)){
2221 print_error('nopermissions', '', '', $cap);
2226 function question_file_links_base_url($courseid){
2228 $baseurl = preg_quote("$CFG->wwwroot/file.php", '!');
2229 $baseurl .= '('.preg_quote('?file=', '!').')?';//may or may not
2230 //be using slasharguments, accept either
2231 $baseurl .= "/$courseid/";//course directory
2236 * Find all course / site files linked to in a piece of html.
2237 * @param string html the html to search
2238 * @param int course search for files for courseid course or set to siteid for
2239 * finding site files.
2240 * @return array files with keys being files.
2242 function question_find_file_links_from_html($html, $courseid){
2244 $baseurl = question_file_links_base_url($courseid);
2246 '(<\s*(a|img)\s[^>]*(href|src)\s*=\s*")'.$baseurl.'([^"]*)"'.
2248 '(<\s*(a|img)\s[^>]*(href|src)\s*=\s*\')'.$baseurl.'([^\']*)\''.
2251 $no = preg_match_all($searchfor, $html, $matches);
2253 $rawurls = array_filter(array_merge($matches[5], $matches[10]));//array_filter removes empty elements
2254 //remove any links that point somewhere they shouldn't
2255 foreach (array_keys($rawurls) as $rawurlkey){
2256 if (!$cleanedurl = question_url_check($rawurls[$rawurlkey])){
2257 unset($rawurls[$rawurlkey]);
2259 $rawurls[$rawurlkey] = $cleanedurl;
2263 $urls = array_flip($rawurls);// array_flip removes duplicate files
2264 // and when we merge arrays will continue to automatically remove duplicates
2271 * Check that url doesn't point anywhere it shouldn't
2273 * @param $url string relative url within course files directory
2274 * @return mixed boolean false if not OK or cleaned URL as string if OK
2276 function question_url_check($url){
2278 if ((substr(strtolower($url), 0, strlen($CFG->moddata
)) == strtolower($CFG->moddata
)) ||
2279 (substr(strtolower($url), 0, 10) == 'backupdata')){
2282 return clean_param($url, PARAM_PATH
);
2287 * Find all course / site files linked to in a piece of html.
2288 * @param string html the html to search
2289 * @param int course search for files for courseid course or set to siteid for
2290 * finding site files.
2291 * @return array files with keys being files.
2293 function question_replace_file_links_in_html($html, $fromcourseid, $tocourseid, $url, $destination, &$changed){
2295 require_once($CFG->libdir
.'/filelib.php');
2296 $tourl = get_file_url("$tocourseid/$destination");
2297 $fromurl = question_file_links_base_url($fromcourseid).preg_quote($url, '!');
2298 $searchfor = array('!(<\s*(a|img)\s[^>]*(href|src)\s*=\s*")'.$fromurl.'(")!i',
2299 '!(<\s*(a|img)\s[^>]*(href|src)\s*=\s*\')'.$fromurl.'(\')!i');
2300 $newhtml = preg_replace($searchfor, '\\1'.$tourl.'\\5', $html);
2301 if ($newhtml != $html){
2307 function get_filesdir_from_context($context){
2308 switch ($context->contextlevel
){
2309 case CONTEXT_COURSE
:
2310 $courseid = $context->instanceid
;
2312 case CONTEXT_MODULE
:
2313 $courseid = get_field('course_modules', 'course', 'id', $context->instanceid
);
2315 case CONTEXT_COURSECAT
:
2316 case CONTEXT_SYSTEM
:
2320 error('Unsupported contextlevel in category record!');