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");
51 define("ESSAY", "essay");
55 * Constant determines the number of answer boxes supplied in the editing
56 * form for multiple choice and similar question types.
58 define("QUESTION_NUMANS", "10");
61 * Constant determines the number of answer boxes supplied in the editing
62 * form for multiple choice and similar question types to start with, with
63 * the option of adding QUESTION_NUMANS_ADD more answers.
65 define("QUESTION_NUMANS_START", 3);
68 * Constant determines the number of answer boxes to add in the editing
69 * form for multiple choice and similar question types when the user presses
70 * 'add form fields button'.
72 define("QUESTION_NUMANS_ADD", 3);
75 * The options used when popping up a question preview window in Javascript.
77 define('QUESTION_PREVIEW_POPUP_OPTIONS', 'scrollbars=yes,resizable=yes,width=700,height=540');
80 * Option flags for ->optionflags
81 * The options are read out via bitwise operation using these constants
84 * Whether the questions is to be run in adaptive mode. If this is not set then
85 * a question closes immediately after the first submission of responses. This
86 * is how question is Moodle always worked before version 1.5
88 define('QUESTION_ADAPTIVE', 1);
92 /// QTYPES INITIATION //////////////////
93 // These variables get initialised via calls to question_register_questiontype
94 // as the question type classes are included.
95 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
97 * Array holding question type objects
101 * Array of question types names translated to the user's language
103 * The $QTYPE_MENU array holds the names of all the question types that the user should
104 * be able to create directly. Some internal question types like random questions are excluded.
105 * The complete list of question types can be found in {@link $QTYPES}.
107 $QTYPE_MENU = array();
109 * String in the format "'type1','type2'" that can be used in SQL clauses like
110 * "WHERE q.type IN ($QTYPE_MANUAL)".
114 * String in the format "'type1','type2'" that can be used in SQL clauses like
115 * "WHERE q.type NOT IN ($QTYPE_EXCLUDE_FROM_RANDOM)".
117 $QTYPE_EXCLUDE_FROM_RANDOM = '';
120 * Add a new question type to the various global arrays above.
122 * @param object $qtype An instance of the new question type class.
124 function question_register_questiontype($qtype) {
125 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
127 $name = $qtype->name();
128 $QTYPES[$name] = $qtype;
129 $menuname = $qtype->menu_name();
131 $QTYPE_MENU[$name] = $menuname;
133 if ($qtype->is_manual_graded()) {
135 $QTYPE_MANUAL .= ',';
137 $QTYPE_MANUAL .= "'$name'";
139 if (!$qtype->is_usable_by_random()) {
140 if ($QTYPE_EXCLUDE_FROM_RANDOM) {
141 $QTYPE_EXCLUDE_FROM_RANDOM .= ',';
143 $QTYPE_EXCLUDE_FROM_RANDOM .= "'$name'";
147 require_once("$CFG->dirroot/question/type/questiontype.php");
149 // Load the questiontype.php file for each question type
150 // These files in turn call question_register_questiontype()
151 // with a new instance of each qtype class.
152 $qtypenames= get_list_of_plugins('question/type');
153 foreach($qtypenames as $qtypename) {
154 // Instanciates all plug-in question types
155 $qtypefilepath= "$CFG->dirroot/question/type/$qtypename/questiontype.php";
157 // echo "Loading $qtypename<br/>"; // Uncomment for debugging
158 if (is_readable($qtypefilepath)) {
159 require_once($qtypefilepath);
163 /// OTHER CLASSES /////////////////////////////////////////////////////////
166 * This holds the options that are set by the course module
170 * Whether a new attempt should be based on the previous one. If true
171 * then a new attempt will start in a state where all responses are set
172 * to the last responses from the previous attempt.
174 var $attemptonlast = false;
177 * Various option flags. The flags are accessed via bitwise operations
178 * using the constants defined in the CONSTANTS section above.
180 var $optionflags = QUESTION_ADAPTIVE
;
183 * Determines whether in the calculation of the score for a question
184 * penalties for earlier wrong responses within the same attempt will
187 var $penaltyscheme = true;
190 * The maximum time the user is allowed to answer the questions withing
191 * an attempt. This is measured in minutes so needs to be multiplied by
192 * 60 before compared to timestamps. If set to 0 no timelimit will be applied
197 * Timestamp for the closing time. Responses submitted after this time will
198 * be saved but no credit will be given for them.
200 var $timeclose = 9999999999;
203 * The id of the course from withing which the question is currently being used
205 var $course = SITEID
;
208 * Whether the answers in a multiple choice question should be randomly
209 * shuffled when a new attempt is started.
211 var $shuffleanswers = true;
214 * The number of decimals to be shown when scores are printed
216 var $decimalpoints = 2;
220 /// FUNCTIONS //////////////////////////////////////////////////////
223 * Returns an array of names of activity modules that use this question
225 * @param object $questionid
226 * @return array of strings
228 function question_list_instances($questionid) {
229 $instances = array();
230 $modules = get_records('modules');
231 foreach ($modules as $module) {
232 $fn = $module->name
.'_question_list_instances';
233 if (function_exists($fn)) {
234 $instances = $instances +
$fn($questionid);
242 * Returns list of 'allowed' grades for grade selection
243 * formatted suitably for dropdown box function
244 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
246 function get_grade_options() {
247 // define basic array of grades
270 // iterate through grades generating full range of options
271 $gradeoptionsfull = array();
272 $gradeoptions = array();
273 foreach ($grades as $grade) {
274 $percentage = 100 * $grade;
276 $gradeoptions["$grade"] = "$percentage %";
277 $gradeoptionsfull["$grade"] = "$percentage %";
278 $gradeoptionsfull["$neggrade"] = -$percentage." %";
280 $gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
283 arsort($gradeoptions, SORT_NUMERIC
);
284 arsort($gradeoptionsfull, SORT_NUMERIC
);
286 // construct return object
287 $grades = new stdClass
;
288 $grades->gradeoptions
= $gradeoptions;
289 $grades->gradeoptionsfull
= $gradeoptionsfull;
295 * match grade options
296 * if no match return error or match nearest
297 * @param array $gradeoptionsfull list of valid options
298 * @param int $grade grade to be tested
299 * @param string $matchgrades 'error' or 'nearest'
300 * @return mixed either 'fixed' value or false if erro
302 function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
303 // if we just need an error...
304 if ($matchgrades=='error') {
305 foreach($gradeoptionsfull as $value => $option) {
306 // slightly fuzzy test, never check floats for equality :-)
307 if (abs($grade-$value)<0.00001) {
311 // didn't find a match so that's an error
314 // work out nearest value
315 else if ($matchgrades=='nearest') {
317 foreach($gradeoptionsfull as $value => $option) {
318 if ($grade==$value) {
321 $hownear[ $value ] = abs( $grade - $value );
323 // reverse sort list of deltas and grab the last (smallest)
324 asort( $hownear, SORT_NUMERIC
);
326 return key( $hownear );
334 * Tests whether a category is in use by any activity module
337 * @param integer $categoryid
338 * @param boolean $recursive Whether to examine category children recursively
340 function question_category_isused($categoryid, $recursive = false) {
342 //Look at each question in the category
343 if ($questions = get_records('question', 'category', $categoryid)) {
344 foreach ($questions as $question) {
345 if (count(question_list_instances($question->id
))) {
351 //Look under child categories recursively
353 if ($children = get_records('question_categories', 'parent', $categoryid)) {
354 foreach ($children as $child) {
355 if (question_category_isused($child->id
, $recursive)) {
366 * Deletes all data associated to an attempt from the database
368 * @param integer $attemptid The id of the attempt being deleted
370 function delete_attempt($attemptid) {
373 $states = get_records('question_states', 'attempt', $attemptid);
375 $stateslist = implode(',', array_keys($states));
377 // delete question-type specific data
378 foreach ($QTYPES as $qtype) {
379 $qtype->delete_states($stateslist);
383 // delete entries from all other question tables
384 // It is important that this is done only after calling the questiontype functions
385 delete_records("question_states", "attempt", $attemptid);
386 delete_records("question_sessions", "attemptid", $attemptid);
387 delete_records("question_attempts", "id", $attemptid);
391 * Deletes question and all associated data from the database
393 * It will not delete a question if it is used by an activity module
394 * @param object $question The question being deleted
396 function delete_question($questionid) {
399 // Do not delete a question if it is used by an activity module
400 if (count(question_list_instances($questionid))) {
404 // delete questiontype-specific data
405 if ($question = get_record('question', 'id', $questionid)) {
406 if (isset($QTYPES[$question->qtype
])) {
407 $QTYPES[$question->qtype
]->delete_question($questionid);
410 echo "Question with id $questionid does not exist.<br />";
413 if ($states = get_records('question_states', 'question', $questionid)) {
414 $stateslist = implode(',', array_keys($states));
416 // delete questiontype-specific data
417 foreach ($QTYPES as $qtype) {
418 $qtype->delete_states($stateslist);
422 // delete entries from all other question tables
423 // It is important that this is done only after calling the questiontype functions
424 delete_records("question_answers", "question", $questionid);
425 delete_records("question_states", "question", $questionid);
426 delete_records("question_sessions", "questionid", $questionid);
428 // Now recursively delete all child questions
429 if ($children = get_records('question', 'parent', $questionid)) {
430 foreach ($children as $child) {
431 if ($child->id
!= $questionid) {
432 delete_question($child->id
);
437 // Finally delete the question record itself
438 delete_records('question', 'id', $questionid);
444 * All non-used question categories and their questions are deleted and
445 * categories still used by other courses are moved to the site course.
447 * @param object $course an object representing the course
448 * @param boolean $feedback to specify if the process must output a summary of its work
451 function question_delete_course($course, $feedback=true) {
453 global $CFG, $QTYPES;
455 //To detect if we have created the "container category"
458 //The "container" category we'll create if we need if
459 $contcat = new object;
461 //To temporary store changes performed with parents
462 $parentchanged = array();
464 //To store feedback to be showed at the end of the process
465 $feedbackdata = array();
468 $strcatcontainer=get_string('containercategorycreated', 'quiz');
469 $strcatmoved = get_string('usedcategorymoved', 'quiz');
470 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
472 if ($categories = get_records('question_categories', 'course', $course->id
, 'parent', 'id, parent, name, course')) {
474 //Sort categories following their tree (parent-child) relationships
475 $categories = sort_categories_by_tree($categories);
477 foreach ($categories as $cat) {
479 //Get the full record
480 $category = get_record('question_categories', 'id', $cat->id
);
482 //Check if the category is being used anywhere
483 if(question_category_isused($category->id
, true)) {
484 //It's being used. Cannot delete it, so:
485 //Create a container category in SITEID course if it doesn't exist
487 $concat = new stdClass
;
488 $concat->course
= SITEID
;
489 if (!isset($course->shortname
)) {
490 $course->shortname
= 'id=' . $course->id
;
492 $concat->name
= get_string('savedfromdeletedcourse', 'quiz', format_string($course->shortname
));
493 $concat->info
= $concat->name
;
494 $concat->publish
= 1;
495 $concat->stamp
= make_unique_id_code();
496 $concatid = insert_record('question_categories', $concat);
499 $feedbackdata[] = array($concat->name
, $strcatcontainer);
501 //Move the category to the container category in SITEID course
502 $category->course
= SITEID
;
503 //Assign to container if the category hasn't parent or if the parent is wrong (not belongs to the course)
504 if (!$category->parent ||
!isset($categories[$category->parent
])) {
505 $category->parent
= $concatid;
507 //If it's being used, its publish field should be 1
508 $category->publish
= 1;
510 update_record('question_categories', $category);
512 //Save this parent change for future use
513 $parentchanged[$category->id
] = $category->parent
;
516 $feedbackdata[] = array($category->name
, $strcatmoved);
519 //Category isn't being used so:
520 //Delete it completely (questions and category itself)
522 if ($questions = get_records("question", "category", $category->id
)) {
523 foreach ($questions as $question) {
524 delete_question($question->id
);
526 delete_records("question", "category", $category->id
);
528 //delete the category
529 delete_records('question_categories', 'id', $category->id
);
531 //Save this parent change for future use
532 if (!empty($category->parent
)) {
533 $parentchanged[$category->id
] = $category->parent
;
535 $parentchanged[$category->id
] = $concatid;
538 //Update all its child categories to re-parent them to grandparent.
539 set_field ('question_categories', 'parent', $parentchanged[$category->id
], 'parent', $category->id
);
542 $feedbackdata[] = array($category->name
, $strcatdeleted);
545 //Inform about changes performed if feedback is enabled
547 $table = new stdClass
;
548 $table->head
= array(get_string('category','quiz'), get_string('action'));
549 $table->data
= $feedbackdata;
556 function questionbank_navigation_tabs(&$row, $context, $querystring) {
558 if (has_capability('moodle/question:manage', $context)) {
559 $row[] = new tabobject('questions', "$CFG->wwwroot/question/edit.php?$querystring", get_string('questions', 'quiz'), get_string('editquestions', "quiz"));
562 if (has_capability('moodle/question:managecategory', $context)) {
563 $row[] = new tabobject('categories', "$CFG->wwwroot/question/category.php?$querystring", get_string('categories', 'quiz'), get_string('editqcats', 'quiz'));
566 if (has_capability('moodle/question:import', $context)) {
567 $row[] = new tabobject('import', "$CFG->wwwroot/question/import.php?$querystring", get_string('import', 'quiz'), get_string('importquestions', 'quiz'));
570 if (has_capability('moodle/question:export', $context)) {
571 $row[] = new tabobject('export', "$CFG->wwwroot/question/export.php?$querystring", get_string('export', 'quiz'), get_string('exportquestions', 'quiz'));
576 * Private function to factor common code out of get_question_options().
578 * @param object $question the question to tidy.
579 * @return boolean true if successful, else false.
581 function _tidy_question(&$question) {
583 if (!array_key_exists($question->qtype
, $QTYPES)) {
584 $question->qtype
= 'missingtype';
585 $question->questiontext
= '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext
;
587 $question->name_prefix
= question_make_name_prefix($question->id
);
588 return $QTYPES[$question->qtype
]->get_question_options($question);
592 * Updates the question objects with question type specific
593 * information by calling {@link get_question_options()}
595 * Can be called either with an array of question objects or with a single
598 * @param mixed $questions Either an array of question objects to be updated
599 * or just a single question object
600 * @return bool Indicates success or failure.
602 function get_question_options(&$questions) {
603 if (is_array($questions)) { // deal with an array of questions
604 foreach ($questions as $i => $notused) {
605 if (!_tidy_question($questions[$i])) {
610 } else { // deal with single question
611 return _tidy_question($questions);
616 * Loads the most recent state of each question session from the database
619 * For each question the most recent session state for the current attempt
620 * is loaded from the question_states table and the question type specific data and
621 * responses are added by calling {@link restore_question_state()} which in turn
622 * calls {@link restore_session_and_responses()} for each question.
623 * If no states exist for the question instance an empty state object is
624 * created representing the start of a session and empty question
625 * type specific information and responses are created by calling
626 * {@link create_session_and_responses()}.
628 * @return array An array of state objects representing the most recent
629 * states of the question sessions.
630 * @param array $questions The questions for which sessions are to be restored or
632 * @param object $cmoptions
633 * @param object $attempt The attempt for which the question sessions are
634 * to be restored or created.
635 * @param mixed either the id of a previous attempt, if this attmpt is
636 * building on a previous one, or false for a clean attempt.
638 function get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) {
639 global $CFG, $QTYPES;
641 // get the question ids
642 $ids = array_keys($questions);
643 $questionlist = implode(',', $ids);
645 // The question field must be listed first so that it is used as the
646 // array index in the array returned by get_records_sql
647 $statefields = 'n.questionid as question, s.*, n.sumpenalty, n.manualcomment';
648 // Load the newest states for the questions
649 $sql = "SELECT $statefields".
650 " FROM {$CFG->prefix}question_states s,".
651 " {$CFG->prefix}question_sessions n".
652 " WHERE s.id = n.newest".
653 " AND n.attemptid = '$attempt->uniqueid'".
654 " AND n.questionid IN ($questionlist)";
655 $states = get_records_sql($sql);
657 // Load the newest graded states for the questions
658 $sql = "SELECT $statefields".
659 " FROM {$CFG->prefix}question_states s,".
660 " {$CFG->prefix}question_sessions n".
661 " WHERE s.id = n.newgraded".
662 " AND n.attemptid = '$attempt->uniqueid'".
663 " AND n.questionid IN ($questionlist)";
664 $gradedstates = get_records_sql($sql);
666 // loop through all questions and set the last_graded states
667 foreach ($ids as $i) {
668 if (isset($states[$i])) {
669 restore_question_state($questions[$i], $states[$i]);
670 if (isset($gradedstates[$i])) {
671 restore_question_state($questions[$i], $gradedstates[$i]);
672 $states[$i]->last_graded
= $gradedstates[$i];
674 $states[$i]->last_graded
= clone($states[$i]);
677 // If the new attempt is to be based on a previous attempt get it and clean things
678 // Having lastattemptid filled implies that (should we double check?):
679 // $attempt->attempt > 1 and $cmoptions->attemptonlast and !$attempt->preview
680 if ($lastattemptid) {
681 // find the responses from the previous attempt and save them to the new session
683 // Load the last graded state for the question
684 $statefields = 'n.questionid as question, s.*, n.sumpenalty';
685 $sql = "SELECT $statefields".
686 " FROM {$CFG->prefix}question_states s,".
687 " {$CFG->prefix}question_sessions n".
688 " WHERE s.id = n.newgraded".
689 " AND n.attemptid = '$lastattemptid'".
690 " AND n.questionid = '$i'";
691 if (!$laststate = get_record_sql($sql)) {
692 // Only restore previous responses that have been graded
695 // Restore the state so that the responses will be restored
696 restore_question_state($questions[$i], $laststate);
697 $states[$i] = clone ($laststate);
699 // create a new empty state
700 $states[$i] = new object;
703 // now fill/overide initial values
704 $states[$i]->attempt
= $attempt->uniqueid
;
705 $states[$i]->question
= (int) $i;
706 $states[$i]->seq_number
= 0;
707 $states[$i]->timestamp
= $attempt->timestart
;
708 $states[$i]->event
= ($attempt->timefinish
) ? QUESTION_EVENTCLOSE
: QUESTION_EVENTOPEN
;
709 $states[$i]->grade
= 0;
710 $states[$i]->raw_grade
= 0;
711 $states[$i]->penalty
= 0;
712 $states[$i]->sumpenalty
= 0;
713 $states[$i]->manualcomment
= '';
715 // if building on last attempt we want to preserve responses
716 if (!$lastattemptid) {
717 $states[$i]->responses
= array('' => '');
719 // Prevent further changes to the session from incrementing the
721 $states[$i]->changed
= true;
723 if ($lastattemptid) {
724 // prepare the previous responses for new processing
725 $action = new stdClass
;
726 $action->responses
= $laststate->responses
;
727 $action->timestamp
= $laststate->timestamp
;
728 $action->event
= QUESTION_EVENTSAVE
; //emulate save of questions from all pages MDL-7631
730 // Process these responses ...
731 question_process_responses($questions[$i], $states[$i], $action, $cmoptions, $attempt);
733 // Fix for Bug #5506: When each attempt is built on the last one,
734 // preserve the options from any previous attempt.
735 if ( isset($laststate->options
) ) {
736 $states[$i]->options
= $laststate->options
;
739 // Create the empty question type specific information
740 if (!$QTYPES[$questions[$i]->qtype
]->create_session_and_responses(
741 $questions[$i], $states[$i], $cmoptions, $attempt)) {
745 $states[$i]->last_graded
= clone($states[$i]);
753 * Creates the run-time fields for the states
755 * Extends the state objects for a question by calling
756 * {@link restore_session_and_responses()}
757 * @param object $question The question for which the state is needed
758 * @param object $state The state as loaded from the database
759 * @return boolean Represents success or failure
761 function restore_question_state(&$question, &$state) {
764 // initialise response to the value in the answer field
765 $state->responses
= array('' => addslashes($state->answer
));
766 unset($state->answer
);
767 $state->manualcomment
= isset($state->manualcomment
) ?
addslashes($state->manualcomment
) : '';
769 // Set the changed field to false; any code which changes the
770 // question session must set this to true and must increment
771 // ->seq_number. The save_question_session
772 // function will save the new state object to the database if the field is
774 $state->changed
= false;
776 // Load the question type specific data
777 return $QTYPES[$question->qtype
]
778 ->restore_session_and_responses($question, $state);
783 * Saves the current state of the question session to the database
785 * The state object representing the current state of the session for the
786 * question is saved to the question_states table with ->responses[''] saved
787 * to the answer field of the database table. The information in the
788 * question_sessions table is updated.
789 * The question type specific data is then saved.
790 * @return mixed The id of the saved or updated state or false
791 * @param object $question The question for which session is to be saved.
792 * @param object $state The state information to be saved. In particular the
793 * most recent responses are in ->responses. The object
794 * is updated to hold the new ->id.
796 function save_question_session(&$question, &$state) {
798 // Check if the state has changed
799 if (!$state->changed
&& isset($state->id
)) {
802 // Set the legacy answer field
803 $state->answer
= isset($state->responses
['']) ?
$state->responses
[''] : '';
806 if (!empty($state->update
)) { // this forces the old state record to be overwritten
807 update_record('question_states', $state);
809 if (!$state->id
= insert_record('question_states', $state)) {
811 unset($state->answer
);
816 // create or update the session
817 if (!$session = get_record('question_sessions', 'attemptid',
818 $state->attempt
, 'questionid', $question->id
)) {
819 $session->attemptid
= $state->attempt
;
820 $session->questionid
= $question->id
;
821 $session->newest
= $state->id
;
822 // The following may seem weird, but the newgraded field needs to be set
823 // already even if there is no graded state yet.
824 $session->newgraded
= $state->id
;
825 $session->sumpenalty
= $state->sumpenalty
;
826 $session->manualcomment
= $state->manualcomment
;
827 if (!insert_record('question_sessions', $session)) {
828 error('Could not insert entry in question_sessions');
831 $session->newest
= $state->id
;
832 if (question_state_is_graded($state) or $state->event
== QUESTION_EVENTOPEN
) {
833 // this state is graded or newly opened, so it goes into the lastgraded field as well
834 $session->newgraded
= $state->id
;
835 $session->sumpenalty
= $state->sumpenalty
;
836 $session->manualcomment
= $state->manualcomment
;
838 $session->manualcomment
= addslashes($session->manualcomment
);
840 update_record('question_sessions', $session);
843 unset($state->answer
);
845 // Save the question type specific state information and responses
846 if (!$QTYPES[$question->qtype
]->save_session_and_responses(
847 $question, $state)) {
850 // Reset the changed flag
851 $state->changed
= false;
856 * Determines whether a state has been graded by looking at the event field
858 * @return boolean true if the state has been graded
859 * @param object $state
861 function question_state_is_graded($state) {
862 return ($state->event
== QUESTION_EVENTGRADE
863 or $state->event
== QUESTION_EVENTCLOSEANDGRADE
864 or $state->event
== QUESTION_EVENTMANUALGRADE
);
868 * Determines whether a state has been closed by looking at the event field
870 * @return boolean true if the state has been closed
871 * @param object $state
873 function question_state_is_closed($state) {
874 return ($state->event
== QUESTION_EVENTCLOSE
875 or $state->event
== QUESTION_EVENTCLOSEANDGRADE
876 or $state->event
== QUESTION_EVENTMANUALGRADE
);
881 * Extracts responses from submitted form
883 * This can extract the responses given to one or several questions present on a page
884 * It returns an array with one entry for each question, indexed by question id
885 * Each entry is an object with the properties
886 * ->event The event that has triggered the submission. This is determined by which button
887 * the user has pressed.
888 * ->responses An array holding the responses to an individual question, indexed by the
889 * name of the corresponding form element.
890 * ->timestamp A unix timestamp
891 * @return array array of action objects, indexed by question ids.
892 * @param array $questions an array containing at least all questions that are used on the form
893 * @param array $formdata the data submitted by the form on the question page
894 * @param integer $defaultevent the event type used if no 'mark' or 'validate' is submitted
896 function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE
) {
900 foreach ($formdata as $key => $response) {
901 // Get the question id from the response name
902 if (false !== ($quid = question_get_id_from_name_prefix($key))) {
903 // check if this is a valid id
904 if (!isset($questions[$quid])) {
905 error('Form contained question that is not in questionids');
908 // Remove the name prefix from the name
910 $key = substr($key, strlen($questions[$quid]->name_prefix
));
911 if (false === $key) {
914 // Check for question validate and mark buttons & set events
915 if ($key === 'validate') {
916 $actions[$quid]->event
= QUESTION_EVENTVALIDATE
;
917 } else if ($key === 'submit') {
918 $actions[$quid]->event
= QUESTION_EVENTSUBMIT
;
920 $actions[$quid]->event
= $defaultevent;
923 // Update the state with the new response
924 $actions[$quid]->responses
[$key] = $response;
927 $actions[$quid]->timestamp
= $time;
930 foreach ($actions as $quid => $notused) {
931 ksort($actions[$quid]->responses
);
938 * Returns the html for question feedback image.
939 * @param float $fraction value representing the correctness of the user's
940 * response to a question.
941 * @param boolean $selected whether or not the answer is the one that the
945 function question_get_feedback_image($fraction, $selected=true) {
949 if ($fraction >= 1.0) {
951 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_green_big.gif" '.
952 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
954 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_green_small.gif" '.
955 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
957 } else if ($fraction > 0.0 && $fraction < 1.0) {
959 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_amber_big.gif" '.
960 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
962 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_amber_small.gif" '.
963 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
967 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/cross_red_big.gif" '.
968 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
970 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/cross_red_small.gif" '.
971 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
979 * Returns the class name for question feedback.
980 * @param float $fraction value representing the correctness of the user's
981 * response to a question.
984 function question_get_feedback_class($fraction) {
988 if ($fraction >= 1.0) {
990 } else if ($fraction > 0.0 && $fraction < 1.0) {
991 $class = 'partiallycorrect';
993 $class = 'incorrect';
1000 * For a given question in an attempt we walk the complete history of states
1001 * and recalculate the grades as we go along.
1003 * This is used when a question is changed and old student
1004 * responses need to be marked with the new version of a question.
1006 * TODO: Make sure this is not quiz-specific
1008 * @return boolean Indicates whether the grade has changed
1009 * @param object $question A question object
1010 * @param object $attempt The attempt, in which the question needs to be regraded.
1011 * @param object $cmoptions
1012 * @param boolean $verbose Optional. Whether to print progress information or not.
1014 function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false) {
1016 // load all states for this question in this attempt, ordered in sequence
1017 if ($states = get_records_select('question_states',
1018 "attempt = '{$attempt->uniqueid}' AND question = '{$question->id}'",
1019 'seq_number ASC')) {
1020 $states = array_values($states);
1022 // Subtract the grade for the latest state from $attempt->sumgrades to get the
1023 // sumgrades for the attempt without this question.
1024 $attempt->sumgrades
-= $states[count($states)-1]->grade
;
1026 // Initialise the replaystate
1027 $state = clone($states[0]);
1028 $state->manualcomment
= get_field('question_sessions', 'manualcomment', 'attemptid',
1029 $attempt->uniqueid
, 'questionid', $question->id
);
1030 restore_question_state($question, $state);
1031 $state->sumpenalty
= 0.0;
1032 $replaystate = clone($state);
1033 $replaystate->last_graded
= $state;
1036 for($j = 1; $j < count($states); $j++
) {
1037 restore_question_state($question, $states[$j]);
1038 $action = new stdClass
;
1039 $action->responses
= $states[$j]->responses
;
1040 $action->timestamp
= $states[$j]->timestamp
;
1042 // Change event to submit so that it will be reprocessed
1043 if (QUESTION_EVENTCLOSE
== $states[$j]->event
1044 or QUESTION_EVENTGRADE
== $states[$j]->event
1045 or QUESTION_EVENTCLOSEANDGRADE
== $states[$j]->event
) {
1046 $action->event
= QUESTION_EVENTSUBMIT
;
1048 // By default take the event that was saved in the database
1050 $action->event
= $states[$j]->event
;
1053 if ($action->event
== QUESTION_EVENTMANUALGRADE
) {
1054 question_process_comment($question, $replaystate, $attempt,
1055 $replaystate->manualcomment
, $states[$j]->grade
);
1058 // Reprocess (regrade) responses
1059 if (!question_process_responses($question, $replaystate,
1060 $action, $cmoptions, $attempt)) {
1061 $verbose && notify("Couldn't regrade state #{$state->id}!");
1065 // We need rounding here because grades in the DB get truncated
1066 // e.g. 0.33333 != 0.3333333, but we want them to be equal here
1067 if ((round((float)$replaystate->raw_grade
, 5) != round((float)$states[$j]->raw_grade
, 5))
1068 or (round((float)$replaystate->penalty
, 5) != round((float)$states[$j]->penalty
, 5))
1069 or (round((float)$replaystate->grade
, 5) != round((float)$states[$j]->grade
, 5))) {
1073 $replaystate->id
= $states[$j]->id
;
1074 $replaystate->changed
= true;
1075 $replaystate->update
= true; // This will ensure that the existing database entry is updated rather than a new one created
1076 save_question_session($question, $replaystate);
1079 // TODO, call a method in quiz to do this, where 'quiz' comes from
1080 // the question_attempts table.
1081 update_record('quiz_attempts', $attempt);
1090 * Processes an array of student responses, grading and saving them as appropriate
1092 * @return boolean Indicates success/failure
1093 * @param object $question Full question object, passed by reference
1094 * @param object $state Full state object, passed by reference
1095 * @param object $action object with the fields ->responses which
1096 * is an array holding the student responses,
1097 * ->action which specifies the action, e.g., QUESTION_EVENTGRADE,
1098 * and ->timestamp which is a timestamp from when the responses
1099 * were submitted by the student.
1100 * @param object $cmoptions
1101 * @param object $attempt The attempt is passed by reference so that
1102 * during grading its ->sumgrades field can be updated
1104 function question_process_responses(&$question, &$state, $action, $cmoptions, &$attempt) {
1107 // if no responses are set initialise to empty response
1108 if (!isset($action->responses
)) {
1109 $action->responses
= array('' => '');
1112 // make sure these are gone!
1113 unset($action->responses
['submit'], $action->responses
['validate']);
1115 // Check the question session is still open
1116 if (question_state_is_closed($state)) {
1120 // If $action->event is not set that implies saving
1121 if (! isset($action->event
)) {
1122 debugging('Ambiguous action in question_process_responses.' , DEBUG_DEVELOPER
);
1123 $action->event
= QUESTION_EVENTSAVE
;
1125 // If submitted then compare against last graded
1126 // responses, not last given responses in this case
1127 if (question_isgradingevent($action->event
)) {
1128 $state->responses
= $state->last_graded
->responses
;
1131 // Check for unchanged responses (exactly unchanged, not equivalent).
1132 // We also have to catch questions that the student has not yet attempted
1133 $sameresponses = $QTYPES[$question->qtype
]->compare_responses($question, $action, $state);
1134 if (!empty($state->last_graded
) && $state->last_graded
->event
== QUESTION_EVENTOPEN
&&
1135 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($courseid, $published = false, $only_editable = false, $selected = "") {
1657 $categoriesarray = question_category_options($courseid, $published, $only_editable);
1661 $nothing = 'choose';
1663 choose_from_menu($categoriesarray, 'category', $selected, $nothing);
1667 * Output an array of question categories.
1669 * Categories from this course and (optionally) published categories from other courses
1670 * are included. Optionally, only categories the current user may edit can be included.
1672 * @param integer $courseid the id of the course to get the categories for.
1673 * @param integer $published if true, include publised categories from other courses.
1674 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1675 * @return array The list of categories.
1677 function question_category_options($courseid, $published = false, $only_editable = false) {
1680 // get sql fragment for published
1683 $publishsql = " OR publish = 1";
1686 $categories = get_records_sql("
1687 SELECT cat.*, c.shortname AS coursename
1688 FROM {$CFG->prefix}question_categories cat, {$CFG->prefix}course c
1689 WHERE c.id = cat.course AND (cat.course = $courseid $publishsql)
1690 ORDER BY (CASE WHEN cat.course = $courseid THEN 0 ELSE 1 END), cat.parent, cat.sortorder, cat.name ASC");
1691 $categories = add_indented_names($categories);
1693 $categoriesarray = array();
1694 foreach ($categories as $category) {
1695 $cid = $category->id
;
1696 $cname = question_category_coursename($category, $courseid);
1697 if ((!$only_editable) ||
has_capability('moodle/question:managecategory', get_context_instance(CONTEXT_COURSE
, $category->course
))) {
1698 $categoriesarray[$cid] = $cname;
1701 return $categoriesarray;
1705 * If the category is not from this course, and it is a published category,
1706 * then return the course category name with the course shortname appended in
1707 * brackets. Otherwise, just return the category name.
1709 function question_category_coursename($category, $courseid = 0) {
1710 $cname = (isset($category->indentedname
)) ?
$category->indentedname
: $category->name
;
1711 if ($category->course
!= $courseid && $category->publish
) {
1712 if (!empty($category->coursename
)) {
1713 $coursename = $category->coursename
;
1715 $coursename = get_field('course', 'shortname', 'id', $category->course
);
1717 $cname .= " ($coursename)";
1723 * Returns a comma separated list of ids of the category and all subcategories
1725 function question_categorylist($categoryid) {
1726 // returns a comma separated list of ids of the category and all subcategories
1727 $categorylist = $categoryid;
1728 if ($subcategories = get_records('question_categories', 'parent', $categoryid, 'sortorder ASC', 'id, id')) {
1729 foreach ($subcategories as $subcategory) {
1730 $categorylist .= ','. question_categorylist($subcategory->id
);
1733 return $categorylist;
1737 * find and/or create the category described by a delimited list
1738 * e.g. tom/dick/harry
1739 * @param string catpath delimited category path
1740 * @param string delimiter path delimiting character
1741 * @param int courseid course to search for categories
1742 * @return mixed category object or null if fails
1744 function create_category_path( $catpath, $delimiter='/', $courseid=0 ) {
1745 $catpath = clean_param( $catpath,PARAM_PATH
);
1746 $catnames = explode( $delimiter, $catpath );
1749 foreach ($catnames as $catname) {
1750 if ($category = get_record( 'question_categories', 'name', $catname, 'course', $courseid, 'parent', $parent )) {
1751 $parent = $category->id
;
1754 // create the new category
1755 $category = new object;
1756 $category->course
= $courseid;
1757 $category->name
= $catname;
1758 $category->info
= '';
1759 $category->publish
= false;
1760 $category->parent
= $parent;
1761 $category->sortorder
= 999;
1762 $category->stamp
= make_unique_id_code();
1763 if (!($id = insert_record( 'question_categories', $category ))) {
1764 error( "cannot create new category - $catname" );
1766 $category->id
= $id;
1774 * get the category as a path (e.g., tom/dick/harry)
1775 * @param int id the id of the most nested catgory
1776 * @param string delimiter the delimiter you want
1777 * @return string the path
1779 function get_category_path( $id, $delimiter='/' ) {
1782 if (!$category = get_record( 'question_categories','id',$id )) {
1783 print_error( "Error reading category record - $id" );
1785 $name = $category->name
;
1786 $id = $category->parent
;
1787 if (!empty($path)) {
1788 $path = "{$name}{$delimiter}{$path}";
1798 //===========================
1799 // Import/Export Functions
1800 //===========================
1803 * Get list of available import or export formats
1804 * @param string $type 'import' if import list, otherwise export list assumed
1805 * @return array sorted list of import/export formats available
1807 function get_import_export_formats( $type ) {
1810 $fileformats = get_list_of_plugins("question/format");
1812 $fileformatname=array();
1813 require_once( "{$CFG->dirroot}/question/format.php" );
1814 foreach ($fileformats as $key => $fileformat) {
1815 $format_file = $CFG->dirroot
. "/question/format/$fileformat/format.php";
1816 if (file_exists( $format_file ) ) {
1817 require_once( $format_file );
1822 $classname = "qformat_$fileformat";
1823 $format_class = new $classname();
1824 if ($type=='import') {
1825 $provided = $format_class->provide_import();
1828 $provided = $format_class->provide_export();
1831 $formatname = get_string($fileformat, 'quiz');
1832 if ($formatname == "[[$fileformat]]") {
1833 $formatname = $fileformat; // Just use the raw folder name
1835 $fileformatnames[$fileformat] = $formatname;
1838 natcasesort($fileformatnames);
1840 return $fileformatnames;
1845 * Create default export filename
1847 * @return string default export filename
1848 * @param object $course
1849 * @param object $category
1851 function default_export_filename($course,$category) {
1852 //Take off some characters in the filename !!
1853 $takeoff = array(" ", ":", "/", "\\", "|");
1854 $export_word = str_replace($takeoff,"_",moodle_strtolower(get_string("exportfilename","quiz")));
1855 //If non-translated, use "export"
1856 if (substr($export_word,0,1) == "[") {
1857 $export_word= "export";
1860 //Calculate the date format string
1861 $export_date_format = str_replace(" ","_",get_string("exportnameformat","quiz"));
1862 //If non-translated, use "%Y%m%d-%H%M"
1863 if (substr($export_date_format,0,1) == "[") {
1864 $export_date_format = "%%Y%%m%%d-%%H%%M";
1867 //Calculate the shortname
1868 $export_shortname = clean_filename($course->shortname
);
1869 if (empty($export_shortname) or $export_shortname == '_' ) {
1870 $export_shortname = $course->id
;
1873 //Calculate the category name
1874 $export_categoryname = clean_filename($category->name
);
1876 //Calculate the final export filename
1878 $export_name = $export_word."-";
1880 $export_name .= moodle_strtolower($export_shortname)."-";
1882 $export_name .= moodle_strtolower($export_categoryname)."-";
1884 $export_name .= userdate(time(),$export_date_format,99,false);
1885 //The extension - no extension, supplied by format
1886 // $export_name .= ".txt";
1888 return $export_name;