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
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");
52 define("ESSAY", "essay");
56 * Constant determines the number of answer boxes supplied in the editing
57 * form for multiple choice and similar question types.
59 define("QUESTION_NUMANS", "10");
62 * Constant determines the number of answer boxes supplied in the editing
63 * form for multiple choice and similar question types to start with, with
64 * the option of adding QUESTION_NUMANS_ADD more answers.
66 define("QUESTION_NUMANS_START", 3);
69 * Constant determines the number of answer boxes to add in the editing
70 * form for multiple choice and similar question types when the user presses
71 * 'add form fields button'.
73 define("QUESTION_NUMANS_ADD", 3);
76 * The options used when popping up a question preview window in Javascript.
78 define('QUESTION_PREVIEW_POPUP_OPTIONS', 'scrollbars=yes,resizable=yes,width=700,height=540');
81 * Option flags for ->optionflags
82 * The options are read out via bitwise operation using these constants
85 * Whether the questions is to be run in adaptive mode. If this is not set then
86 * a question closes immediately after the first submission of responses. This
87 * is how question is Moodle always worked before version 1.5
89 define('QUESTION_ADAPTIVE', 1);
93 /// QTYPES INITIATION //////////////////
94 // These variables get initialised via calls to question_register_questiontype
95 // as the question type classes are included.
96 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
98 * Array holding question type objects
102 * Array of question types names translated to the user's language
104 * The $QTYPE_MENU array holds the names of all the question types that the user should
105 * be able to create directly. Some internal question types like random questions are excluded.
106 * The complete list of question types can be found in {@link $QTYPES}.
108 $QTYPE_MENU = array();
110 * String in the format "'type1','type2'" that can be used in SQL clauses like
111 * "WHERE q.type IN ($QTYPE_MANUAL)".
115 * String in the format "'type1','type2'" that can be used in SQL clauses like
116 * "WHERE q.type NOT IN ($QTYPE_EXCLUDE_FROM_RANDOM)".
118 $QTYPE_EXCLUDE_FROM_RANDOM = '';
121 * Add a new question type to the various global arrays above.
123 * @param object $qtype An instance of the new question type class.
125 function question_register_questiontype($qtype) {
126 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
128 $name = $qtype->name();
129 $QTYPES[$name] = $qtype;
130 $menuname = $qtype->menu_name();
132 $QTYPE_MENU[$name] = $menuname;
134 if ($qtype->is_manual_graded()) {
136 $QTYPE_MANUAL .= ',';
138 $QTYPE_MANUAL .= "'$name'";
140 if (!$qtype->is_usable_by_random()) {
141 if ($QTYPE_EXCLUDE_FROM_RANDOM) {
142 $QTYPE_EXCLUDE_FROM_RANDOM .= ',';
144 $QTYPE_EXCLUDE_FROM_RANDOM .= "'$name'";
148 require_once("$CFG->dirroot/question/type/questiontype.php");
150 // Load the questiontype.php file for each question type
151 // These files in turn call question_register_questiontype()
152 // with a new instance of each qtype class.
153 $qtypenames= get_list_of_plugins('question/type');
154 foreach($qtypenames as $qtypename) {
155 // Instanciates all plug-in question types
156 $qtypefilepath= "$CFG->dirroot/question/type/$qtypename/questiontype.php";
158 // echo "Loading $qtypename<br/>"; // Uncomment for debugging
159 if (is_readable($qtypefilepath)) {
160 require_once($qtypefilepath);
164 /// OTHER CLASSES /////////////////////////////////////////////////////////
167 * This holds the options that are set by the course module
171 * Whether a new attempt should be based on the previous one. If true
172 * then a new attempt will start in a state where all responses are set
173 * to the last responses from the previous attempt.
175 var $attemptonlast = false;
178 * Various option flags. The flags are accessed via bitwise operations
179 * using the constants defined in the CONSTANTS section above.
181 var $optionflags = QUESTION_ADAPTIVE
;
184 * Determines whether in the calculation of the score for a question
185 * penalties for earlier wrong responses within the same attempt will
188 var $penaltyscheme = true;
191 * The maximum time the user is allowed to answer the questions withing
192 * an attempt. This is measured in minutes so needs to be multiplied by
193 * 60 before compared to timestamps. If set to 0 no timelimit will be applied
198 * Timestamp for the closing time. Responses submitted after this time will
199 * be saved but no credit will be given for them.
201 var $timeclose = 9999999999;
204 * The id of the course from withing which the question is currently being used
206 var $course = SITEID
;
209 * Whether the answers in a multiple choice question should be randomly
210 * shuffled when a new attempt is started.
212 var $shuffleanswers = true;
215 * The number of decimals to be shown when scores are printed
217 var $decimalpoints = 2;
221 /// FUNCTIONS //////////////////////////////////////////////////////
224 * Returns an array of names of activity modules that use this question
226 * @param object $questionid
227 * @return array of strings
229 function question_list_instances($questionid) {
230 $instances = array();
231 $modules = get_records('modules');
232 foreach ($modules as $module) {
233 $fn = $module->name
.'_question_list_instances';
234 if (function_exists($fn)) {
235 $instances = $instances +
$fn($questionid);
243 * Returns list of 'allowed' grades for grade selection
244 * formatted suitably for dropdown box function
245 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
247 function get_grade_options() {
248 // define basic array of grades
271 // iterate through grades generating full range of options
272 $gradeoptionsfull = array();
273 $gradeoptions = array();
274 foreach ($grades as $grade) {
275 $percentage = 100 * $grade;
277 $gradeoptions["$grade"] = "$percentage %";
278 $gradeoptionsfull["$grade"] = "$percentage %";
279 $gradeoptionsfull["$neggrade"] = -$percentage." %";
281 $gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
284 arsort($gradeoptions, SORT_NUMERIC
);
285 arsort($gradeoptionsfull, SORT_NUMERIC
);
287 // construct return object
288 $grades = new stdClass
;
289 $grades->gradeoptions
= $gradeoptions;
290 $grades->gradeoptionsfull
= $gradeoptionsfull;
296 * match grade options
297 * if no match return error or match nearest
298 * @param array $gradeoptionsfull list of valid options
299 * @param int $grade grade to be tested
300 * @param string $matchgrades 'error' or 'nearest'
301 * @return mixed either 'fixed' value or false if erro
303 function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
304 // if we just need an error...
305 if ($matchgrades=='error') {
306 foreach($gradeoptionsfull as $value => $option) {
307 // slightly fuzzy test, never check floats for equality :-)
308 if (abs($grade-$value)<0.00001) {
312 // didn't find a match so that's an error
315 // work out nearest value
316 else if ($matchgrades=='nearest') {
318 foreach($gradeoptionsfull as $value => $option) {
319 if ($grade==$value) {
322 $hownear[ $value ] = abs( $grade - $value );
324 // reverse sort list of deltas and grab the last (smallest)
325 asort( $hownear, SORT_NUMERIC
);
327 return key( $hownear );
335 * Tests whether a category is in use by any activity module
338 * @param integer $categoryid
339 * @param boolean $recursive Whether to examine category children recursively
341 function question_category_isused($categoryid, $recursive = false) {
343 //Look at each question in the category
344 if ($questions = get_records('question', 'category', $categoryid)) {
345 foreach ($questions as $question) {
346 if (count(question_list_instances($question->id
))) {
352 //Look under child categories recursively
354 if ($children = get_records('question_categories', 'parent', $categoryid)) {
355 foreach ($children as $child) {
356 if (question_category_isused($child->id
, $recursive)) {
367 * Deletes all data associated to an attempt from the database
369 * @param integer $attemptid The id of the attempt being deleted
371 function delete_attempt($attemptid) {
374 $states = get_records('question_states', 'attempt', $attemptid);
376 $stateslist = implode(',', array_keys($states));
378 // delete question-type specific data
379 foreach ($QTYPES as $qtype) {
380 $qtype->delete_states($stateslist);
384 // delete entries from all other question tables
385 // It is important that this is done only after calling the questiontype functions
386 delete_records("question_states", "attempt", $attemptid);
387 delete_records("question_sessions", "attemptid", $attemptid);
388 delete_records("question_attempts", "id", $attemptid);
392 * Deletes question and all associated data from the database
394 * It will not delete a question if it is used by an activity module
395 * @param object $question The question being deleted
397 function delete_question($questionid) {
400 // Do not delete a question if it is used by an activity module
401 if (count(question_list_instances($questionid))) {
405 // delete questiontype-specific data
406 if ($question = get_record('question', 'id', $questionid)) {
407 if (isset($QTYPES[$question->qtype
])) {
408 $QTYPES[$question->qtype
]->delete_question($questionid);
411 echo "Question with id $questionid does not exist.<br />";
414 if ($states = get_records('question_states', 'question', $questionid)) {
415 $stateslist = implode(',', array_keys($states));
417 // delete questiontype-specific data
418 foreach ($QTYPES as $qtype) {
419 $qtype->delete_states($stateslist);
423 // delete entries from all other question tables
424 // It is important that this is done only after calling the questiontype functions
425 delete_records("question_answers", "question", $questionid);
426 delete_records("question_states", "question", $questionid);
427 delete_records("question_sessions", "questionid", $questionid);
429 // Now recursively delete all child questions
430 if ($children = get_records('question', 'parent', $questionid)) {
431 foreach ($children as $child) {
432 if ($child->id
!= $questionid) {
433 delete_question($child->id
);
438 // Finally delete the question record itself
439 delete_records('question', 'id', $questionid);
445 * All non-used question categories and their questions are deleted and
446 * categories still used by other courses are moved to the site course.
448 * @param object $course an object representing the course
449 * @param boolean $feedback to specify if the process must output a summary of its work
452 function question_delete_course($course, $feedback=true) {
454 global $CFG, $QTYPES;
456 //To detect if we have created the "container category"
459 //The "container" category we'll create if we need if
460 $contcat = new object;
462 //To temporary store changes performed with parents
463 $parentchanged = array();
465 //To store feedback to be showed at the end of the process
466 $feedbackdata = array();
469 $strcatcontainer=get_string('containercategorycreated', 'quiz');
470 $strcatmoved = get_string('usedcategorymoved', 'quiz');
471 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
473 if ($categories = get_records('question_categories', 'course', $course->id
, 'parent', 'id, parent, name, course')) {
475 //Sort categories following their tree (parent-child) relationships
476 $categories = sort_categories_by_tree($categories);
478 foreach ($categories as $cat) {
480 //Get the full record
481 $category = get_record('question_categories', 'id', $cat->id
);
483 //Check if the category is being used anywhere
484 if(question_category_isused($category->id
, true)) {
485 //It's being used. Cannot delete it, so:
486 //Create a container category in SITEID course if it doesn't exist
488 $concat = new stdClass
;
489 $concat->course
= SITEID
;
490 if (!isset($course->shortname
)) {
491 $course->shortname
= 'id=' . $course->id
;
493 $concat->name
= get_string('savedfromdeletedcourse', 'quiz', format_string($course->shortname
));
494 $concat->info
= $concat->name
;
495 $concat->publish
= 1;
496 $concat->stamp
= make_unique_id_code();
497 $concatid = insert_record('question_categories', $concat);
500 $feedbackdata[] = array($concat->name
, $strcatcontainer);
502 //Move the category to the container category in SITEID course
503 $category->course
= SITEID
;
504 //Assign to container if the category hasn't parent or if the parent is wrong (not belongs to the course)
505 if (!$category->parent ||
!isset($categories[$category->parent
])) {
506 $category->parent
= $concatid;
508 //If it's being used, its publish field should be 1
509 $category->publish
= 1;
511 update_record('question_categories', $category);
513 //Save this parent change for future use
514 $parentchanged[$category->id
] = $category->parent
;
517 $feedbackdata[] = array($category->name
, $strcatmoved);
520 //Category isn't being used so:
521 //Delete it completely (questions and category itself)
523 if ($questions = get_records("question", "category", $category->id
)) {
524 foreach ($questions as $question) {
525 delete_question($question->id
);
527 delete_records("question", "category", $category->id
);
529 //delete the category
530 delete_records('question_categories', 'id', $category->id
);
532 //Save this parent change for future use
533 if (!empty($category->parent
)) {
534 $parentchanged[$category->id
] = $category->parent
;
536 $parentchanged[$category->id
] = $concatid;
539 //Update all its child categories to re-parent them to grandparent.
540 set_field ('question_categories', 'parent', $parentchanged[$category->id
], 'parent', $category->id
);
543 $feedbackdata[] = array($category->name
, $strcatdeleted);
546 //Inform about changes performed if feedback is enabled
548 $table = new stdClass
;
549 $table->head
= array(get_string('category','quiz'), get_string('action'));
550 $table->data
= $feedbackdata;
557 function questionbank_navigation_tabs(&$row, $context, $querystring) {
559 if (has_capability('moodle/question:manage', $context)) {
560 $row[] = new tabobject('questions', "$CFG->wwwroot/question/edit.php?$querystring", get_string('questions', 'quiz'), get_string('editquestions', "quiz"));
563 if (has_capability('moodle/question:managecategory', $context)) {
564 $row[] = new tabobject('categories', "$CFG->wwwroot/question/category.php?$querystring", get_string('categories', 'quiz'), get_string('editqcats', 'quiz'));
567 if (has_capability('moodle/question:import', $context)) {
568 $row[] = new tabobject('import', "$CFG->wwwroot/question/import.php?$querystring", get_string('import', 'quiz'), get_string('importquestions', 'quiz'));
571 if (has_capability('moodle/question:export', $context)) {
572 $row[] = new tabobject('export', "$CFG->wwwroot/question/export.php?$querystring", get_string('export', 'quiz'), get_string('exportquestions', 'quiz'));
577 * Private function to factor common code out of get_question_options().
579 * @param object $question the question to tidy.
580 * @return boolean true if successful, else false.
582 function _tidy_question(&$question) {
584 if (!array_key_exists($question->qtype
, $QTYPES)) {
585 $question->qtype
= 'missingtype';
586 $question->questiontext
= '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext
;
588 $question->name_prefix
= question_make_name_prefix($question->id
);
589 return $QTYPES[$question->qtype
]->get_question_options($question);
593 * Updates the question objects with question type specific
594 * information by calling {@link get_question_options()}
596 * Can be called either with an array of question objects or with a single
599 * @param mixed $questions Either an array of question objects to be updated
600 * or just a single question object
601 * @return bool Indicates success or failure.
603 function get_question_options(&$questions) {
604 if (is_array($questions)) { // deal with an array of questions
605 foreach ($questions as $i => $notused) {
606 if (!_tidy_question($questions[$i])) {
611 } else { // deal with single question
612 return _tidy_question($questions);
617 * Loads the most recent state of each question session from the database
620 * For each question the most recent session state for the current attempt
621 * is loaded from the question_states table and the question type specific data and
622 * responses are added by calling {@link restore_question_state()} which in turn
623 * calls {@link restore_session_and_responses()} for each question.
624 * If no states exist for the question instance an empty state object is
625 * created representing the start of a session and empty question
626 * type specific information and responses are created by calling
627 * {@link create_session_and_responses()}.
629 * @return array An array of state objects representing the most recent
630 * states of the question sessions.
631 * @param array $questions The questions for which sessions are to be restored or
633 * @param object $cmoptions
634 * @param object $attempt The attempt for which the question sessions are
635 * to be restored or created.
636 * @param mixed either the id of a previous attempt, if this attmpt is
637 * building on a previous one, or false for a clean attempt.
639 function get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) {
640 global $CFG, $QTYPES;
642 // get the question ids
643 $ids = array_keys($questions);
644 $questionlist = implode(',', $ids);
646 // The question field must be listed first so that it is used as the
647 // array index in the array returned by get_records_sql
648 $statefields = 'n.questionid as question, s.*, n.sumpenalty, n.manualcomment';
649 // Load the newest states for the questions
650 $sql = "SELECT $statefields".
651 " FROM {$CFG->prefix}question_states s,".
652 " {$CFG->prefix}question_sessions n".
653 " WHERE s.id = n.newest".
654 " AND n.attemptid = '$attempt->uniqueid'".
655 " AND n.questionid IN ($questionlist)";
656 $states = get_records_sql($sql);
658 // Load the newest graded states for the questions
659 $sql = "SELECT $statefields".
660 " FROM {$CFG->prefix}question_states s,".
661 " {$CFG->prefix}question_sessions n".
662 " WHERE s.id = n.newgraded".
663 " AND n.attemptid = '$attempt->uniqueid'".
664 " AND n.questionid IN ($questionlist)";
665 $gradedstates = get_records_sql($sql);
667 // loop through all questions and set the last_graded states
668 foreach ($ids as $i) {
669 if (isset($states[$i])) {
670 restore_question_state($questions[$i], $states[$i]);
671 if (isset($gradedstates[$i])) {
672 restore_question_state($questions[$i], $gradedstates[$i]);
673 $states[$i]->last_graded
= $gradedstates[$i];
675 $states[$i]->last_graded
= clone($states[$i]);
678 // If the new attempt is to be based on a previous attempt get it and clean things
679 // Having lastattemptid filled implies that (should we double check?):
680 // $attempt->attempt > 1 and $cmoptions->attemptonlast and !$attempt->preview
681 if ($lastattemptid) {
682 // find the responses from the previous attempt and save them to the new session
684 // Load the last graded state for the question
685 $statefields = 'n.questionid as question, s.*, n.sumpenalty';
686 $sql = "SELECT $statefields".
687 " FROM {$CFG->prefix}question_states s,".
688 " {$CFG->prefix}question_sessions n".
689 " WHERE s.id = n.newgraded".
690 " AND n.attemptid = '$lastattemptid'".
691 " AND n.questionid = '$i'";
692 if (!$laststate = get_record_sql($sql)) {
693 // Only restore previous responses that have been graded
696 // Restore the state so that the responses will be restored
697 restore_question_state($questions[$i], $laststate);
698 $states[$i] = clone ($laststate);
700 // create a new empty state
701 $states[$i] = new object;
704 // now fill/overide initial values
705 $states[$i]->attempt
= $attempt->uniqueid
;
706 $states[$i]->question
= (int) $i;
707 $states[$i]->seq_number
= 0;
708 $states[$i]->timestamp
= $attempt->timestart
;
709 $states[$i]->event
= ($attempt->timefinish
) ? QUESTION_EVENTCLOSE
: QUESTION_EVENTOPEN
;
710 $states[$i]->grade
= 0;
711 $states[$i]->raw_grade
= 0;
712 $states[$i]->penalty
= 0;
713 $states[$i]->sumpenalty
= 0;
714 $states[$i]->manualcomment
= '';
716 // if building on last attempt we want to preserve responses
717 if (!$lastattemptid) {
718 $states[$i]->responses
= array('' => '');
720 // Prevent further changes to the session from incrementing the
722 $states[$i]->changed
= true;
724 if ($lastattemptid) {
725 // prepare the previous responses for new processing
726 $action = new stdClass
;
727 $action->responses
= $laststate->responses
;
728 $action->timestamp
= $laststate->timestamp
;
729 $action->event
= QUESTION_EVENTSAVE
; //emulate save of questions from all pages MDL-7631
731 // Process these responses ...
732 question_process_responses($questions[$i], $states[$i], $action, $cmoptions, $attempt);
734 // Fix for Bug #5506: When each attempt is built on the last one,
735 // preserve the options from any previous attempt.
736 if ( isset($laststate->options
) ) {
737 $states[$i]->options
= $laststate->options
;
740 // Create the empty question type specific information
741 if (!$QTYPES[$questions[$i]->qtype
]->create_session_and_responses(
742 $questions[$i], $states[$i], $cmoptions, $attempt)) {
746 $states[$i]->last_graded
= clone($states[$i]);
754 * Creates the run-time fields for the states
756 * Extends the state objects for a question by calling
757 * {@link restore_session_and_responses()}
758 * @param object $question The question for which the state is needed
759 * @param object $state The state as loaded from the database
760 * @return boolean Represents success or failure
762 function restore_question_state(&$question, &$state) {
765 // initialise response to the value in the answer field
766 $state->responses
= array('' => addslashes($state->answer
));
767 unset($state->answer
);
768 $state->manualcomment
= isset($state->manualcomment
) ?
addslashes($state->manualcomment
) : '';
770 // Set the changed field to false; any code which changes the
771 // question session must set this to true and must increment
772 // ->seq_number. The save_question_session
773 // function will save the new state object to the database if the field is
775 $state->changed
= false;
777 // Load the question type specific data
778 return $QTYPES[$question->qtype
]
779 ->restore_session_and_responses($question, $state);
784 * Saves the current state of the question session to the database
786 * The state object representing the current state of the session for the
787 * question is saved to the question_states table with ->responses[''] saved
788 * to the answer field of the database table. The information in the
789 * question_sessions table is updated.
790 * The question type specific data is then saved.
791 * @return mixed The id of the saved or updated state or false
792 * @param object $question The question for which session is to be saved.
793 * @param object $state The state information to be saved. In particular the
794 * most recent responses are in ->responses. The object
795 * is updated to hold the new ->id.
797 function save_question_session(&$question, &$state) {
799 // Check if the state has changed
800 if (!$state->changed
&& isset($state->id
)) {
803 // Set the legacy answer field
804 $state->answer
= isset($state->responses
['']) ?
$state->responses
[''] : '';
807 if (!empty($state->update
)) { // this forces the old state record to be overwritten
808 update_record('question_states', $state);
810 if (!$state->id
= insert_record('question_states', $state)) {
812 unset($state->answer
);
817 // create or update the session
818 if (!$session = get_record('question_sessions', 'attemptid',
819 $state->attempt
, 'questionid', $question->id
)) {
820 $session->attemptid
= $state->attempt
;
821 $session->questionid
= $question->id
;
822 $session->newest
= $state->id
;
823 // The following may seem weird, but the newgraded field needs to be set
824 // already even if there is no graded state yet.
825 $session->newgraded
= $state->id
;
826 $session->sumpenalty
= $state->sumpenalty
;
827 $session->manualcomment
= $state->manualcomment
;
828 if (!insert_record('question_sessions', $session)) {
829 error('Could not insert entry in question_sessions');
832 $session->newest
= $state->id
;
833 if (question_state_is_graded($state) or $state->event
== QUESTION_EVENTOPEN
) {
834 // this state is graded or newly opened, so it goes into the lastgraded field as well
835 $session->newgraded
= $state->id
;
836 $session->sumpenalty
= $state->sumpenalty
;
837 $session->manualcomment
= $state->manualcomment
;
839 $session->manualcomment
= addslashes($session->manualcomment
);
841 update_record('question_sessions', $session);
844 unset($state->answer
);
846 // Save the question type specific state information and responses
847 if (!$QTYPES[$question->qtype
]->save_session_and_responses(
848 $question, $state)) {
851 // Reset the changed flag
852 $state->changed
= false;
857 * Determines whether a state has been graded by looking at the event field
859 * @return boolean true if the state has been graded
860 * @param object $state
862 function question_state_is_graded($state) {
863 return ($state->event
== QUESTION_EVENTGRADE
864 or $state->event
== QUESTION_EVENTCLOSEANDGRADE
865 or $state->event
== QUESTION_EVENTMANUALGRADE
);
869 * Determines whether a state has been closed by looking at the event field
871 * @return boolean true if the state has been closed
872 * @param object $state
874 function question_state_is_closed($state) {
875 return ($state->event
== QUESTION_EVENTCLOSE
876 or $state->event
== QUESTION_EVENTCLOSEANDGRADE
877 or $state->event
== QUESTION_EVENTMANUALGRADE
);
882 * Extracts responses from submitted form
884 * This can extract the responses given to one or several questions present on a page
885 * It returns an array with one entry for each question, indexed by question id
886 * Each entry is an object with the properties
887 * ->event The event that has triggered the submission. This is determined by which button
888 * the user has pressed.
889 * ->responses An array holding the responses to an individual question, indexed by the
890 * name of the corresponding form element.
891 * ->timestamp A unix timestamp
892 * @return array array of action objects, indexed by question ids.
893 * @param array $questions an array containing at least all questions that are used on the form
894 * @param array $formdata the data submitted by the form on the question page
895 * @param integer $defaultevent the event type used if no 'mark' or 'validate' is submitted
897 function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE
) {
901 foreach ($formdata as $key => $response) {
902 // Get the question id from the response name
903 if (false !== ($quid = question_get_id_from_name_prefix($key))) {
904 // check if this is a valid id
905 if (!isset($questions[$quid])) {
906 error('Form contained question that is not in questionids');
909 // Remove the name prefix from the name
911 $key = substr($key, strlen($questions[$quid]->name_prefix
));
912 if (false === $key) {
915 // Check for question validate and mark buttons & set events
916 if ($key === 'validate') {
917 $actions[$quid]->event
= QUESTION_EVENTVALIDATE
;
918 } else if ($key === 'submit') {
919 $actions[$quid]->event
= QUESTION_EVENTSUBMIT
;
921 $actions[$quid]->event
= $defaultevent;
924 // Update the state with the new response
925 $actions[$quid]->responses
[$key] = $response;
928 $actions[$quid]->timestamp
= $time;
931 foreach ($actions as $quid => $notused) {
932 ksort($actions[$quid]->responses
);
939 * Returns the html for question feedback image.
940 * @param float $fraction value representing the correctness of the user's
941 * response to a question.
942 * @param boolean $selected whether or not the answer is the one that the
946 function question_get_feedback_image($fraction, $selected=true) {
950 if ($fraction >= 1.0) {
952 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_green_big.gif" '.
953 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
955 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_green_small.gif" '.
956 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
958 } else if ($fraction > 0.0 && $fraction < 1.0) {
960 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_amber_big.gif" '.
961 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
963 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_amber_small.gif" '.
964 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
968 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/cross_red_big.gif" '.
969 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
971 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/cross_red_small.gif" '.
972 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
980 * Returns the class name for question feedback.
981 * @param float $fraction value representing the correctness of the user's
982 * response to a question.
985 function question_get_feedback_class($fraction) {
989 if ($fraction >= 1.0) {
991 } else if ($fraction > 0.0 && $fraction < 1.0) {
992 $class = 'partiallycorrect';
994 $class = 'incorrect';
1001 * For a given question in an attempt we walk the complete history of states
1002 * and recalculate the grades as we go along.
1004 * This is used when a question is changed and old student
1005 * responses need to be marked with the new version of a question.
1007 * TODO: Make sure this is not quiz-specific
1009 * @return boolean Indicates whether the grade has changed
1010 * @param object $question A question object
1011 * @param object $attempt The attempt, in which the question needs to be regraded.
1012 * @param object $cmoptions
1013 * @param boolean $verbose Optional. Whether to print progress information or not.
1015 function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false) {
1017 // load all states for this question in this attempt, ordered in sequence
1018 if ($states = get_records_select('question_states',
1019 "attempt = '{$attempt->uniqueid}' AND question = '{$question->id}'",
1020 'seq_number ASC')) {
1021 $states = array_values($states);
1023 // Subtract the grade for the latest state from $attempt->sumgrades to get the
1024 // sumgrades for the attempt without this question.
1025 $attempt->sumgrades
-= $states[count($states)-1]->grade
;
1027 // Initialise the replaystate
1028 $state = clone($states[0]);
1029 $state->manualcomment
= get_field('question_sessions', 'manualcomment', 'attemptid',
1030 $attempt->uniqueid
, 'questionid', $question->id
);
1031 restore_question_state($question, $state);
1032 $state->sumpenalty
= 0.0;
1033 $replaystate = clone($state);
1034 $replaystate->last_graded
= $state;
1037 for($j = 1; $j < count($states); $j++
) {
1038 restore_question_state($question, $states[$j]);
1039 $action = new stdClass
;
1040 $action->responses
= $states[$j]->responses
;
1041 $action->timestamp
= $states[$j]->timestamp
;
1043 // Change event to submit so that it will be reprocessed
1044 if (QUESTION_EVENTCLOSE
== $states[$j]->event
1045 or QUESTION_EVENTGRADE
== $states[$j]->event
1046 or QUESTION_EVENTCLOSEANDGRADE
== $states[$j]->event
) {
1047 $action->event
= QUESTION_EVENTSUBMIT
;
1049 // By default take the event that was saved in the database
1051 $action->event
= $states[$j]->event
;
1054 if ($action->event
== QUESTION_EVENTMANUALGRADE
) {
1055 question_process_comment($question, $replaystate, $attempt,
1056 $replaystate->manualcomment
, $states[$j]->grade
);
1059 // Reprocess (regrade) responses
1060 if (!question_process_responses($question, $replaystate,
1061 $action, $cmoptions, $attempt)) {
1062 $verbose && notify("Couldn't regrade state #{$state->id}!");
1066 // We need rounding here because grades in the DB get truncated
1067 // e.g. 0.33333 != 0.3333333, but we want them to be equal here
1068 if ((round((float)$replaystate->raw_grade
, 5) != round((float)$states[$j]->raw_grade
, 5))
1069 or (round((float)$replaystate->penalty
, 5) != round((float)$states[$j]->penalty
, 5))
1070 or (round((float)$replaystate->grade
, 5) != round((float)$states[$j]->grade
, 5))) {
1074 $replaystate->id
= $states[$j]->id
;
1075 $replaystate->changed
= true;
1076 $replaystate->update
= true; // This will ensure that the existing database entry is updated rather than a new one created
1077 save_question_session($question, $replaystate);
1080 // TODO, call a method in quiz to do this, where 'quiz' comes from
1081 // the question_attempts table.
1082 update_record('quiz_attempts', $attempt);
1091 * Processes an array of student responses, grading and saving them as appropriate
1093 * @return boolean Indicates success/failure
1094 * @param object $question Full question object, passed by reference
1095 * @param object $state Full state object, passed by reference
1096 * @param object $action object with the fields ->responses which
1097 * is an array holding the student responses,
1098 * ->action which specifies the action, e.g., QUESTION_EVENTGRADE,
1099 * and ->timestamp which is a timestamp from when the responses
1100 * were submitted by the student.
1101 * @param object $cmoptions
1102 * @param object $attempt The attempt is passed by reference so that
1103 * during grading its ->sumgrades field can be updated
1105 function question_process_responses(&$question, &$state, $action, $cmoptions, &$attempt) {
1108 // if no responses are set initialise to empty response
1109 if (!isset($action->responses
)) {
1110 $action->responses
= array('' => '');
1113 // make sure these are gone!
1114 unset($action->responses
['submit'], $action->responses
['validate']);
1116 // Check the question session is still open
1117 if (question_state_is_closed($state)) {
1121 // If $action->event is not set that implies saving
1122 if (! isset($action->event
)) {
1123 debugging('Ambiguous action in question_process_responses.' , DEBUG_DEVELOPER
);
1124 $action->event
= QUESTION_EVENTSAVE
;
1126 // If submitted then compare against last graded
1127 // responses, not last given responses in this case
1128 if (question_isgradingevent($action->event
)) {
1129 $state->responses
= $state->last_graded
->responses
;
1132 // Check for unchanged responses (exactly unchanged, not equivalent).
1133 // We also have to catch questions that the student has not yet attempted
1134 $sameresponses = $QTYPES[$question->qtype
]->compare_responses($question, $action, $state);
1135 if ($state->last_graded
->event
== QUESTION_EVENTOPEN
&& question_isgradingevent($action->event
)) {
1136 $sameresponses = false;
1139 // If the response has not been changed then we do not have to process it again
1140 // unless the attempt is closing or validation is requested
1141 if ($sameresponses and QUESTION_EVENTCLOSE
!= $action->event
1142 and QUESTION_EVENTVALIDATE
!= $action->event
) {
1146 // Roll back grading information to last graded state and set the new
1148 $newstate = clone($state->last_graded
);
1149 $newstate->responses
= $action->responses
;
1150 $newstate->seq_number
= $state->seq_number +
1;
1151 $newstate->changed
= true; // will assure that it gets saved to the database
1152 $newstate->last_graded
= clone($state->last_graded
);
1153 $newstate->timestamp
= $action->timestamp
;
1156 // Set the event to the action we will perform. The question type specific
1157 // grading code may override this by setting it to QUESTION_EVENTCLOSE if the
1158 // attempt at the question causes the session to close
1159 $state->event
= $action->event
;
1161 if (!question_isgradingevent($action->event
)) {
1162 // Grade the response but don't update the overall grade
1163 $QTYPES[$question->qtype
]->grade_responses($question, $state, $cmoptions);
1165 // Temporary hack because question types are not given enough control over what is going
1166 // on. Used by Opaque questions.
1167 // TODO fix this code properly.
1168 if (!empty($state->believeevent
)) {
1169 // If the state was graded we need to ...
1170 if (question_state_is_graded($state)) {
1171 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1173 // update the attempt grade
1174 $attempt->sumgrades
-= (float)$state->last_graded
->grade
;
1175 $attempt->sumgrades +
= (float)$state->grade
;
1177 // and update the last_graded field.
1178 unset($state->last_graded
);
1179 $state->last_graded
= clone($state);
1180 unset($state->last_graded
->changed
);
1183 // Don't allow the processing to change the event type
1184 $state->event
= $action->event
;
1187 } else { // grading event
1189 // Unless the attempt is closing, we want to work out if the current responses
1190 // (or equivalent responses) were already given in the last graded attempt.
1191 if(QUESTION_EVENTCLOSE
!= $action->event
&& QUESTION_EVENTOPEN
!= $state->last_graded
->event
&&
1192 $QTYPES[$question->qtype
]->compare_responses($question, $state, $state->last_graded
)) {
1193 $state->event
= QUESTION_EVENTDUPLICATE
;
1196 // If we did not find a duplicate or if the attempt is closing, perform grading
1197 if ((!$sameresponses and QUESTION_EVENTDUPLICATE
!= $state->event
) or
1198 QUESTION_EVENTCLOSE
== $action->event
) {
1200 $QTYPES[$question->qtype
]->grade_responses($question, $state, $cmoptions);
1201 // Calculate overall grade using correct penalty method
1202 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1205 // If the state was graded we need to ...
1206 if (question_state_is_graded($state)) {
1207 // update the attempt grade
1208 $attempt->sumgrades
-= (float)$state->last_graded
->grade
;
1209 $attempt->sumgrades +
= (float)$state->grade
;
1211 // and update the last_graded field.
1212 unset($state->last_graded
);
1213 $state->last_graded
= clone($state);
1214 unset($state->last_graded
->changed
);
1217 $attempt->timemodified
= $action->timestamp
;
1223 * Determine if event requires grading
1225 function question_isgradingevent($event) {
1226 return (QUESTION_EVENTSUBMIT
== $event || QUESTION_EVENTCLOSE
== $event);
1230 * Applies the penalty from the previous graded responses to the raw grade
1231 * for the current responses
1233 * The grade for the question in the current state is computed by subtracting the
1234 * penalty accumulated over the previous graded responses at the question from the
1235 * raw grade. If the timestamp is more than 1 minute beyond the end of the attempt
1236 * the grade is set to zero. The ->grade field of the state object is modified to
1237 * reflect the new grade but is never allowed to decrease.
1238 * @param object $question The question for which the penalty is to be applied.
1239 * @param object $state The state for which the grade is to be set from the
1240 * raw grade and the cumulative penalty from the last
1241 * graded state. The ->grade field is updated by applying
1242 * the penalty scheme determined in $cmoptions to the ->raw_grade and
1243 * ->last_graded->penalty fields.
1244 * @param object $cmoptions The options set by the course module.
1245 * The ->penaltyscheme field determines whether penalties
1246 * for incorrect earlier responses are subtracted.
1248 function question_apply_penalty_and_timelimit(&$question, &$state, $attempt, $cmoptions) {
1249 // TODO. Quiz dependancy. The fact that the attempt that is passed in here
1250 // is from quiz_attempts, and we use things like $cmoptions->timelimit.
1252 // deal with penalty
1253 if ($cmoptions->penaltyscheme
) {
1254 $state->grade
= $state->raw_grade
- $state->sumpenalty
;
1255 $state->sumpenalty +
= (float) $state->penalty
;
1257 $state->grade
= $state->raw_grade
;
1260 // deal with timelimit
1261 if ($cmoptions->timelimit
) {
1262 // We allow for 5% uncertainty in the following test
1263 if ($state->timestamp
- $attempt->timestart
> $cmoptions->timelimit
* 63) {
1264 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id
);
1265 if (!has_capability('mod/quiz:ignoretimelimits', get_context_instance(CONTEXT_MODULE
, $cm->id
),
1266 $attempt->userid
, false)) {
1272 // deal with closing time
1273 if ($cmoptions->timeclose
and $state->timestamp
> ($cmoptions->timeclose +
60) // allowing 1 minute lateness
1274 and !$attempt->preview
) { // ignore closing time for previews
1278 // Ensure that the grade does not go down
1279 $state->grade
= max($state->grade
, $state->last_graded
->grade
);
1283 * Print the icon for the question type
1285 * @param object $question The question object for which the icon is required
1286 * @param boolean $return If true the functions returns the link as a string
1288 function print_question_icon($question, $return = false) {
1289 global $QTYPES, $CFG;
1291 $namestr = $QTYPES[$question->qtype
]->menu_name();
1292 $html = '<img src="' . $CFG->wwwroot
. '/question/type/' .
1293 $question->qtype
. '/icon.gif" alt="' .
1294 $namestr . '" title="' . $namestr . '" />';
1303 * Returns a html link to the question image if there is one
1305 * @return string The html image tag or the empy string if there is no image.
1306 * @param object $question The question object
1308 function get_question_image($question, $courseid) {
1313 if ($question->image
) {
1315 if (substr(strtolower($question->image
), 0, 7) == 'http://') {
1316 $img .= $question->image
;
1318 } else if ($CFG->slasharguments
) { // Use this method if possible for better caching
1319 $img .= "$CFG->wwwroot/file.php/$courseid/$question->image";
1322 $img .= "$CFG->wwwroot/file.php?file=/$courseid/$question->image";
1328 function question_print_comment_box($question, $state, $attempt, $url) {
1331 $prefix = 'response';
1332 $usehtmleditor = can_use_richtext_editor();
1333 $grade = round($state->last_graded
->grade
, 3);
1334 echo '<form method="post" action="'.$url.'">';
1335 include($CFG->dirroot
.'/question/comment.html');
1336 echo '<input type="hidden" name="attempt" value="'.$attempt->uniqueid
.'" />';
1337 echo '<input type="hidden" name="question" value="'.$question->id
.'" />';
1338 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1339 echo '<input type="submit" name="submit" value="'.get_string('save', 'quiz').'" />';
1342 if ($usehtmleditor) {
1347 function question_process_comment($question, &$state, &$attempt, $comment, $grade) {
1349 // Update the comment and save it in the database
1350 $state->manualcomment
= $comment;
1351 if (!set_field('question_sessions', 'manualcomment', $comment, 'attemptid', $attempt->uniqueid
, 'questionid', $question->id
)) {
1352 error("Cannot save comment");
1355 // Update the attempt if the score has changed.
1356 if (abs($state->last_graded
->grade
- $grade) > 0.002) {
1357 $attempt->sumgrades
= $attempt->sumgrades
- $state->last_graded
->grade +
$grade;
1358 $attempt->timemodified
= time();
1359 if (!update_record('quiz_attempts', $attempt)) {
1360 error('Failed to save the current quiz attempt!');
1364 // Update the state if either the score has changed, or this is the first
1365 // manual grade event.
1366 // We don't need to store the modified state in the database, we just need
1367 // to set the $state->changed flag.
1368 if (abs($state->last_graded
->grade
- $grade) > 0.002 ||
1369 $state->last_graded
->event
!= QUESTION_EVENTMANUALGRADE
) {
1371 // We want to update existing state (rather than creating new one) if it
1372 // was itself created by a manual grading event.
1373 $state->update
= ($state->event
== QUESTION_EVENTMANUALGRADE
) ?
1 : 0;
1375 // Update the other parts of the state object.
1376 $state->raw_grade
= $grade;
1377 $state->grade
= $grade;
1378 $state->penalty
= 0;
1379 $state->timestamp
= time();
1380 $state->seq_number++
;
1381 $state->event
= QUESTION_EVENTMANUALGRADE
;
1383 // Update the last graded state (don't simplify!)
1384 unset($state->last_graded
);
1385 $state->last_graded
= clone($state);
1387 // We need to indicate that the state has changed in order for it to be saved.
1388 $state->changed
= 1;
1394 * Construct name prefixes for question form element names
1396 * Construct the name prefix that should be used for example in the
1397 * names of form elements created by questions.
1398 * This is called by {@link get_question_options()}
1399 * to set $question->name_prefix.
1400 * This name prefix includes the question id which can be
1401 * extracted from it with {@link question_get_id_from_name_prefix()}.
1404 * @param integer $id The question id
1406 function question_make_name_prefix($id) {
1407 return 'resp' . $id . '_';
1411 * Extract question id from the prefix of form element names
1413 * @return integer The question id
1414 * @param string $name The name that contains a prefix that was
1415 * constructed with {@link question_make_name_prefix()}
1417 function question_get_id_from_name_prefix($name) {
1418 if (!preg_match('/^resp([0-9]+)_/', $name, $matches))
1420 return (integer) $matches[1];
1424 * Returns the unique id for a new attempt
1426 * Every module can keep their own attempts table with their own sequential ids but
1427 * the question code needs to also have a unique id by which to identify all these
1428 * attempts. Hence a module, when creating a new attempt, calls this function and
1429 * stores the return value in the 'uniqueid' field of its attempts table.
1431 function question_new_attempt_uniqueid($modulename='quiz') {
1433 $attempt = new stdClass
;
1434 $attempt->modulename
= $modulename;
1435 if (!$id = insert_record('question_attempts', $attempt)) {
1436 error('Could not create new entry in question_attempts table');
1442 * Creates a stamp that uniquely identifies this version of the question
1444 * In future we want this to use a hash of the question data to guarantee that
1445 * identical versions have the same version stamp.
1447 * @param object $question
1448 * @return string A unique version stamp
1450 function question_hash($question) {
1451 return make_unique_id_code();
1455 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
1457 * Get the HTML that needs to be included in the head tag when the
1458 * questions in $questionlist are printed in the gives states.
1460 * @param array $questionlist a list of questionids of the questions what will appear on this page.
1461 * @param array $questions an array of question objects, whose keys are question ids.
1462 * Must contain all the questions in $questionlist
1463 * @param array $states an array of question state objects, whose keys are question ids.
1464 * Must contain the state of all the questions in $questionlist
1466 * @return string some HTML code that can go inside the head tag.
1468 function get_html_head_contributions(&$questionlist, &$questions, &$states) {
1471 $contributions = array();
1472 foreach ($questionlist as $questionid) {
1473 $question = $questions[$questionid];
1474 $contributions = array_merge($contributions,
1475 $QTYPES[$question->qtype
]->get_html_head_contributions(
1476 $question, $states[$questionid]));
1478 return implode("\n", array_unique($contributions));
1484 * Simply calls the question type specific print_question() method.
1485 * @param object $question The question to be rendered.
1486 * @param object $state The state to render the question in.
1487 * @param integer $number The number for this question.
1488 * @param object $cmoptions The options specified by the course module
1489 * @param object $options An object specifying the rendering options.
1491 function print_question(&$question, &$state, $number, $cmoptions, $options=null) {
1494 $QTYPES[$question->qtype
]->print_question($question, $state, $number,
1495 $cmoptions, $options);
1498 * Saves question options
1500 * Simply calls the question type specific save_question_options() method.
1502 function save_question_options($question) {
1505 $QTYPES[$question->qtype
]->save_question_options($question);
1509 * Gets all teacher stored answers for a given question
1511 * Simply calls the question type specific get_all_responses() method.
1514 function get_question_responses($question, $state) {
1516 $r = $QTYPES[$question->qtype
]->get_all_responses($question, $state);
1522 * Gets the response given by the user in a particular state
1524 * Simply calls the question type specific get_actual_response() method.
1527 function get_question_actual_response($question, $state) {
1530 $r = $QTYPES[$question->qtype
]->get_actual_response($question, $state);
1535 * TODO: document this
1538 function get_question_fraction_grade($question, $state) {
1541 $r = $QTYPES[$question->qtype
]->get_fractional_grade($question, $state);
1546 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1549 * returns the categories with their names ordered following parent-child relationships
1550 * finally it tries to return pending categories (those being orphaned, whose parent is
1551 * incorrect) to avoid missing any category from original array.
1553 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1554 $children = array();
1555 $keys = array_keys($categories);
1557 foreach ($keys as $key) {
1558 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
1559 $children[$key] = $categories[$key];
1560 $categories[$key]->processed
= true;
1561 $children = $children +
sort_categories_by_tree($categories, $children[$key]->id
, $level+
1);
1564 //If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too
1566 foreach ($keys as $key) {
1567 //If not processed and it's a good candidate to start (because its parent doesn't exist in the course)
1568 if (!isset($categories[$key]->processed
) && !record_exists('question_categories', 'course', $categories[$key]->course
, 'id', $categories[$key]->parent
)) {
1569 $children[$key] = $categories[$key];
1570 $categories[$key]->processed
= true;
1571 $children = $children +
sort_categories_by_tree($categories, $children[$key]->id
, $level+
1);
1579 * Private method, only for the use of add_indented_names().
1581 * Recursively adds an indentedname field to each category, starting with the category
1582 * with id $id, and dealing with that category and all its children, and
1583 * return a new array, with those categories in the right order.
1585 * @param array $categories an array of categories which has had childids
1586 * fields added by flatten_category_tree(). Passed by reference for
1587 * performance only. It is not modfied.
1588 * @param int $id the category to start the indenting process from.
1589 * @param int $depth the indent depth. Used in recursive calls.
1590 * @return array a new array of categories, in the right order for the tree.
1592 function flatten_category_tree(&$categories, $id, $depth = 0) {
1594 // Indent the name of this category.
1595 $newcategories = array();
1596 $newcategories[$id] = $categories[$id];
1597 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) . $categories[$id]->name
;
1599 // Recursively indent the children.
1600 foreach ($categories[$id]->childids
as $childid) {
1601 $newcategories = $newcategories +
flatten_category_tree($categories, $childid, $depth +
1);
1604 // Remove the childids array that were temporarily added.
1605 unset($newcategories[$id]->childids
);
1607 return $newcategories;
1611 * Format categories into an indented list reflecting the tree structure.
1613 * @param array $categories An array of category objects, for example from the.
1614 * @return array The formatted list of categories.
1616 function add_indented_names($categories) {
1618 // Add an array to each category to hold the child category ids. This array will be removed
1619 // again by flatten_category_tree(). It should not be used outside these two functions.
1620 foreach (array_keys($categories) as $id) {
1621 $categories[$id]->childids
= array();
1624 // Build the tree structure, and record which categories are top-level.
1625 // We have to be careful, because the categories array may include published
1626 // categories from other courses, but not their parents.
1627 $toplevelcategoryids = array();
1628 foreach (array_keys($categories) as $id) {
1629 if (!empty($categories[$id]->parent
) && array_key_exists($categories[$id]->parent
, $categories)) {
1630 $categories[$categories[$id]->parent
]->childids
[] = $id;
1632 $toplevelcategoryids[] = $id;
1636 // Flatten the tree to and add the indents.
1637 $newcategories = array();
1638 foreach ($toplevelcategoryids as $id) {
1639 $newcategories = $newcategories +
flatten_category_tree($categories, $id);
1642 return $newcategories;
1646 * Output a select menu of question categories.
1648 * Categories from this course and (optionally) published categories from other courses
1649 * are included. Optionally, only categories the current user may edit can be included.
1651 * @param integer $courseid the id of the course to get the categories for.
1652 * @param integer $published if true, include publised categories from other courses.
1653 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1654 * @param integer $selected optionally, the id of a category to be selected by default in the dropdown.
1656 function question_category_select_menu($contexts, $top = false, $currentcat = 0, $selected = "") {
1657 $categoriesarray = question_category_options($contexts, $top, $currentcat);
1661 $nothing = 'choose';
1663 choose_from_menu_nested($categoriesarray, 'category', $selected, $nothing);
1667 * Output an array of question categories.
1671 function question_category_options($contexts, $top = false, $currentcat = 0, $popupform = false) {
1673 $pcontexts = array();
1674 foreach($contexts as $context){
1675 $pcontexts[] = $context->id
;
1677 $contextslist = join($pcontexts, ', ');
1679 // get sql fragment for published
1682 $categories = get_records_sql("
1683 SELECT c.*, count(q.id) as questioncount
1684 FROM {$CFG->prefix}question_categories as c
1685 LEFT JOIN {$CFG->prefix}question as q ON c.id = q.category
1686 WHERE c.contextid IN ($contextslist) AND
1687 (q.id IS NULL OR (q.hidden='0' AND q.parent='0'))
1689 ORDER BY parent, sortorder, name ASC");
1692 $categories = question_add_context_in_key($categories);
1695 $categories = question_add_tops($categories, $pcontexts);
1697 $categories = add_indented_names($categories);
1699 //sort cats out into different contexts
1700 $categoriesarray = array();
1701 foreach ($pcontexts as $pcontext){
1702 $contextstring = print_context_name(get_context_instance_by_id($pcontext), true, true);
1703 foreach ($categories as $category) {
1704 if ($category->contextid
== $pcontext){
1705 $cid = $category->id
;
1706 if ($currentcat!= $cid) {
1707 $countstring = (!empty($category->questioncount
))?
"($category->questioncount)":'';
1708 $categoriesarray[$contextstring][$cid] = $category->indentedname
.$countstring;
1714 $popupcats = array();
1715 foreach ($categoriesarray as $contextstring => $optgroup){
1716 $popupcats[] = '--'.$contextstring;
1717 $popupcats = array_merge($popupcats, $optgroup);
1718 $popupcats[] = '--';
1722 return $categoriesarray;
1726 function question_add_context_in_key($categories){
1727 $newcatarray = array();
1728 foreach ($categories as $id => $category) {
1729 $category->parent
= "$category->parent,$category->contextid";
1730 $category->id
= "$category->id,$category->contextid";
1731 $newcatarray["$id,$category->contextid"] = $category;
1733 return $newcatarray;
1735 function question_add_tops($categories, $pcontexts){
1737 foreach ($pcontexts as $context){
1738 $newcat = new object();
1739 $newcat->id
= "0,$context";
1740 $newcat->name
= get_string('top');
1741 $newcat->parent
= -1;
1742 $newcat->contextid
= $context;
1743 $topcats["0,$context"] = $newcat;
1745 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1746 return array_merge($topcats, $categories);
1750 * Returns a comma separated list of ids of the category and all subcategories
1752 function question_categorylist($categoryid) {
1753 // returns a comma separated list of ids of the category and all subcategories
1754 $categorylist = $categoryid;
1755 if ($subcategories = get_records('question_categories', 'parent', $categoryid, 'sortorder ASC', 'id, id')) {
1756 foreach ($subcategories as $subcategory) {
1757 $categorylist .= ','. question_categorylist($subcategory->id
);
1760 return $categorylist;
1766 //===========================
1767 // Import/Export Functions
1768 //===========================
1771 * Get list of available import or export formats
1772 * @param string $type 'import' if import list, otherwise export list assumed
1773 * @return array sorted list of import/export formats available
1775 function get_import_export_formats( $type ) {
1778 $fileformats = get_list_of_plugins("question/format");
1780 $fileformatname=array();
1781 require_once( "{$CFG->dirroot}/question/format.php" );
1782 foreach ($fileformats as $key => $fileformat) {
1783 $format_file = $CFG->dirroot
. "/question/format/$fileformat/format.php";
1784 if (file_exists( $format_file ) ) {
1785 require_once( $format_file );
1790 $classname = "qformat_$fileformat";
1791 $format_class = new $classname();
1792 if ($type=='import') {
1793 $provided = $format_class->provide_import();
1796 $provided = $format_class->provide_export();
1799 $formatname = get_string($fileformat, 'quiz');
1800 if ($formatname == "[[$fileformat]]") {
1801 $formatname = $fileformat; // Just use the raw folder name
1803 $fileformatnames[$fileformat] = $formatname;
1806 natcasesort($fileformatnames);
1808 return $fileformatnames;
1813 * Create default export filename
1815 * @return string default export filename
1816 * @param object $course
1817 * @param object $category
1819 function default_export_filename($course,$category) {
1820 //Take off some characters in the filename !!
1821 $takeoff = array(" ", ":", "/", "\\", "|");
1822 $export_word = str_replace($takeoff,"_",moodle_strtolower(get_string("exportfilename","quiz")));
1823 //If non-translated, use "export"
1824 if (substr($export_word,0,1) == "[") {
1825 $export_word= "export";
1828 //Calculate the date format string
1829 $export_date_format = str_replace(" ","_",get_string("exportnameformat","quiz"));
1830 //If non-translated, use "%Y%m%d-%H%M"
1831 if (substr($export_date_format,0,1) == "[") {
1832 $export_date_format = "%%Y%%m%%d-%%H%%M";
1835 //Calculate the shortname
1836 $export_shortname = clean_filename($course->shortname
);
1837 if (empty($export_shortname) or $export_shortname == '_' ) {
1838 $export_shortname = $course->id
;
1841 //Calculate the category name
1842 $export_categoryname = clean_filename($category->name
);
1844 //Calculate the final export filename
1846 $export_name = $export_word."-";
1848 $export_name .= moodle_strtolower($export_shortname)."-";
1850 $export_name .= moodle_strtolower($export_categoryname)."-";
1852 $export_name .= userdate(time(),$export_date_format,99,false);
1853 //The extension - no extension, supplied by format
1854 // $export_name .= ".txt";
1856 return $export_name;