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);
91 * options used in forms that move files.
94 define('QUESTION_FILENOTHINGSELECTED', 0);
95 define('QUESTION_FILEDONOTHING', 1);
96 define('QUESTION_FILECOPY', 2);
97 define('QUESTION_FILEMOVE', 3);
98 define('QUESTION_FILEMOVELINKSONLY', 4);
102 /// QTYPES INITIATION //////////////////
103 // These variables get initialised via calls to question_register_questiontype
104 // as the question type classes are included.
105 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
107 * Array holding question type objects
111 * Array of question types names translated to the user's language
113 * The $QTYPE_MENU array holds the names of all the question types that the user should
114 * be able to create directly. Some internal question types like random questions are excluded.
115 * The complete list of question types can be found in {@link $QTYPES}.
117 $QTYPE_MENU = array();
119 * String in the format "'type1','type2'" that can be used in SQL clauses like
120 * "WHERE q.type IN ($QTYPE_MANUAL)".
124 * String in the format "'type1','type2'" that can be used in SQL clauses like
125 * "WHERE q.type NOT IN ($QTYPE_EXCLUDE_FROM_RANDOM)".
127 $QTYPE_EXCLUDE_FROM_RANDOM = '';
130 * Add a new question type to the various global arrays above.
132 * @param object $qtype An instance of the new question type class.
134 function question_register_questiontype($qtype) {
135 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
137 $name = $qtype->name();
138 $QTYPES[$name] = $qtype;
139 $menuname = $qtype->menu_name();
141 $QTYPE_MENU[$name] = $menuname;
143 if ($qtype->is_manual_graded()) {
145 $QTYPE_MANUAL .= ',';
147 $QTYPE_MANUAL .= "'$name'";
149 if (!$qtype->is_usable_by_random()) {
150 if ($QTYPE_EXCLUDE_FROM_RANDOM) {
151 $QTYPE_EXCLUDE_FROM_RANDOM .= ',';
153 $QTYPE_EXCLUDE_FROM_RANDOM .= "'$name'";
157 require_once("$CFG->dirroot/question/type/questiontype.php");
159 // Load the questiontype.php file for each question type
160 // These files in turn call question_register_questiontype()
161 // with a new instance of each qtype class.
162 $qtypenames= get_list_of_plugins('question/type');
163 foreach($qtypenames as $qtypename) {
164 // Instanciates all plug-in question types
165 $qtypefilepath= "$CFG->dirroot/question/type/$qtypename/questiontype.php";
167 // echo "Loading $qtypename<br/>"; // Uncomment for debugging
168 if (is_readable($qtypefilepath)) {
169 require_once($qtypefilepath);
173 /// OTHER CLASSES /////////////////////////////////////////////////////////
176 * This holds the options that are set by the course module
180 * Whether a new attempt should be based on the previous one. If true
181 * then a new attempt will start in a state where all responses are set
182 * to the last responses from the previous attempt.
184 var $attemptonlast = false;
187 * Various option flags. The flags are accessed via bitwise operations
188 * using the constants defined in the CONSTANTS section above.
190 var $optionflags = QUESTION_ADAPTIVE
;
193 * Determines whether in the calculation of the score for a question
194 * penalties for earlier wrong responses within the same attempt will
197 var $penaltyscheme = true;
200 * The maximum time the user is allowed to answer the questions withing
201 * an attempt. This is measured in minutes so needs to be multiplied by
202 * 60 before compared to timestamps. If set to 0 no timelimit will be applied
207 * Timestamp for the closing time. Responses submitted after this time will
208 * be saved but no credit will be given for them.
210 var $timeclose = 9999999999;
213 * The id of the course from withing which the question is currently being used
215 var $course = SITEID
;
218 * Whether the answers in a multiple choice question should be randomly
219 * shuffled when a new attempt is started.
221 var $shuffleanswers = true;
224 * The number of decimals to be shown when scores are printed
226 var $decimalpoints = 2;
230 /// FUNCTIONS //////////////////////////////////////////////////////
233 * Returns an array of names of activity modules that use this question
235 * @param object $questionid
236 * @return array of strings
238 function question_list_instances($questionid) {
239 $instances = array();
240 $modules = get_records('modules');
241 foreach ($modules as $module) {
242 $fn = $module->name
.'_question_list_instances';
243 if (function_exists($fn)) {
244 $instances = $instances +
$fn($questionid);
252 * Returns list of 'allowed' grades for grade selection
253 * formatted suitably for dropdown box function
254 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
256 function get_grade_options() {
257 // define basic array of grades
280 // iterate through grades generating full range of options
281 $gradeoptionsfull = array();
282 $gradeoptions = array();
283 foreach ($grades as $grade) {
284 $percentage = 100 * $grade;
286 $gradeoptions["$grade"] = "$percentage %";
287 $gradeoptionsfull["$grade"] = "$percentage %";
288 $gradeoptionsfull["$neggrade"] = -$percentage." %";
290 $gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
293 arsort($gradeoptions, SORT_NUMERIC
);
294 arsort($gradeoptionsfull, SORT_NUMERIC
);
296 // construct return object
297 $grades = new stdClass
;
298 $grades->gradeoptions
= $gradeoptions;
299 $grades->gradeoptionsfull
= $gradeoptionsfull;
305 * match grade options
306 * if no match return error or match nearest
307 * @param array $gradeoptionsfull list of valid options
308 * @param int $grade grade to be tested
309 * @param string $matchgrades 'error' or 'nearest'
310 * @return mixed either 'fixed' value or false if erro
312 function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
313 // if we just need an error...
314 if ($matchgrades=='error') {
315 foreach($gradeoptionsfull as $value => $option) {
316 // slightly fuzzy test, never check floats for equality :-)
317 if (abs($grade-$value)<0.00001) {
321 // didn't find a match so that's an error
324 // work out nearest value
325 else if ($matchgrades=='nearest') {
327 foreach($gradeoptionsfull as $value => $option) {
328 if ($grade==$value) {
331 $hownear[ $value ] = abs( $grade - $value );
333 // reverse sort list of deltas and grab the last (smallest)
334 asort( $hownear, SORT_NUMERIC
);
336 return key( $hownear );
344 * Tests whether a category is in use by any activity module
347 * @param integer $categoryid
348 * @param boolean $recursive Whether to examine category children recursively
350 function question_category_isused($categoryid, $recursive = false) {
352 //Look at each question in the category
353 if ($questions = get_records('question', 'category', $categoryid)) {
354 foreach ($questions as $question) {
355 if (count(question_list_instances($question->id
))) {
361 //Look under child categories recursively
363 if ($children = get_records('question_categories', 'parent', $categoryid)) {
364 foreach ($children as $child) {
365 if (question_category_isused($child->id
, $recursive)) {
376 * Deletes all data associated to an attempt from the database
378 * @param integer $attemptid The id of the attempt being deleted
380 function delete_attempt($attemptid) {
383 $states = get_records('question_states', 'attempt', $attemptid);
385 $stateslist = implode(',', array_keys($states));
387 // delete question-type specific data
388 foreach ($QTYPES as $qtype) {
389 $qtype->delete_states($stateslist);
393 // delete entries from all other question tables
394 // It is important that this is done only after calling the questiontype functions
395 delete_records("question_states", "attempt", $attemptid);
396 delete_records("question_sessions", "attemptid", $attemptid);
397 delete_records("question_attempts", "id", $attemptid);
401 * Deletes question and all associated data from the database
403 * It will not delete a question if it is used by an activity module
404 * @param object $question The question being deleted
406 function delete_question($questionid) {
409 // Do not delete a question if it is used by an activity module
410 if (count(question_list_instances($questionid))) {
414 // delete questiontype-specific data
415 $question = get_record('question', 'id', $questionid);
416 question_require_capability_on($question, 'edit');
418 if (isset($QTYPES[$question->qtype
])) {
419 $QTYPES[$question->qtype
]->delete_question($questionid);
422 echo "Question with id $questionid does not exist.<br />";
425 if ($states = get_records('question_states', 'question', $questionid)) {
426 $stateslist = implode(',', array_keys($states));
428 // delete questiontype-specific data
429 foreach ($QTYPES as $qtype) {
430 $qtype->delete_states($stateslist);
434 // delete entries from all other question tables
435 // It is important that this is done only after calling the questiontype functions
436 delete_records("question_answers", "question", $questionid);
437 delete_records("question_states", "question", $questionid);
438 delete_records("question_sessions", "questionid", $questionid);
440 // Now recursively delete all child questions
441 if ($children = get_records('question', 'parent', $questionid)) {
442 foreach ($children as $child) {
443 if ($child->id
!= $questionid) {
444 delete_question($child->id
);
449 // Finally delete the question record itself
450 delete_records('question', 'id', $questionid);
456 * All question categories and their questions are deleted for this course.
458 * @param object $mod an object representing the activity
459 * @param boolean $feedback to specify if the process must output a summary of its work
462 function question_delete_course($course, $feedback=true) {
463 //To store feedback to be showed at the end of the process
464 $feedbackdata = array();
467 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
468 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
469 $categoriescourse = get_records('question_categories', 'contextid', $coursecontext->id
, 'parent', 'id, parent, name');
471 if ($categoriescourse) {
473 //Sort categories following their tree (parent-child) relationships
474 //this will make the feedback more readable
475 $categoriescourse = sort_categories_by_tree($categoriescourse);
477 foreach ($categoriescourse as $category) {
479 //Delete it completely (questions and category itself)
481 if ($questions = get_records("question", "category", $category->id
)) {
482 foreach ($questions as $question) {
483 delete_question($question->id
);
485 delete_records("question", "category", $category->id
);
487 //delete the category
488 delete_records('question_categories', 'id', $category->id
);
491 $feedbackdata[] = array($category->name
, $strcatdeleted);
493 //Inform about changes performed if feedback is enabled
495 $table = new stdClass
;
496 $table->head
= array(get_string('category','quiz'), get_string('action'));
497 $table->data
= $feedbackdata;
505 * All question categories and their questions are deleted for this activity.
507 * @param object $cm the course module object representing the activity
508 * @param boolean $feedback to specify if the process must output a summary of its work
511 function question_delete_activity($cm, $feedback=true) {
512 //To store feedback to be showed at the end of the process
513 $feedbackdata = array();
516 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
517 $modcontext = get_context_instance(CONTEXT_MODULE
, $cm->id
);
518 if ($categoriesmods = get_records('question_categories', 'contextid', $modcontext->id
, 'parent', 'id, parent, name')){
519 //Sort categories following their tree (parent-child) relationships
520 //this will make the feedback more readable
521 $categoriesmods = sort_categories_by_tree($categoriesmods);
523 foreach ($categoriesmods as $category) {
525 //Delete it completely (questions and category itself)
527 if ($questions = get_records("question", "category", $category->id
)) {
528 foreach ($questions as $question) {
529 delete_question($question->id
);
531 delete_records("question", "category", $category->id
);
533 //delete the category
534 delete_records('question_categories', 'id', $category->id
);
537 $feedbackdata[] = array($category->name
, $strcatdeleted);
539 //Inform about changes performed if feedback is enabled
541 $table = new stdClass
;
542 $table->head
= array(get_string('category','quiz'), get_string('action'));
543 $table->data
= $feedbackdata;
550 * @param array $row tab objects
551 * @param question_edit_contexts $contexts object representing contexts available from this context
552 * @param string $querystring to append to urls
554 function questionbank_navigation_tabs(&$row, $contexts, $querystring) {
555 global $CFG, $QUESTION_EDITTABCAPS;
557 'questions' =>array("$CFG->wwwroot/question/edit.php?$querystring", get_string('questions', 'quiz'), get_string('editquestions', 'quiz')),
558 'categories' =>array("$CFG->wwwroot/question/category.php?$querystring", get_string('categories', 'quiz'), get_string('editqcats', 'quiz')),
559 'import' =>array("$CFG->wwwroot/question/import.php?$querystring", get_string('import', 'quiz'), get_string('importquestions', 'quiz')),
560 'export' =>array("$CFG->wwwroot/question/export.php?$querystring", get_string('export', 'quiz'), get_string('exportquestions', 'quiz')));
561 foreach ($tabs as $tabname => $tabparams){
562 if ($contexts->have_one_edit_tab_cap($tabname)) {
563 $row[] = new tabobject($tabname, $tabparams[0], $tabparams[1], $tabparams[2]);
569 * Private function to factor common code out of get_question_options().
571 * @param object $question the question to tidy.
572 * @return boolean true if successful, else false.
574 function _tidy_question(&$question) {
576 if (!array_key_exists($question->qtype
, $QTYPES)) {
577 $question->qtype
= 'missingtype';
578 $question->questiontext
= '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext
;
580 $question->name_prefix
= question_make_name_prefix($question->id
);
581 return $QTYPES[$question->qtype
]->get_question_options($question);
585 * Updates the question objects with question type specific
586 * information by calling {@link get_question_options()}
588 * Can be called either with an array of question objects or with a single
591 * @param mixed $questions Either an array of question objects to be updated
592 * or just a single question object
593 * @return bool Indicates success or failure.
595 function get_question_options(&$questions) {
596 if (is_array($questions)) { // deal with an array of questions
597 foreach ($questions as $i => $notused) {
598 if (!_tidy_question($questions[$i])) {
603 } else { // deal with single question
604 return _tidy_question($questions);
609 * Loads the most recent state of each question session from the database
612 * For each question the most recent session state for the current attempt
613 * is loaded from the question_states table and the question type specific data and
614 * responses are added by calling {@link restore_question_state()} which in turn
615 * calls {@link restore_session_and_responses()} for each question.
616 * If no states exist for the question instance an empty state object is
617 * created representing the start of a session and empty question
618 * type specific information and responses are created by calling
619 * {@link create_session_and_responses()}.
621 * @return array An array of state objects representing the most recent
622 * states of the question sessions.
623 * @param array $questions The questions for which sessions are to be restored or
625 * @param object $cmoptions
626 * @param object $attempt The attempt for which the question sessions are
627 * to be restored or created.
628 * @param mixed either the id of a previous attempt, if this attmpt is
629 * building on a previous one, or false for a clean attempt.
631 function get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) {
632 global $CFG, $QTYPES;
634 // get the question ids
635 $ids = array_keys($questions);
636 $questionlist = implode(',', $ids);
638 // The question field must be listed first so that it is used as the
639 // array index in the array returned by get_records_sql
640 $statefields = 'n.questionid as question, s.*, n.sumpenalty, n.manualcomment';
641 // Load the newest states for the questions
642 $sql = "SELECT $statefields".
643 " FROM {$CFG->prefix}question_states s,".
644 " {$CFG->prefix}question_sessions n".
645 " WHERE s.id = n.newest".
646 " AND n.attemptid = '$attempt->uniqueid'".
647 " AND n.questionid IN ($questionlist)";
648 $states = get_records_sql($sql);
650 // Load the newest graded states for the questions
651 $sql = "SELECT $statefields".
652 " FROM {$CFG->prefix}question_states s,".
653 " {$CFG->prefix}question_sessions n".
654 " WHERE s.id = n.newgraded".
655 " AND n.attemptid = '$attempt->uniqueid'".
656 " AND n.questionid IN ($questionlist)";
657 $gradedstates = get_records_sql($sql);
659 // loop through all questions and set the last_graded states
660 foreach ($ids as $i) {
661 if (isset($states[$i])) {
662 restore_question_state($questions[$i], $states[$i]);
663 if (isset($gradedstates[$i])) {
664 restore_question_state($questions[$i], $gradedstates[$i]);
665 $states[$i]->last_graded
= $gradedstates[$i];
667 $states[$i]->last_graded
= clone($states[$i]);
670 // If the new attempt is to be based on a previous attempt get it and clean things
671 // Having lastattemptid filled implies that (should we double check?):
672 // $attempt->attempt > 1 and $cmoptions->attemptonlast and !$attempt->preview
673 if ($lastattemptid) {
674 // find the responses from the previous attempt and save them to the new session
676 // Load the last graded state for the question
677 $statefields = 'n.questionid as question, s.*, n.sumpenalty';
678 $sql = "SELECT $statefields".
679 " FROM {$CFG->prefix}question_states s,".
680 " {$CFG->prefix}question_sessions n".
681 " WHERE s.id = n.newgraded".
682 " AND n.attemptid = '$lastattemptid'".
683 " AND n.questionid = '$i'";
684 if (!$laststate = get_record_sql($sql)) {
685 // Only restore previous responses that have been graded
688 // Restore the state so that the responses will be restored
689 restore_question_state($questions[$i], $laststate);
690 $states[$i] = clone($laststate);
692 // create a new empty state
693 $states[$i] = new object;
694 $states[$i]->question
= $i;
695 $states[$i]->responses
= array('' => '');
696 $states[$i]->raw_grade
= 0;
699 // now fill/overide initial values
700 $states[$i]->attempt
= $attempt->uniqueid
;
701 $states[$i]->seq_number
= 0;
702 $states[$i]->timestamp
= $attempt->timestart
;
703 $states[$i]->event
= ($attempt->timefinish
) ? QUESTION_EVENTCLOSE
: QUESTION_EVENTOPEN
;
704 $states[$i]->grade
= 0;
705 $states[$i]->penalty
= 0;
706 $states[$i]->sumpenalty
= 0;
707 $states[$i]->manualcomment
= '';
709 // Prevent further changes to the session from incrementing the
711 $states[$i]->changed
= true;
713 if ($lastattemptid) {
714 // prepare the previous responses for new processing
715 $action = new stdClass
;
716 $action->responses
= $laststate->responses
;
717 $action->timestamp
= $laststate->timestamp
;
718 $action->event
= QUESTION_EVENTSAVE
; //emulate save of questions from all pages MDL-7631
720 // Process these responses ...
721 question_process_responses($questions[$i], $states[$i], $action, $cmoptions, $attempt);
723 // Fix for Bug #5506: When each attempt is built on the last one,
724 // preserve the options from any previous attempt.
725 if ( isset($laststate->options
) ) {
726 $states[$i]->options
= $laststate->options
;
729 // Create the empty question type specific information
730 if (!$QTYPES[$questions[$i]->qtype
]->create_session_and_responses(
731 $questions[$i], $states[$i], $cmoptions, $attempt)) {
735 $states[$i]->last_graded
= clone($states[$i]);
743 * Creates the run-time fields for the states
745 * Extends the state objects for a question by calling
746 * {@link restore_session_and_responses()}
747 * @param object $question The question for which the state is needed
748 * @param object $state The state as loaded from the database
749 * @return boolean Represents success or failure
751 function restore_question_state(&$question, &$state) {
754 // initialise response to the value in the answer field
755 $state->responses
= array('' => addslashes($state->answer
));
756 unset($state->answer
);
757 $state->manualcomment
= isset($state->manualcomment
) ?
addslashes($state->manualcomment
) : '';
759 // Set the changed field to false; any code which changes the
760 // question session must set this to true and must increment
761 // ->seq_number. The save_question_session
762 // function will save the new state object to the database if the field is
764 $state->changed
= false;
766 // Load the question type specific data
767 return $QTYPES[$question->qtype
]
768 ->restore_session_and_responses($question, $state);
773 * Saves the current state of the question session to the database
775 * The state object representing the current state of the session for the
776 * question is saved to the question_states table with ->responses[''] saved
777 * to the answer field of the database table. The information in the
778 * question_sessions table is updated.
779 * The question type specific data is then saved.
780 * @return mixed The id of the saved or updated state or false
781 * @param object $question The question for which session is to be saved.
782 * @param object $state The state information to be saved. In particular the
783 * most recent responses are in ->responses. The object
784 * is updated to hold the new ->id.
786 function save_question_session(&$question, &$state) {
788 // Check if the state has changed
789 if (!$state->changed
&& isset($state->id
)) {
792 // Set the legacy answer field
793 $state->answer
= isset($state->responses
['']) ?
$state->responses
[''] : '';
796 if (!empty($state->update
)) { // this forces the old state record to be overwritten
797 update_record('question_states', $state);
799 if (!$state->id
= insert_record('question_states', $state)) {
801 unset($state->answer
);
806 // create or update the session
807 if (!$session = get_record('question_sessions', 'attemptid',
808 $state->attempt
, 'questionid', $question->id
)) {
809 $session->attemptid
= $state->attempt
;
810 $session->questionid
= $question->id
;
811 $session->newest
= $state->id
;
812 // The following may seem weird, but the newgraded field needs to be set
813 // already even if there is no graded state yet.
814 $session->newgraded
= $state->id
;
815 $session->sumpenalty
= $state->sumpenalty
;
816 $session->manualcomment
= $state->manualcomment
;
817 if (!insert_record('question_sessions', $session)) {
818 error('Could not insert entry in question_sessions');
821 $session->newest
= $state->id
;
822 if (question_state_is_graded($state) or $state->event
== QUESTION_EVENTOPEN
) {
823 // this state is graded or newly opened, so it goes into the lastgraded field as well
824 $session->newgraded
= $state->id
;
825 $session->sumpenalty
= $state->sumpenalty
;
826 $session->manualcomment
= $state->manualcomment
;
828 $session->manualcomment
= addslashes($session->manualcomment
);
830 update_record('question_sessions', $session);
833 unset($state->answer
);
835 // Save the question type specific state information and responses
836 if (!$QTYPES[$question->qtype
]->save_session_and_responses(
837 $question, $state)) {
840 // Reset the changed flag
841 $state->changed
= false;
846 * Determines whether a state has been graded by looking at the event field
848 * @return boolean true if the state has been graded
849 * @param object $state
851 function question_state_is_graded($state) {
852 return ($state->event
== QUESTION_EVENTGRADE
853 or $state->event
== QUESTION_EVENTCLOSEANDGRADE
854 or $state->event
== QUESTION_EVENTMANUALGRADE
);
858 * Determines whether a state has been closed by looking at the event field
860 * @return boolean true if the state has been closed
861 * @param object $state
863 function question_state_is_closed($state) {
864 return ($state->event
== QUESTION_EVENTCLOSE
865 or $state->event
== QUESTION_EVENTCLOSEANDGRADE
866 or $state->event
== QUESTION_EVENTMANUALGRADE
);
871 * Extracts responses from submitted form
873 * This can extract the responses given to one or several questions present on a page
874 * It returns an array with one entry for each question, indexed by question id
875 * Each entry is an object with the properties
876 * ->event The event that has triggered the submission. This is determined by which button
877 * the user has pressed.
878 * ->responses An array holding the responses to an individual question, indexed by the
879 * name of the corresponding form element.
880 * ->timestamp A unix timestamp
881 * @return array array of action objects, indexed by question ids.
882 * @param array $questions an array containing at least all questions that are used on the form
883 * @param array $formdata the data submitted by the form on the question page
884 * @param integer $defaultevent the event type used if no 'mark' or 'validate' is submitted
886 function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE
) {
890 foreach ($formdata as $key => $response) {
891 // Get the question id from the response name
892 if (false !== ($quid = question_get_id_from_name_prefix($key))) {
893 // check if this is a valid id
894 if (!isset($questions[$quid])) {
895 error('Form contained question that is not in questionids');
898 // Remove the name prefix from the name
900 $key = substr($key, strlen($questions[$quid]->name_prefix
));
901 if (false === $key) {
904 // Check for question validate and mark buttons & set events
905 if ($key === 'validate') {
906 $actions[$quid]->event
= QUESTION_EVENTVALIDATE
;
907 } else if ($key === 'submit') {
908 $actions[$quid]->event
= QUESTION_EVENTSUBMIT
;
910 $actions[$quid]->event
= $defaultevent;
913 // Update the state with the new response
914 $actions[$quid]->responses
[$key] = $response;
917 $actions[$quid]->timestamp
= $time;
920 foreach ($actions as $quid => $notused) {
921 ksort($actions[$quid]->responses
);
928 * Returns the html for question feedback image.
929 * @param float $fraction value representing the correctness of the user's
930 * response to a question.
931 * @param boolean $selected whether or not the answer is the one that the
935 function question_get_feedback_image($fraction, $selected=true) {
939 if ($fraction >= 1.0) {
941 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_green_big.gif" '.
942 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
944 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_green_small.gif" '.
945 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
947 } else if ($fraction > 0.0 && $fraction < 1.0) {
949 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_amber_big.gif" '.
950 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
952 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_amber_small.gif" '.
953 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
957 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/cross_red_big.gif" '.
958 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
960 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/cross_red_small.gif" '.
961 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
969 * Returns the class name for question feedback.
970 * @param float $fraction value representing the correctness of the user's
971 * response to a question.
974 function question_get_feedback_class($fraction) {
978 if ($fraction >= 1.0) {
980 } else if ($fraction > 0.0 && $fraction < 1.0) {
981 $class = 'partiallycorrect';
983 $class = 'incorrect';
990 * For a given question in an attempt we walk the complete history of states
991 * and recalculate the grades as we go along.
993 * This is used when a question is changed and old student
994 * responses need to be marked with the new version of a question.
996 * TODO: Make sure this is not quiz-specific
998 * @return boolean Indicates whether the grade has changed
999 * @param object $question A question object
1000 * @param object $attempt The attempt, in which the question needs to be regraded.
1001 * @param object $cmoptions
1002 * @param boolean $verbose Optional. Whether to print progress information or not.
1004 function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false) {
1006 // load all states for this question in this attempt, ordered in sequence
1007 if ($states = get_records_select('question_states',
1008 "attempt = '{$attempt->uniqueid}' AND question = '{$question->id}'",
1009 'seq_number ASC')) {
1010 $states = array_values($states);
1012 // Subtract the grade for the latest state from $attempt->sumgrades to get the
1013 // sumgrades for the attempt without this question.
1014 $attempt->sumgrades
-= $states[count($states)-1]->grade
;
1016 // Initialise the replaystate
1017 $state = clone($states[0]);
1018 $state->manualcomment
= get_field('question_sessions', 'manualcomment', 'attemptid',
1019 $attempt->uniqueid
, 'questionid', $question->id
);
1020 restore_question_state($question, $state);
1021 $state->sumpenalty
= 0.0;
1022 $replaystate = clone($state);
1023 $replaystate->last_graded
= $state;
1026 for($j = 1; $j < count($states); $j++
) {
1027 restore_question_state($question, $states[$j]);
1028 $action = new stdClass
;
1029 $action->responses
= $states[$j]->responses
;
1030 $action->timestamp
= $states[$j]->timestamp
;
1032 // Change event to submit so that it will be reprocessed
1033 if (QUESTION_EVENTCLOSE
== $states[$j]->event
1034 or QUESTION_EVENTGRADE
== $states[$j]->event
1035 or QUESTION_EVENTCLOSEANDGRADE
== $states[$j]->event
) {
1036 $action->event
= QUESTION_EVENTSUBMIT
;
1038 // By default take the event that was saved in the database
1040 $action->event
= $states[$j]->event
;
1043 if ($action->event
== QUESTION_EVENTMANUALGRADE
) {
1044 question_process_comment($question, $replaystate, $attempt,
1045 $replaystate->manualcomment
, $states[$j]->grade
);
1048 // Reprocess (regrade) responses
1049 if (!question_process_responses($question, $replaystate,
1050 $action, $cmoptions, $attempt)) {
1051 $verbose && notify("Couldn't regrade state #{$state->id}!");
1055 // We need rounding here because grades in the DB get truncated
1056 // e.g. 0.33333 != 0.3333333, but we want them to be equal here
1057 if ((round((float)$replaystate->raw_grade
, 5) != round((float)$states[$j]->raw_grade
, 5))
1058 or (round((float)$replaystate->penalty
, 5) != round((float)$states[$j]->penalty
, 5))
1059 or (round((float)$replaystate->grade
, 5) != round((float)$states[$j]->grade
, 5))) {
1063 $replaystate->id
= $states[$j]->id
;
1064 $replaystate->changed
= true;
1065 $replaystate->update
= true; // This will ensure that the existing database entry is updated rather than a new one created
1066 save_question_session($question, $replaystate);
1069 // TODO, call a method in quiz to do this, where 'quiz' comes from
1070 // the question_attempts table.
1071 update_record('quiz_attempts', $attempt);
1080 * Processes an array of student responses, grading and saving them as appropriate
1082 * @return boolean Indicates success/failure
1083 * @param object $question Full question object, passed by reference
1084 * @param object $state Full state object, passed by reference
1085 * @param object $action object with the fields ->responses which
1086 * is an array holding the student responses,
1087 * ->action which specifies the action, e.g., QUESTION_EVENTGRADE,
1088 * and ->timestamp which is a timestamp from when the responses
1089 * were submitted by the student.
1090 * @param object $cmoptions
1091 * @param object $attempt The attempt is passed by reference so that
1092 * during grading its ->sumgrades field can be updated
1094 function question_process_responses(&$question, &$state, $action, $cmoptions, &$attempt) {
1097 // if no responses are set initialise to empty response
1098 if (!isset($action->responses
)) {
1099 $action->responses
= array('' => '');
1102 // make sure these are gone!
1103 unset($action->responses
['submit'], $action->responses
['validate']);
1105 // Check the question session is still open
1106 if (question_state_is_closed($state)) {
1110 // If $action->event is not set that implies saving
1111 if (! isset($action->event
)) {
1112 debugging('Ambiguous action in question_process_responses.' , DEBUG_DEVELOPER
);
1113 $action->event
= QUESTION_EVENTSAVE
;
1115 // If submitted then compare against last graded
1116 // responses, not last given responses in this case
1117 if (question_isgradingevent($action->event
)) {
1118 $state->responses
= $state->last_graded
->responses
;
1121 // Check for unchanged responses (exactly unchanged, not equivalent).
1122 // We also have to catch questions that the student has not yet attempted
1123 $sameresponses = $QTYPES[$question->qtype
]->compare_responses($question, $action, $state);
1124 if (!empty($state->last_graded
) && $state->last_graded
->event
== QUESTION_EVENTOPEN
&&
1125 question_isgradingevent($action->event
)) {
1126 $sameresponses = false;
1129 // If the response has not been changed then we do not have to process it again
1130 // unless the attempt is closing or validation is requested
1131 if ($sameresponses and QUESTION_EVENTCLOSE
!= $action->event
1132 and QUESTION_EVENTVALIDATE
!= $action->event
) {
1136 // Roll back grading information to last graded state and set the new
1138 $newstate = clone($state->last_graded
);
1139 $newstate->responses
= $action->responses
;
1140 $newstate->seq_number
= $state->seq_number +
1;
1141 $newstate->changed
= true; // will assure that it gets saved to the database
1142 $newstate->last_graded
= clone($state->last_graded
);
1143 $newstate->timestamp
= $action->timestamp
;
1146 // Set the event to the action we will perform. The question type specific
1147 // grading code may override this by setting it to QUESTION_EVENTCLOSE if the
1148 // attempt at the question causes the session to close
1149 $state->event
= $action->event
;
1151 if (!question_isgradingevent($action->event
)) {
1152 // Grade the response but don't update the overall grade
1153 $QTYPES[$question->qtype
]->grade_responses($question, $state, $cmoptions);
1155 // Temporary hack because question types are not given enough control over what is going
1156 // on. Used by Opaque questions.
1157 // TODO fix this code properly.
1158 if (!empty($state->believeevent
)) {
1159 // If the state was graded we need to ...
1160 if (question_state_is_graded($state)) {
1161 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1163 // update the attempt grade
1164 $attempt->sumgrades
-= (float)$state->last_graded
->grade
;
1165 $attempt->sumgrades +
= (float)$state->grade
;
1167 // and update the last_graded field.
1168 unset($state->last_graded
);
1169 $state->last_graded
= clone($state);
1170 unset($state->last_graded
->changed
);
1173 // Don't allow the processing to change the event type
1174 $state->event
= $action->event
;
1177 } else { // grading event
1179 // Unless the attempt is closing, we want to work out if the current responses
1180 // (or equivalent responses) were already given in the last graded attempt.
1181 if(QUESTION_EVENTCLOSE
!= $action->event
&& QUESTION_EVENTOPEN
!= $state->last_graded
->event
&&
1182 $QTYPES[$question->qtype
]->compare_responses($question, $state, $state->last_graded
)) {
1183 $state->event
= QUESTION_EVENTDUPLICATE
;
1186 // If we did not find a duplicate or if the attempt is closing, perform grading
1187 if ((!$sameresponses and QUESTION_EVENTDUPLICATE
!= $state->event
) or
1188 QUESTION_EVENTCLOSE
== $action->event
) {
1190 $QTYPES[$question->qtype
]->grade_responses($question, $state, $cmoptions);
1191 // Calculate overall grade using correct penalty method
1192 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1195 // If the state was graded we need to ...
1196 if (question_state_is_graded($state)) {
1197 // update the attempt grade
1198 $attempt->sumgrades
-= (float)$state->last_graded
->grade
;
1199 $attempt->sumgrades +
= (float)$state->grade
;
1201 // and update the last_graded field.
1202 unset($state->last_graded
);
1203 $state->last_graded
= clone($state);
1204 unset($state->last_graded
->changed
);
1207 $attempt->timemodified
= $action->timestamp
;
1213 * Determine if event requires grading
1215 function question_isgradingevent($event) {
1216 return (QUESTION_EVENTSUBMIT
== $event || QUESTION_EVENTCLOSE
== $event);
1220 * Applies the penalty from the previous graded responses to the raw grade
1221 * for the current responses
1223 * The grade for the question in the current state is computed by subtracting the
1224 * penalty accumulated over the previous graded responses at the question from the
1225 * raw grade. If the timestamp is more than 1 minute beyond the end of the attempt
1226 * the grade is set to zero. The ->grade field of the state object is modified to
1227 * reflect the new grade but is never allowed to decrease.
1228 * @param object $question The question for which the penalty is to be applied.
1229 * @param object $state The state for which the grade is to be set from the
1230 * raw grade and the cumulative penalty from the last
1231 * graded state. The ->grade field is updated by applying
1232 * the penalty scheme determined in $cmoptions to the ->raw_grade and
1233 * ->last_graded->penalty fields.
1234 * @param object $cmoptions The options set by the course module.
1235 * The ->penaltyscheme field determines whether penalties
1236 * for incorrect earlier responses are subtracted.
1238 function question_apply_penalty_and_timelimit(&$question, &$state, $attempt, $cmoptions) {
1239 // TODO. Quiz dependancy. The fact that the attempt that is passed in here
1240 // is from quiz_attempts, and we use things like $cmoptions->timelimit.
1242 // deal with penalty
1243 if ($cmoptions->penaltyscheme
) {
1244 $state->grade
= $state->raw_grade
- $state->sumpenalty
;
1245 $state->sumpenalty +
= (float) $state->penalty
;
1247 $state->grade
= $state->raw_grade
;
1250 // deal with timelimit
1251 if ($cmoptions->timelimit
) {
1252 // We allow for 5% uncertainty in the following test
1253 if ($state->timestamp
- $attempt->timestart
> $cmoptions->timelimit
* 63) {
1254 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id
);
1255 if (!has_capability('mod/quiz:ignoretimelimits', get_context_instance(CONTEXT_MODULE
, $cm->id
),
1256 $attempt->userid
, false)) {
1262 // deal with closing time
1263 if ($cmoptions->timeclose
and $state->timestamp
> ($cmoptions->timeclose +
60) // allowing 1 minute lateness
1264 and !$attempt->preview
) { // ignore closing time for previews
1268 // Ensure that the grade does not go down
1269 $state->grade
= max($state->grade
, $state->last_graded
->grade
);
1273 * Print the icon for the question type
1275 * @param object $question The question object for which the icon is required
1276 * @param boolean $return If true the functions returns the link as a string
1278 function print_question_icon($question, $return = false) {
1279 global $QTYPES, $CFG;
1281 $namestr = $QTYPES[$question->qtype
]->menu_name();
1282 $html = '<img src="' . $CFG->wwwroot
. '/question/type/' .
1283 $question->qtype
. '/icon.gif" alt="' .
1284 $namestr . '" title="' . $namestr . '" />';
1293 * Returns a html link to the question image if there is one
1295 * @return string The html image tag or the empy string if there is no image.
1296 * @param object $question The question object
1298 function get_question_image($question) {
1303 if (!$category = get_record('question_categories', 'id', $question->category
)){
1304 error('invalid category id '.$question->category
);
1306 $coursefilesdir = get_filesdir_from_context(get_context_instance_by_id($category->contextid
));
1308 if ($question->image
) {
1310 if (substr(strtolower($question->image
), 0, 7) == 'http://') {
1311 $img .= $question->image
;
1313 } else if ($CFG->slasharguments
) { // Use this method if possible for better caching
1314 $img .= "$CFG->wwwroot/file.php/$coursefilesdir/$question->image";
1317 $img .= "$CFG->wwwroot/file.php?file=/$coursefilesdir/$question->image";
1323 function question_print_comment_box($question, $state, $attempt, $url) {
1326 $prefix = 'response';
1327 $usehtmleditor = can_use_richtext_editor();
1328 $grade = round($state->last_graded
->grade
, 3);
1329 echo '<form method="post" action="'.$url.'">';
1330 include($CFG->dirroot
.'/question/comment.html');
1331 echo '<input type="hidden" name="attempt" value="'.$attempt->uniqueid
.'" />';
1332 echo '<input type="hidden" name="question" value="'.$question->id
.'" />';
1333 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1334 echo '<input type="submit" name="submit" value="'.get_string('save', 'quiz').'" />';
1337 if ($usehtmleditor) {
1342 function question_process_comment($question, &$state, &$attempt, $comment, $grade) {
1344 // Update the comment and save it in the database
1345 $comment = trim($comment);
1346 $state->manualcomment
= $comment;
1347 if (!set_field('question_sessions', 'manualcomment', $comment, 'attemptid', $attempt->uniqueid
, 'questionid', $question->id
)) {
1348 error("Cannot save comment");
1351 // Update the attempt if the score has changed.
1352 if (abs($state->last_graded
->grade
- $grade) > 0.002) {
1353 $attempt->sumgrades
= $attempt->sumgrades
- $state->last_graded
->grade +
$grade;
1354 $attempt->timemodified
= time();
1355 if (!update_record('quiz_attempts', $attempt)) {
1356 error('Failed to save the current quiz attempt!');
1360 // Update the state if either the score has changed, or this is the first
1361 // manual grade event and there is actually a grade of comment to process.
1362 // We don't need to store the modified state in the database, we just need
1363 // to set the $state->changed flag.
1364 if (abs($state->last_graded
->grade
- $grade) > 0.002 ||
1365 ($state->last_graded
->event
!= QUESTION_EVENTMANUALGRADE
&& ($grade > 0.002 ||
$comment != ''))) {
1367 // We want to update existing state (rather than creating new one) if it
1368 // was itself created by a manual grading event.
1369 $state->update
= ($state->event
== QUESTION_EVENTMANUALGRADE
) ?
1 : 0;
1371 // Update the other parts of the state object.
1372 $state->raw_grade
= $grade;
1373 $state->grade
= $grade;
1374 $state->penalty
= 0;
1375 $state->timestamp
= time();
1376 $state->seq_number++
;
1377 $state->event
= QUESTION_EVENTMANUALGRADE
;
1379 // Update the last graded state (don't simplify!)
1380 unset($state->last_graded
);
1381 $state->last_graded
= clone($state);
1383 // We need to indicate that the state has changed in order for it to be saved.
1384 $state->changed
= 1;
1390 * Construct name prefixes for question form element names
1392 * Construct the name prefix that should be used for example in the
1393 * names of form elements created by questions.
1394 * This is called by {@link get_question_options()}
1395 * to set $question->name_prefix.
1396 * This name prefix includes the question id which can be
1397 * extracted from it with {@link question_get_id_from_name_prefix()}.
1400 * @param integer $id The question id
1402 function question_make_name_prefix($id) {
1403 return 'resp' . $id . '_';
1407 * Extract question id from the prefix of form element names
1409 * @return integer The question id
1410 * @param string $name The name that contains a prefix that was
1411 * constructed with {@link question_make_name_prefix()}
1413 function question_get_id_from_name_prefix($name) {
1414 if (!preg_match('/^resp([0-9]+)_/', $name, $matches))
1416 return (integer) $matches[1];
1420 * Returns the unique id for a new attempt
1422 * Every module can keep their own attempts table with their own sequential ids but
1423 * the question code needs to also have a unique id by which to identify all these
1424 * attempts. Hence a module, when creating a new attempt, calls this function and
1425 * stores the return value in the 'uniqueid' field of its attempts table.
1427 function question_new_attempt_uniqueid($modulename='quiz') {
1429 $attempt = new stdClass
;
1430 $attempt->modulename
= $modulename;
1431 if (!$id = insert_record('question_attempts', $attempt)) {
1432 error('Could not create new entry in question_attempts table');
1438 * Creates a stamp that uniquely identifies this version of the question
1440 * In future we want this to use a hash of the question data to guarantee that
1441 * identical versions have the same version stamp.
1443 * @param object $question
1444 * @return string A unique version stamp
1446 function question_hash($question) {
1447 return make_unique_id_code();
1451 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
1453 * Get the HTML that needs to be included in the head tag when the
1454 * questions in $questionlist are printed in the gives states.
1456 * @param array $questionlist a list of questionids of the questions what will appear on this page.
1457 * @param array $questions an array of question objects, whose keys are question ids.
1458 * Must contain all the questions in $questionlist
1459 * @param array $states an array of question state objects, whose keys are question ids.
1460 * Must contain the state of all the questions in $questionlist
1462 * @return string some HTML code that can go inside the head tag.
1464 function get_html_head_contributions(&$questionlist, &$questions, &$states) {
1467 $contributions = array();
1468 foreach ($questionlist as $questionid) {
1469 $question = $questions[$questionid];
1470 $contributions = array_merge($contributions,
1471 $QTYPES[$question->qtype
]->get_html_head_contributions(
1472 $question, $states[$questionid]));
1474 return implode("\n", array_unique($contributions));
1480 * Simply calls the question type specific print_question() method.
1481 * @param object $question The question to be rendered.
1482 * @param object $state The state to render the question in.
1483 * @param integer $number The number for this question.
1484 * @param object $cmoptions The options specified by the course module
1485 * @param object $options An object specifying the rendering options.
1487 function print_question(&$question, &$state, $number, $cmoptions, $options=null) {
1490 $QTYPES[$question->qtype
]->print_question($question, $state, $number,
1491 $cmoptions, $options);
1494 * Saves question options
1496 * Simply calls the question type specific save_question_options() method.
1498 function save_question_options($question) {
1501 $QTYPES[$question->qtype
]->save_question_options($question);
1505 * Gets all teacher stored answers for a given question
1507 * Simply calls the question type specific get_all_responses() method.
1510 function get_question_responses($question, $state) {
1512 $r = $QTYPES[$question->qtype
]->get_all_responses($question, $state);
1518 * Gets the response given by the user in a particular state
1520 * Simply calls the question type specific get_actual_response() method.
1523 function get_question_actual_response($question, $state) {
1526 $r = $QTYPES[$question->qtype
]->get_actual_response($question, $state);
1531 * TODO: document this
1534 function get_question_fraction_grade($question, $state) {
1537 $r = $QTYPES[$question->qtype
]->get_fractional_grade($question, $state);
1542 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1545 * returns the categories with their names ordered following parent-child relationships
1546 * finally it tries to return pending categories (those being orphaned, whose parent is
1547 * incorrect) to avoid missing any category from original array.
1549 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1550 $children = array();
1551 $keys = array_keys($categories);
1553 foreach ($keys as $key) {
1554 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
1555 $children[$key] = $categories[$key];
1556 $categories[$key]->processed
= true;
1557 $children = $children +
sort_categories_by_tree($categories, $children[$key]->id
, $level+
1);
1560 //If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too
1562 foreach ($keys as $key) {
1563 //If not processed and it's a good candidate to start (because its parent doesn't exist in the course)
1564 if (!isset($categories[$key]->processed
) && !record_exists('question_categories', 'course', $categories[$key]->course
, 'id', $categories[$key]->parent
)) {
1565 $children[$key] = $categories[$key];
1566 $categories[$key]->processed
= true;
1567 $children = $children +
sort_categories_by_tree($categories, $children[$key]->id
, $level+
1);
1575 * Private method, only for the use of add_indented_names().
1577 * Recursively adds an indentedname field to each category, starting with the category
1578 * with id $id, and dealing with that category and all its children, and
1579 * return a new array, with those categories in the right order.
1581 * @param array $categories an array of categories which has had childids
1582 * fields added by flatten_category_tree(). Passed by reference for
1583 * performance only. It is not modfied.
1584 * @param int $id the category to start the indenting process from.
1585 * @param int $depth the indent depth. Used in recursive calls.
1586 * @return array a new array of categories, in the right order for the tree.
1588 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1590 // Indent the name of this category.
1591 $newcategories = array();
1592 $newcategories[$id] = $categories[$id];
1593 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) . $categories[$id]->name
;
1595 // Recursively indent the children.
1596 foreach ($categories[$id]->childids
as $childid) {
1597 if ($childid != $nochildrenof){
1598 $newcategories = $newcategories +
flatten_category_tree($categories, $childid, $depth +
1, $nochildrenof);
1602 // Remove the childids array that were temporarily added.
1603 unset($newcategories[$id]->childids
);
1605 return $newcategories;
1609 * Format categories into an indented list reflecting the tree structure.
1611 * @param array $categories An array of category objects, for example from the.
1612 * @return array The formatted list of categories.
1614 function add_indented_names($categories, $nochildrenof = -1) {
1616 // Add an array to each category to hold the child category ids. This array will be removed
1617 // again by flatten_category_tree(). It should not be used outside these two functions.
1618 foreach (array_keys($categories) as $id) {
1619 $categories[$id]->childids
= array();
1622 // Build the tree structure, and record which categories are top-level.
1623 // We have to be careful, because the categories array may include published
1624 // categories from other courses, but not their parents.
1625 $toplevelcategoryids = array();
1626 foreach (array_keys($categories) as $id) {
1627 if (!empty($categories[$id]->parent
) && array_key_exists($categories[$id]->parent
, $categories)) {
1628 $categories[$categories[$id]->parent
]->childids
[] = $id;
1630 $toplevelcategoryids[] = $id;
1634 // Flatten the tree to and add the indents.
1635 $newcategories = array();
1636 foreach ($toplevelcategoryids as $id) {
1637 $newcategories = $newcategories +
flatten_category_tree($categories, $id, 0, $nochildrenof);
1640 return $newcategories;
1644 * Output a select menu of question categories.
1646 * Categories from this course and (optionally) published categories from other courses
1647 * are included. Optionally, only categories the current user may edit can be included.
1649 * @param integer $courseid the id of the course to get the categories for.
1650 * @param integer $published if true, include publised categories from other courses.
1651 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1652 * @param integer $selected optionally, the id of a category to be selected by default in the dropdown.
1654 function question_category_select_menu($contexts, $top = false, $currentcat = 0, $selected = "", $nochildrenof = -1) {
1655 $categoriesarray = question_category_options($contexts, $top, $currentcat, false, $nochildrenof);
1659 $nothing = 'choose';
1661 choose_from_menu_nested($categoriesarray, 'category', $selected, $nothing);
1665 * Gets the default category in the most specific context.
1666 * If no categories exist yet then default ones are created in all contexts.
1668 * @param array $contexts The context objects for this context and all parent contexts.
1669 * @return object The default category - the category in the course context
1671 function question_make_default_categories($contexts) {
1673 // If it already exists, just return it.
1674 foreach ($contexts as $key => $context) {
1675 if (!$categoryrs = get_recordset_select("question_categories", "contextid = '{$context->id}'", 'sortorder, name', '*', '', 1)) {
1676 error('error getting category record');
1678 if (!$category = rs_fetch_record($categoryrs)){
1679 // Otherwise, we need to make one
1680 $category = new stdClass
;
1681 $contextname = print_context_name($context, false, true);
1682 $category->name
= addslashes(get_string('defaultfor', 'question', $contextname));
1683 $category->info
= addslashes(get_string('defaultinfofor', 'question', $contextname));
1684 $category->contextid
= $context->id
;
1685 $category->parent
= 0;
1686 $category->sortorder
= 999; // By default, all categories get this number, and are sorted alphabetically.
1687 $category->stamp
= make_unique_id_code();
1688 if (!$category->id
= insert_record('question_categories', $category)) {
1689 error('Error creating a default category for context '.print_context_name($context));
1693 if ($context->contextlevel
== CONTEXT_COURSE
){
1694 $toreturn = clone($category);
1703 * Get all the category objects, including a count of the number of questions in that category,
1704 * for all the categories in the lists $contexts.
1706 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1707 * @param string $sortorder used as the ORDER BY clause in the select statement.
1708 * @return array of category objects.
1710 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1712 return get_records_sql("
1713 SELECT *, (SELECT count(1) FROM {$CFG->prefix}question q
1714 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') as questioncount
1715 FROM {$CFG->prefix}question_categories c
1716 WHERE c.contextid IN ($contexts)
1717 ORDER BY $sortorder");
1721 * Output an array of question categories.
1723 function question_category_options($contexts, $top = false, $currentcat = 0, $popupform = false, $nochildrenof = -1) {
1725 $pcontexts = array();
1726 foreach($contexts as $context){
1727 $pcontexts[] = $context->id
;
1729 $contextslist = join($pcontexts, ', ');
1731 $categories = get_categories_for_contexts($contextslist);
1733 $categories = question_add_context_in_key($categories);
1736 $categories = question_add_tops($categories, $pcontexts);
1738 $categories = add_indented_names($categories, $nochildrenof);
1740 //sort cats out into different contexts
1741 $categoriesarray = array();
1742 foreach ($pcontexts as $pcontext){
1743 $contextstring = print_context_name(get_context_instance_by_id($pcontext), true, true);
1744 foreach ($categories as $category) {
1745 if ($category->contextid
== $pcontext){
1746 $cid = $category->id
;
1747 if ($currentcat!= $cid ||
$currentcat==0) {
1748 $countstring = (!empty($category->questioncount
))?
" ($category->questioncount)":'';
1749 $categoriesarray[$contextstring][$cid] = $category->indentedname
.$countstring;
1755 $popupcats = array();
1756 foreach ($categoriesarray as $contextstring => $optgroup){
1757 $popupcats[] = '--'.$contextstring;
1758 $popupcats = array_merge($popupcats, $optgroup);
1759 $popupcats[] = '--';
1763 return $categoriesarray;
1767 function question_add_context_in_key($categories){
1768 $newcatarray = array();
1769 foreach ($categories as $id => $category) {
1770 $category->parent
= "$category->parent,$category->contextid";
1771 $category->id
= "$category->id,$category->contextid";
1772 $newcatarray["$id,$category->contextid"] = $category;
1774 return $newcatarray;
1776 function question_add_tops($categories, $pcontexts){
1778 foreach ($pcontexts as $context){
1779 $newcat = new object();
1780 $newcat->id
= "0,$context";
1781 $newcat->name
= get_string('top');
1782 $newcat->parent
= -1;
1783 $newcat->contextid
= $context;
1784 $topcats["0,$context"] = $newcat;
1786 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1787 return array_merge($topcats, $categories);
1791 * Returns a comma separated list of ids of the category and all subcategories
1793 function question_categorylist($categoryid) {
1794 // returns a comma separated list of ids of the category and all subcategories
1795 $categorylist = $categoryid;
1796 if ($subcategories = get_records('question_categories', 'parent', $categoryid, 'sortorder ASC', 'id, id')) {
1797 foreach ($subcategories as $subcategory) {
1798 $categorylist .= ','. question_categorylist($subcategory->id
);
1801 return $categorylist;
1807 //===========================
1808 // Import/Export Functions
1809 //===========================
1812 * Get list of available import or export formats
1813 * @param string $type 'import' if import list, otherwise export list assumed
1814 * @return array sorted list of import/export formats available
1816 function get_import_export_formats( $type ) {
1819 $fileformats = get_list_of_plugins("question/format");
1821 $fileformatname=array();
1822 require_once( "{$CFG->dirroot}/question/format.php" );
1823 foreach ($fileformats as $key => $fileformat) {
1824 $format_file = $CFG->dirroot
. "/question/format/$fileformat/format.php";
1825 if (file_exists( $format_file ) ) {
1826 require_once( $format_file );
1831 $classname = "qformat_$fileformat";
1832 $format_class = new $classname();
1833 if ($type=='import') {
1834 $provided = $format_class->provide_import();
1837 $provided = $format_class->provide_export();
1840 $formatname = get_string($fileformat, 'quiz');
1841 if ($formatname == "[[$fileformat]]") {
1842 $formatname = $fileformat; // Just use the raw folder name
1844 $fileformatnames[$fileformat] = $formatname;
1847 natcasesort($fileformatnames);
1849 return $fileformatnames;
1854 * Create default export filename
1856 * @return string default export filename
1857 * @param object $course
1858 * @param object $category
1860 function default_export_filename($course,$category) {
1861 //Take off some characters in the filename !!
1862 $takeoff = array(" ", ":", "/", "\\", "|");
1863 $export_word = str_replace($takeoff,"_",moodle_strtolower(get_string("exportfilename","quiz")));
1864 //If non-translated, use "export"
1865 if (substr($export_word,0,1) == "[") {
1866 $export_word= "export";
1869 //Calculate the date format string
1870 $export_date_format = str_replace(" ","_",get_string("exportnameformat","quiz"));
1871 //If non-translated, use "%Y%m%d-%H%M"
1872 if (substr($export_date_format,0,1) == "[") {
1873 $export_date_format = "%%Y%%m%%d-%%H%%M";
1876 //Calculate the shortname
1877 $export_shortname = clean_filename($course->shortname
);
1878 if (empty($export_shortname) or $export_shortname == '_' ) {
1879 $export_shortname = $course->id
;
1882 //Calculate the category name
1883 $export_categoryname = clean_filename($category->name
);
1885 //Calculate the final export filename
1887 $export_name = $export_word."-";
1889 $export_name .= moodle_strtolower($export_shortname)."-";
1891 $export_name .= moodle_strtolower($export_categoryname)."-";
1893 $export_name .= userdate(time(),$export_date_format,99,false);
1894 //The extension - no extension, supplied by format
1895 // $export_name .= ".txt";
1897 return $export_name;
1899 class context_to_string_translator
{
1901 * @var array used to translate between contextids and strings for this context.
1903 var $contexttostringarray = array();
1905 function context_to_string_translator($contexts){
1906 $this->generate_context_to_string_array($contexts);
1909 function context_to_string($contextid){
1910 return $this->contexttostringarray
[$contextid];
1913 function string_to_context($contextname){
1914 $contextid = array_search($contextname, $this->contexttostringarray
);
1918 function generate_context_to_string_array($contexts){
1919 if (!$this->contexttostringarray
){
1921 foreach ($contexts as $context){
1922 switch ($context->contextlevel
){
1923 case CONTEXT_MODULE
:
1924 $contextstring = 'module';
1926 case CONTEXT_COURSE
:
1927 $contextstring = 'course';
1929 case CONTEXT_COURSECAT
:
1930 $contextstring = "cat$catno";
1933 case CONTEXT_SYSTEM
:
1934 $contextstring = 'system';
1937 $this->contexttostringarray
[$context->id
] = $contextstring;
1946 * Check capability on category
1947 * @param mixed $question object or id
1948 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1949 * @param integer $cachecat useful to cache all question records in a category
1950 * @return boolean this user has the capability $cap for this question $question?
1952 function question_has_capability_on($question, $cap, $cachecat = -1){
1954 // these are capabilities on existing questions capabilties are
1955 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1956 $question_questioncaps = array('edit', 'view', 'use', 'move');
1957 static $questions = array();
1958 static $categories = array();
1959 static $cachedcat = array();
1960 if ($cachecat != -1 && (array_search($cachecat, $cachedcat)===FALSE)){
1961 $questions +
= get_records('question', 'category', $cachecat);
1962 $cachedcat[] = $cachecat;
1964 if (!is_object($question)){
1965 if (!isset($questions[$question])){
1966 if (!$questions[$question] = get_record('question', 'id', $question)){
1967 print_error('invalidcategory', 'quiz');
1970 $question = $questions[$question];
1972 if (!isset($categories[$question->category
])){
1973 if (!$categories[$question->category
] = get_record('question_categories', 'id', $question->category
)){
1974 print_error('invalidcategory', 'quiz');
1977 $category = $categories[$question->category
];
1979 if (array_search($cap, $question_questioncaps)!== FALSE){
1980 if (!has_capability('moodle/question:'.$cap.'all', get_context_instance_by_id($category->contextid
))){
1981 if ($question->createdby
== $USER->id
){
1982 return has_capability('moodle/question:'.$cap.'mine', get_context_instance_by_id($category->contextid
));
1990 return has_capability('moodle/question:'.$cap, get_context_instance_by_id($category->contextid
));
1996 * Require capability on question.
1998 function question_require_capability_on($question, $cap){
1999 if (!question_has_capability_on($question, $cap)){
2000 print_error('nopermissions', '', '', $cap);
2005 function question_file_links_base_url($courseid){
2007 $baseurl = preg_quote("$CFG->wwwroot/file.php", '!');
2008 $baseurl .= '('.preg_quote('?file=', '!').')?';//may or may not
2009 //be using slasharguments, accept either
2010 $baseurl .= "/$courseid/";//course directory
2015 * Find all course / site files linked to in a piece of html.
2016 * @param string html the html to search
2017 * @param int course search for files for courseid course or set to siteid for
2018 * finding site files.
2019 * @return array files with keys being files.
2021 function question_find_file_links_from_html($html, $courseid){
2023 $baseurl = question_file_links_base_url($courseid);
2025 '(<\s*(a|img)\s[^>]*(href|src)\s*=\s*")'.$baseurl.'([^"]*)"'.
2027 '(<\s*(a|img)\s[^>]*(href|src)\s*=\s*\')'.$baseurl.'([^\']*)\''.
2030 $no = preg_match_all($searchfor, $html, $matches);
2032 $rawurls = array_filter(array_merge($matches[5], $matches[10]));//array_filter removes empty elements
2033 //remove any links that point somewhere they shouldn't
2034 foreach (array_keys($rawurls) as $rawurlkey){
2035 if (!$cleanedurl = question_url_check($rawurls[$rawurlkey])){
2036 unset($rawurls[$rawurlkey]);
2038 $rawurls[$rawurlkey] = $cleanedurl;
2042 $urls = array_flip($rawurls);// array_flip removes duplicate files
2043 // and when we merge arrays will continue to automatically remove duplicates
2050 * Check that url doesn't point anywhere it shouldn't
2052 * @param $url string relative url within course files directory
2053 * @return mixed boolean false if not OK or cleaned URL as string if OK
2055 function question_url_check($url){
2057 if ((substr(strtolower($url), 0, strlen($CFG->moddata
)) == strtolower($CFG->moddata
)) ||
2058 (substr(strtolower($url), 0, 10) == 'backupdata')){
2061 return clean_param($url, PARAM_PATH
);
2066 * Find all course / site files linked to in a piece of html.
2067 * @param string html the html to search
2068 * @param int course search for files for courseid course or set to siteid for
2069 * finding site files.
2070 * @return array files with keys being files.
2072 function question_replace_file_links_in_html($html, $fromcourseid, $tocourseid, $url, $destination, &$changed){
2074 if ($CFG->slasharguments
) { // Use this method if possible for better caching
2075 $tourl = "$CFG->wwwroot/file.php/$tocourseid/$destination";
2078 $tourl = "$CFG->wwwroot/file.php?file=/$tocourseid/$destination";
2080 $fromurl = question_file_links_base_url($fromcourseid).preg_quote($url, '!');
2081 $searchfor = array('!(<\s*(a|img)\s[^>]*(href|src)\s*=\s*")'.$fromurl.'(")!i',
2082 '!(<\s*(a|img)\s[^>]*(href|src)\s*=\s*\')'.$fromurl.'(\')!i');
2083 $newhtml = preg_replace($searchfor, '\\1'.$tourl.'\\5', $html);
2084 if ($newhtml != $html){
2090 function get_filesdir_from_context($context){
2091 switch ($context->contextlevel
){
2092 case CONTEXT_COURSE
:
2093 $courseid = $context->instanceid
;
2095 case CONTEXT_MODULE
:
2096 $courseid = get_field('course_modules', 'course', 'id', $context->instanceid
);
2098 case CONTEXT_COURSECAT
:
2099 case CONTEXT_SYSTEM
:
2103 error('Unsupported contextlevel in category record!');