3 * Code for handling and processing questions
5 * This is code that is module independent, i.e., can be used by any module that
6 * uses questions, like quiz, lesson, ..
7 * This script also loads the questiontype classes
8 * Code for handling the editing of questions is in {@link question/editlib.php}
10 * TODO: separate those functions which form part of the API
11 * from the helper functions.
13 * @author Martin Dougiamas and many others. This has recently been completely
14 * rewritten by Alex Smith, Julian Sedding and Gustav Delius as part of
15 * the Serving Mathematics project
16 * {@link http://maths.york.ac.uk/serving_maths}
17 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
21 /// CONSTANTS ///////////////////////////////////
24 * The different types of events that can create question states
26 define('QUESTION_EVENTOPEN', '0'); // The state was created by Moodle
27 define('QUESTION_EVENTNAVIGATE', '1'); // The responses were saved because the student navigated to another page (this is not currently used)
28 define('QUESTION_EVENTSAVE', '2'); // The student has requested that the responses should be saved but not submitted or validated
29 define('QUESTION_EVENTGRADE', '3'); // Moodle has graded the responses. A SUBMIT event can be changed to a GRADE event by Moodle.
30 define('QUESTION_EVENTDUPLICATE', '4'); // The responses submitted were the same as previously
31 define('QUESTION_EVENTVALIDATE', '5'); // The student has requested a validation. This causes the responses to be saved as well, but not graded.
32 define('QUESTION_EVENTCLOSEANDGRADE', '6'); // Moodle has graded the responses. A CLOSE event can be changed to a CLOSEANDGRADE event by Moodle.
33 define('QUESTION_EVENTSUBMIT', '7'); // The student response has been submitted but it has not yet been marked
34 define('QUESTION_EVENTCLOSE', '8'); // The response has been submitted and the session has been closed, either because the student requested it or because Moodle did it (e.g. because of a timelimit). The responses have not been graded.
35 define('QUESTION_EVENTMANUALGRADE', '9'); // Grade was entered by teacher
37 define('QUESTION_EVENTS_GRADED', QUESTION_EVENTGRADE
.','.
38 QUESTION_EVENTCLOSEANDGRADE
.','.
39 QUESTION_EVENTMANUALGRADE
);
43 * The core question types.
45 define("SHORTANSWER", "shortanswer");
46 define("TRUEFALSE", "truefalse");
47 define("MULTICHOICE", "multichoice");
48 define("RANDOM", "random");
49 define("MATCH", "match");
50 define("RANDOMSAMATCH", "randomsamatch");
51 define("DESCRIPTION", "description");
52 define("NUMERICAL", "numerical");
53 define("MULTIANSWER", "multianswer");
54 define("CALCULATED", "calculated");
55 define("ESSAY", "essay");
59 * Constant determines the number of answer boxes supplied in the editing
60 * form for multiple choice and similar question types.
62 define("QUESTION_NUMANS", "10");
65 * Constant determines the number of answer boxes supplied in the editing
66 * form for multiple choice and similar question types to start with, with
67 * the option of adding QUESTION_NUMANS_ADD more answers.
69 define("QUESTION_NUMANS_START", 3);
72 * Constant determines the number of answer boxes to add in the editing
73 * form for multiple choice and similar question types when the user presses
74 * 'add form fields button'.
76 define("QUESTION_NUMANS_ADD", 3);
79 * The options used when popping up a question preview window in Javascript.
81 define('QUESTION_PREVIEW_POPUP_OPTIONS', 'scrollbars=yes,resizable=yes,width=700,height=540');
84 * Option flags for ->optionflags
85 * The options are read out via bitwise operation using these constants
88 * Whether the questions is to be run in adaptive mode. If this is not set then
89 * a question closes immediately after the first submission of responses. This
90 * is how question is Moodle always worked before version 1.5
92 define('QUESTION_ADAPTIVE', 1);
95 * options used in forms that move files.
98 define('QUESTION_FILENOTHINGSELECTED', 0);
99 define('QUESTION_FILEDONOTHING', 1);
100 define('QUESTION_FILECOPY', 2);
101 define('QUESTION_FILEMOVE', 3);
102 define('QUESTION_FILEMOVELINKSONLY', 4);
106 /// QTYPES INITIATION //////////////////
107 // These variables get initialised via calls to question_register_questiontype
108 // as the question type classes are included.
109 global $QTYPES, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
111 * Array holding question type objects
115 * String in the format "'type1','type2'" that can be used in SQL clauses like
116 * "WHERE q.type IN ($QTYPE_MANUAL)".
120 * String in the format "'type1','type2'" that can be used in SQL clauses like
121 * "WHERE q.type NOT IN ($QTYPE_EXCLUDE_FROM_RANDOM)".
123 $QTYPE_EXCLUDE_FROM_RANDOM = '';
126 * Add a new question type to the various global arrays above.
128 * @param object $qtype An instance of the new question type class.
130 function question_register_questiontype($qtype) {
131 global $QTYPES, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
133 $name = $qtype->name();
134 $QTYPES[$name] = $qtype;
135 if ($qtype->is_manual_graded()) {
137 $QTYPE_MANUAL .= ',';
139 $QTYPE_MANUAL .= "'$name'";
141 if (!$qtype->is_usable_by_random()) {
142 if ($QTYPE_EXCLUDE_FROM_RANDOM) {
143 $QTYPE_EXCLUDE_FROM_RANDOM .= ',';
145 $QTYPE_EXCLUDE_FROM_RANDOM .= "'$name'";
149 require_once("$CFG->dirroot/question/type/questiontype.php");
151 // Load the questiontype.php file for each question type
152 // These files in turn call question_register_questiontype()
153 // with a new instance of each qtype class.
154 $qtypenames= get_list_of_plugins('question/type');
155 foreach($qtypenames as $qtypename) {
156 // Instanciates all plug-in question types
157 $qtypefilepath= "$CFG->dirroot/question/type/$qtypename/questiontype.php";
159 // echo "Loading $qtypename<br/>"; // Uncomment for debugging
160 if (is_readable($qtypefilepath)) {
161 require_once($qtypefilepath);
166 * An array of question type names translated to the user's language, suitable for use when
167 * creating a drop-down menu of options.
169 * Long-time Moodle programmers will realise that this replaces the old $QTYPE_MENU array.
170 * The array returned will only hold the names of all the question types that the user should
171 * be able to create directly. Some internal question types like random questions are excluded.
173 * @return array an array of question type names translated to the user's language.
175 function question_type_menu() {
177 static $menu_options = null;
178 if (is_null($menu_options)) {
179 $menu_options = array();
180 foreach ($QTYPES as $name => $qtype) {
181 $menuname = $qtype->menu_name();
183 $menu_options[$name] = $menuname;
187 return $menu_options;
190 /// OTHER CLASSES /////////////////////////////////////////////////////////
193 * This holds the options that are set by the course module
197 * Whether a new attempt should be based on the previous one. If true
198 * then a new attempt will start in a state where all responses are set
199 * to the last responses from the previous attempt.
201 var $attemptonlast = false;
204 * Various option flags. The flags are accessed via bitwise operations
205 * using the constants defined in the CONSTANTS section above.
207 var $optionflags = QUESTION_ADAPTIVE
;
210 * Determines whether in the calculation of the score for a question
211 * penalties for earlier wrong responses within the same attempt will
214 var $penaltyscheme = true;
217 * The maximum time the user is allowed to answer the questions withing
218 * an attempt. This is measured in minutes so needs to be multiplied by
219 * 60 before compared to timestamps. If set to 0 no timelimit will be applied
224 * Timestamp for the closing time. Responses submitted after this time will
225 * be saved but no credit will be given for them.
227 var $timeclose = 9999999999;
230 * The id of the course from withing which the question is currently being used
232 var $course = SITEID
;
235 * Whether the answers in a multiple choice question should be randomly
236 * shuffled when a new attempt is started.
238 var $shuffleanswers = true;
241 * The number of decimals to be shown when scores are printed
243 var $decimalpoints = 2;
247 /// FUNCTIONS //////////////////////////////////////////////////////
250 * Returns an array of names of activity modules that use this question
252 * @param object $questionid
253 * @return array of strings
255 function question_list_instances($questionid) {
257 $instances = array();
258 $modules = get_records('modules');
259 foreach ($modules as $module) {
260 $fullmod = $CFG->dirroot
. '/mod/' . $module->name
;
261 if (file_exists($fullmod . '/lib.php')) {
262 include_once($fullmod . '/lib.php');
263 $fn = $module->name
.'_question_list_instances';
264 if (function_exists($fn)) {
265 $instances = $instances +
$fn($questionid);
273 * Determine whether there arey any questions belonging to this context, that is whether any of its
274 * question categories contain any questions. This will return true even if all the questions are
277 * @param mixed $context either a context object, or a context id.
278 * @return boolean whether any of the question categories beloning to this context have
279 * any questions in them.
281 function question_context_has_any_questions($context) {
283 if (is_object($context)) {
284 $contextid = $context->id
;
285 } else if (is_numeric($context)) {
286 $contextid = $context;
288 print_error('invalidcontextinhasanyquestions', 'question');
290 return record_exists_sql('SELECT * FROM ' . $CFG->prefix
. 'question q ' .
291 'JOIN ' . $CFG->prefix
. 'question_categories qc ON qc.id = q.category ' .
292 "WHERE qc.contextid = $contextid AND q.parent = 0");
296 * Returns list of 'allowed' grades for grade selection
297 * formatted suitably for dropdown box function
298 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
300 function get_grade_options() {
301 // define basic array of grades
325 // iterate through grades generating full range of options
326 $gradeoptionsfull = array();
327 $gradeoptions = array();
328 foreach ($grades as $grade) {
329 $percentage = 100 * $grade;
331 $gradeoptions["$grade"] = "$percentage %";
332 $gradeoptionsfull["$grade"] = "$percentage %";
333 $gradeoptionsfull["$neggrade"] = -$percentage." %";
335 $gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
338 arsort($gradeoptions, SORT_NUMERIC
);
339 arsort($gradeoptionsfull, SORT_NUMERIC
);
341 // construct return object
342 $grades = new stdClass
;
343 $grades->gradeoptions
= $gradeoptions;
344 $grades->gradeoptionsfull
= $gradeoptionsfull;
350 * match grade options
351 * if no match return error or match nearest
352 * @param array $gradeoptionsfull list of valid options
353 * @param int $grade grade to be tested
354 * @param string $matchgrades 'error' or 'nearest'
355 * @return mixed either 'fixed' value or false if erro
357 function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
358 // if we just need an error...
359 if ($matchgrades=='error') {
360 foreach($gradeoptionsfull as $value => $option) {
361 // slightly fuzzy test, never check floats for equality :-)
362 if (abs($grade-$value)<0.00001) {
366 // didn't find a match so that's an error
369 // work out nearest value
370 else if ($matchgrades=='nearest') {
372 foreach($gradeoptionsfull as $value => $option) {
373 if ($grade==$value) {
376 $hownear[ $value ] = abs( $grade - $value );
378 // reverse sort list of deltas and grab the last (smallest)
379 asort( $hownear, SORT_NUMERIC
);
381 return key( $hownear );
389 * Tests whether a category is in use by any activity module
392 * @param integer $categoryid
393 * @param boolean $recursive Whether to examine category children recursively
395 function question_category_isused($categoryid, $recursive = false) {
397 //Look at each question in the category
398 if ($questions = get_records('question', 'category', $categoryid)) {
399 foreach ($questions as $question) {
400 if (count(question_list_instances($question->id
))) {
406 //Look under child categories recursively
408 if ($children = get_records('question_categories', 'parent', $categoryid)) {
409 foreach ($children as $child) {
410 if (question_category_isused($child->id
, $recursive)) {
421 * Deletes all data associated to an attempt from the database
423 * @param integer $attemptid The id of the attempt being deleted
425 function delete_attempt($attemptid) {
428 $states = get_records('question_states', 'attempt', $attemptid);
430 $stateslist = implode(',', array_keys($states));
432 // delete question-type specific data
433 foreach ($QTYPES as $qtype) {
434 $qtype->delete_states($stateslist);
438 // delete entries from all other question tables
439 // It is important that this is done only after calling the questiontype functions
440 delete_records("question_states", "attempt", $attemptid);
441 delete_records("question_sessions", "attemptid", $attemptid);
442 delete_records("question_attempts", "id", $attemptid);
446 * Deletes question and all associated data from the database
448 * It will not delete a question if it is used by an activity module
449 * @param object $question The question being deleted
451 function delete_question($questionid) {
454 if (!$question = get_record('question', 'id', $questionid)) {
455 // In some situations, for example if this was a child of a
456 // Cloze question that was previously deleted, the question may already
457 // have gone. In this case, just do nothing.
461 // Do not delete a question if it is used by an activity module
462 if (count(question_list_instances($questionid))) {
466 // delete questiontype-specific data
467 question_require_capability_on($question, 'edit');
469 if (isset($QTYPES[$question->qtype
])) {
470 $QTYPES[$question->qtype
]->delete_question($questionid);
473 echo "Question with id $questionid does not exist.<br />";
476 if ($states = get_records('question_states', 'question', $questionid)) {
477 $stateslist = implode(',', array_keys($states));
479 // delete questiontype-specific data
480 foreach ($QTYPES as $qtype) {
481 $qtype->delete_states($stateslist);
485 // delete entries from all other question tables
486 // It is important that this is done only after calling the questiontype functions
487 delete_records("question_answers", "question", $questionid);
488 delete_records("question_states", "question", $questionid);
489 delete_records("question_sessions", "questionid", $questionid);
491 // Now recursively delete all child questions
492 if ($children = get_records('question', 'parent', $questionid)) {
493 foreach ($children as $child) {
494 if ($child->id
!= $questionid) {
495 delete_question($child->id
);
500 // Finally delete the question record itself
501 delete_records('question', 'id', $questionid);
507 * All question categories and their questions are deleted for this course.
509 * @param object $mod an object representing the activity
510 * @param boolean $feedback to specify if the process must output a summary of its work
513 function question_delete_course($course, $feedback=true) {
514 //To store feedback to be showed at the end of the process
515 $feedbackdata = array();
518 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
519 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
520 $categoriescourse = get_records('question_categories', 'contextid', $coursecontext->id
, 'parent', 'id, parent, name');
522 if ($categoriescourse) {
524 //Sort categories following their tree (parent-child) relationships
525 //this will make the feedback more readable
526 $categoriescourse = sort_categories_by_tree($categoriescourse);
528 foreach ($categoriescourse as $category) {
530 //Delete it completely (questions and category itself)
532 if ($questions = get_records("question", "category", $category->id
)) {
533 foreach ($questions as $question) {
534 delete_question($question->id
);
536 delete_records("question", "category", $category->id
);
538 //delete the category
539 delete_records('question_categories', 'id', $category->id
);
542 $feedbackdata[] = array($category->name
, $strcatdeleted);
544 //Inform about changes performed if feedback is enabled
546 $table = new stdClass
;
547 $table->head
= array(get_string('category','quiz'), get_string('action'));
548 $table->data
= $feedbackdata;
556 * Category is about to be deleted,
557 * 1/ All question categories and their questions are deleted for this course category.
558 * 2/ All questions are moved to new category
560 * @param object $category course category object
561 * @param object $newcategory empty means everything deleted, otherwise id of category where content moved
562 * @param boolean $feedback to specify if the process must output a summary of its work
565 function question_delete_course_category($category, $newcategory, $feedback=true) {
566 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
567 if (empty($newcategory)) {
568 $feedbackdata = array(); // To store feedback to be showed at the end of the process
569 $rescueqcategory = null; // See the code around the call to question_save_from_deletion.
570 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
572 // Loop over question categories.
573 if ($categories = get_records('question_categories', 'contextid', $context->id
, 'parent', 'id, parent, name')) {
574 foreach ($categories as $category) {
576 // Deal with any questions in the category.
577 if ($questions = get_records('question', 'category', $category->id
)) {
579 // Try to delete each question.
580 foreach ($questions as $question) {
581 delete_question($question->id
);
584 // Check to see if there were any questions that were kept because they are
585 // still in use somehow, even though quizzes in courses in this category will
586 // already have been deteted. This could happen, for example, if questions are
587 // added to a course, and then that course is moved to another category (MDL-14802).
588 $questionids = get_records_select_menu('question', 'category = ' . $category->id
, '', 'id,1');
589 if (!empty($questionids)) {
590 if (!$rescueqcategory = question_save_from_deletion(implode(',', array_keys($questionids)),
591 get_parent_contextid($context), print_context_name($context), $rescueqcategory)) {
594 $feedbackdata[] = array($category->name
, get_string('questionsmovedto', 'question', $rescueqcategory->name
));
598 // Now delete the category.
599 if (!delete_records('question_categories', 'id', $category->id
)) {
602 $feedbackdata[] = array($category->name
, $strcatdeleted);
604 } // End loop over categories.
607 // Output feedback if requested.
608 if ($feedback and $feedbackdata) {
609 $table = new stdClass
;
610 $table->head
= array(get_string('questioncategory','question'), get_string('action'));
611 $table->data
= $feedbackdata;
616 // Move question categories ot the new context.
617 if (!$newcontext = get_context_instance(CONTEXT_COURSECAT
, $newcategory->id
)) {
620 if (!set_field('question_categories', 'contextid', $newcontext->id
, 'contextid', $context->id
)) {
625 $a->oldplace
= print_context_name($context);
626 $a->newplace
= print_context_name($newcontext);
627 notify(get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
635 * Enter description here...
637 * @param string $questionids list of questionids
638 * @param object $newcontext the context to create the saved category in.
639 * @param string $oldplace a textual description of the think being deleted, e.g. from get_context_name
640 * @param object $newcategory
641 * @return mixed false on
643 function question_save_from_deletion($questionids, $newcontextid, $oldplace, $newcategory = null) {
644 // Make a category in the parent context to move the questions to.
645 if (is_null($newcategory)) {
646 $newcategory = new object();
647 $newcategory->parent
= 0;
648 $newcategory->contextid
= $newcontextid;
649 $newcategory->name
= addslashes(get_string('questionsrescuedfrom', 'question', $oldplace));
650 $newcategory->info
= addslashes(get_string('questionsrescuedfrominfo', 'question', $oldplace));
651 $newcategory->sortorder
= 999;
652 $newcategory->stamp
= make_unique_id_code();
653 if (!$newcategory->id
= insert_record('question_categories', $newcategory)) {
658 // Move any remaining questions to the 'saved' category.
659 if (!question_move_questions_to_category($questionids, $newcategory->id
)) {
666 * All question categories and their questions are deleted for this activity.
668 * @param object $cm the course module object representing the activity
669 * @param boolean $feedback to specify if the process must output a summary of its work
672 function question_delete_activity($cm, $feedback=true) {
673 //To store feedback to be showed at the end of the process
674 $feedbackdata = array();
677 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
678 $modcontext = get_context_instance(CONTEXT_MODULE
, $cm->id
);
679 if ($categoriesmods = get_records('question_categories', 'contextid', $modcontext->id
, 'parent', 'id, parent, name')){
680 //Sort categories following their tree (parent-child) relationships
681 //this will make the feedback more readable
682 $categoriesmods = sort_categories_by_tree($categoriesmods);
684 foreach ($categoriesmods as $category) {
686 //Delete it completely (questions and category itself)
688 if ($questions = get_records("question", "category", $category->id
)) {
689 foreach ($questions as $question) {
690 delete_question($question->id
);
692 delete_records("question", "category", $category->id
);
694 //delete the category
695 delete_records('question_categories', 'id', $category->id
);
698 $feedbackdata[] = array($category->name
, $strcatdeleted);
700 //Inform about changes performed if feedback is enabled
702 $table = new stdClass
;
703 $table->head
= array(get_string('category','quiz'), get_string('action'));
704 $table->data
= $feedbackdata;
712 * This function should be considered private to the question bank, it is called from
713 * question/editlib.php question/contextmoveq.php and a few similar places to to the work of
714 * acutally moving questions and associated data. However, callers of this function also have to
715 * do other work, which is why you should not call this method directly from outside the questionbank.
717 * @param string $questionids a comma-separated list of question ids.
718 * @param integer $newcategory the id of the category to move to.
720 function question_move_questions_to_category($questionids, $newcategory) {
723 // Move the questions themselves.
724 $result = $result && set_field_select('question', 'category', $newcategory, "id IN ($questionids)");
726 // Move any subquestions belonging to them.
727 $result = $result && set_field_select('question', 'category', $newcategory, "parent IN ($questionids)");
729 // TODO Deal with datasets.
735 * @param array $row tab objects
736 * @param question_edit_contexts $contexts object representing contexts available from this context
737 * @param string $querystring to append to urls
739 function questionbank_navigation_tabs(&$row, $contexts, $querystring) {
740 global $CFG, $QUESTION_EDITTABCAPS;
742 'questions' =>array("$CFG->wwwroot/question/edit.php?$querystring", get_string('questions', 'quiz'), get_string('editquestions', 'quiz')),
743 'categories' =>array("$CFG->wwwroot/question/category.php?$querystring", get_string('categories', 'quiz'), get_string('editqcats', 'quiz')),
744 'import' =>array("$CFG->wwwroot/question/import.php?$querystring", get_string('import', 'quiz'), get_string('importquestions', 'quiz')),
745 'export' =>array("$CFG->wwwroot/question/export.php?$querystring", get_string('export', 'quiz'), get_string('exportquestions', 'quiz')));
746 foreach ($tabs as $tabname => $tabparams){
747 if ($contexts->have_one_edit_tab_cap($tabname)) {
748 $row[] = new tabobject($tabname, $tabparams[0], $tabparams[1], $tabparams[2]);
754 * Private function to factor common code out of get_question_options().
756 * @param object $question the question to tidy.
757 * @return boolean true if successful, else false.
759 function _tidy_question(&$question) {
761 if (!array_key_exists($question->qtype
, $QTYPES)) {
762 $question->qtype
= 'missingtype';
763 $question->questiontext
= '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext
;
765 $question->name_prefix
= question_make_name_prefix($question->id
);
766 return $QTYPES[$question->qtype
]->get_question_options($question);
770 * Updates the question objects with question type specific
771 * information by calling {@link get_question_options()}
773 * Can be called either with an array of question objects or with a single
776 * @param mixed $questions Either an array of question objects to be updated
777 * or just a single question object
778 * @return bool Indicates success or failure.
780 function get_question_options(&$questions) {
781 if (is_array($questions)) { // deal with an array of questions
782 foreach ($questions as $i => $notused) {
783 if (!_tidy_question($questions[$i])) {
788 } else { // deal with single question
789 return _tidy_question($questions);
794 * Loads the most recent state of each question session from the database
797 * For each question the most recent session state for the current attempt
798 * is loaded from the question_states table and the question type specific data and
799 * responses are added by calling {@link restore_question_state()} which in turn
800 * calls {@link restore_session_and_responses()} for each question.
801 * If no states exist for the question instance an empty state object is
802 * created representing the start of a session and empty question
803 * type specific information and responses are created by calling
804 * {@link create_session_and_responses()}.
806 * @return array An array of state objects representing the most recent
807 * states of the question sessions.
808 * @param array $questions The questions for which sessions are to be restored or
810 * @param object $cmoptions
811 * @param object $attempt The attempt for which the question sessions are
812 * to be restored or created.
813 * @param mixed either the id of a previous attempt, if this attmpt is
814 * building on a previous one, or false for a clean attempt.
816 function get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) {
817 global $CFG, $QTYPES;
819 // get the question ids
820 $ids = array_keys($questions);
821 $questionlist = implode(',', $ids);
823 // The question field must be listed first so that it is used as the
824 // array index in the array returned by get_records_sql
825 $statefields = 'n.questionid as question, s.*, n.sumpenalty, n.manualcomment';
826 // Load the newest states for the questions
827 $sql = "SELECT $statefields".
828 " FROM {$CFG->prefix}question_states s,".
829 " {$CFG->prefix}question_sessions n".
830 " WHERE s.id = n.newest".
831 " AND n.attemptid = '$attempt->uniqueid'".
832 " AND n.questionid IN ($questionlist)";
833 $states = get_records_sql($sql);
835 // Load the newest graded states for the questions
836 $sql = "SELECT $statefields".
837 " FROM {$CFG->prefix}question_states s,".
838 " {$CFG->prefix}question_sessions n".
839 " WHERE s.id = n.newgraded".
840 " AND n.attemptid = '$attempt->uniqueid'".
841 " AND n.questionid IN ($questionlist)";
842 $gradedstates = get_records_sql($sql);
844 // loop through all questions and set the last_graded states
845 foreach ($ids as $i) {
846 if (isset($states[$i])) {
847 restore_question_state($questions[$i], $states[$i]);
848 if (isset($gradedstates[$i])) {
849 restore_question_state($questions[$i], $gradedstates[$i]);
850 $states[$i]->last_graded
= $gradedstates[$i];
852 $states[$i]->last_graded
= clone($states[$i]);
855 if ($lastattemptid) {
856 // If the new attempt is to be based on this previous attempt.
857 // Find the responses from the previous attempt and save them to the new session
859 // Load the last graded state for the question
860 $statefields = 'n.questionid as question, s.*, n.sumpenalty';
861 $sql = "SELECT $statefields".
862 " FROM {$CFG->prefix}question_states s,".
863 " {$CFG->prefix}question_sessions n".
864 " WHERE s.id = n.newgraded".
865 " AND n.attemptid = '$lastattemptid'".
866 " AND n.questionid = '$i'";
867 if (!$laststate = get_record_sql($sql)) {
868 // Only restore previous responses that have been graded
871 // Restore the state so that the responses will be restored
872 restore_question_state($questions[$i], $laststate);
873 $states[$i] = clone($laststate);
874 unset($states[$i]->id
);
876 // create a new empty state
877 $states[$i] = new object;
878 $states[$i]->question
= $i;
879 $states[$i]->responses
= array('' => '');
880 $states[$i]->raw_grade
= 0;
883 // now fill/overide initial values
884 $states[$i]->attempt
= $attempt->uniqueid
;
885 $states[$i]->seq_number
= 0;
886 $states[$i]->timestamp
= $attempt->timestart
;
887 $states[$i]->event
= ($attempt->timefinish
) ? QUESTION_EVENTCLOSE
: QUESTION_EVENTOPEN
;
888 $states[$i]->grade
= 0;
889 $states[$i]->penalty
= 0;
890 $states[$i]->sumpenalty
= 0;
891 $states[$i]->manualcomment
= '';
893 // Prevent further changes to the session from incrementing the
895 $states[$i]->changed
= true;
897 if ($lastattemptid) {
898 // prepare the previous responses for new processing
899 $action = new stdClass
;
900 $action->responses
= $laststate->responses
;
901 $action->timestamp
= $laststate->timestamp
;
902 $action->event
= QUESTION_EVENTSAVE
; //emulate save of questions from all pages MDL-7631
904 // Process these responses ...
905 question_process_responses($questions[$i], $states[$i], $action, $cmoptions, $attempt);
907 // Fix for Bug #5506: When each attempt is built on the last one,
908 // preserve the options from any previous attempt.
909 if ( isset($laststate->options
) ) {
910 $states[$i]->options
= $laststate->options
;
913 // Create the empty question type specific information
914 if (!$QTYPES[$questions[$i]->qtype
]->create_session_and_responses(
915 $questions[$i], $states[$i], $cmoptions, $attempt)) {
919 $states[$i]->last_graded
= clone($states[$i]);
927 * Creates the run-time fields for the states
929 * Extends the state objects for a question by calling
930 * {@link restore_session_and_responses()}
931 * @param object $question The question for which the state is needed
932 * @param object $state The state as loaded from the database
933 * @return boolean Represents success or failure
935 function restore_question_state(&$question, &$state) {
938 // initialise response to the value in the answer field
939 $state->responses
= array('' => addslashes($state->answer
));
940 unset($state->answer
);
941 $state->manualcomment
= isset($state->manualcomment
) ?
addslashes($state->manualcomment
) : '';
943 // Set the changed field to false; any code which changes the
944 // question session must set this to true and must increment
945 // ->seq_number. The save_question_session
946 // function will save the new state object to the database if the field is
948 $state->changed
= false;
950 // Load the question type specific data
951 return $QTYPES[$question->qtype
]
952 ->restore_session_and_responses($question, $state);
957 * Saves the current state of the question session to the database
959 * The state object representing the current state of the session for the
960 * question is saved to the question_states table with ->responses[''] saved
961 * to the answer field of the database table. The information in the
962 * question_sessions table is updated.
963 * The question type specific data is then saved.
964 * @return mixed The id of the saved or updated state or false
965 * @param object $question The question for which session is to be saved.
966 * @param object $state The state information to be saved. In particular the
967 * most recent responses are in ->responses. The object
968 * is updated to hold the new ->id.
970 function save_question_session(&$question, &$state) {
972 // Check if the state has changed
973 if (!$state->changed
&& isset($state->id
)) {
976 // Set the legacy answer field
977 $state->answer
= isset($state->responses
['']) ?
$state->responses
[''] : '';
980 if (!empty($state->update
)) { // this forces the old state record to be overwritten
981 update_record('question_states', $state);
983 if (!$state->id
= insert_record('question_states', $state)) {
985 unset($state->answer
);
990 // create or update the session
991 if (!$session = get_record('question_sessions', 'attemptid',
992 $state->attempt
, 'questionid', $question->id
)) {
993 $session->attemptid
= $state->attempt
;
994 $session->questionid
= $question->id
;
995 $session->newest
= $state->id
;
996 // The following may seem weird, but the newgraded field needs to be set
997 // already even if there is no graded state yet.
998 $session->newgraded
= $state->id
;
999 $session->sumpenalty
= $state->sumpenalty
;
1000 $session->manualcomment
= $state->manualcomment
;
1001 if (!insert_record('question_sessions', $session)) {
1002 error('Could not insert entry in question_sessions');
1005 $session->newest
= $state->id
;
1006 if (question_state_is_graded($state) or $state->event
== QUESTION_EVENTOPEN
) {
1007 // this state is graded or newly opened, so it goes into the lastgraded field as well
1008 $session->newgraded
= $state->id
;
1009 $session->sumpenalty
= $state->sumpenalty
;
1010 $session->manualcomment
= $state->manualcomment
;
1012 $session->manualcomment
= addslashes($session->manualcomment
);
1014 update_record('question_sessions', $session);
1017 unset($state->answer
);
1019 // Save the question type specific state information and responses
1020 if (!$QTYPES[$question->qtype
]->save_session_and_responses(
1021 $question, $state)) {
1024 // Reset the changed flag
1025 $state->changed
= false;
1030 * Determines whether a state has been graded by looking at the event field
1032 * @return boolean true if the state has been graded
1033 * @param object $state
1035 function question_state_is_graded($state) {
1036 $gradedevents = explode(',', QUESTION_EVENTS_GRADED
);
1037 return (in_array($state->event
, $gradedevents));
1041 * Determines whether a state has been closed by looking at the event field
1043 * @return boolean true if the state has been closed
1044 * @param object $state
1046 function question_state_is_closed($state) {
1047 return ($state->event
== QUESTION_EVENTCLOSE
1048 or $state->event
== QUESTION_EVENTCLOSEANDGRADE
1049 or $state->event
== QUESTION_EVENTMANUALGRADE
);
1054 * Extracts responses from submitted form
1056 * This can extract the responses given to one or several questions present on a page
1057 * It returns an array with one entry for each question, indexed by question id
1058 * Each entry is an object with the properties
1059 * ->event The event that has triggered the submission. This is determined by which button
1060 * the user has pressed.
1061 * ->responses An array holding the responses to an individual question, indexed by the
1062 * name of the corresponding form element.
1063 * ->timestamp A unix timestamp
1064 * @return array array of action objects, indexed by question ids.
1065 * @param array $questions an array containing at least all questions that are used on the form
1066 * @param array $formdata the data submitted by the form on the question page
1067 * @param integer $defaultevent the event type used if no 'mark' or 'validate' is submitted
1069 function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE
) {
1073 foreach ($formdata as $key => $response) {
1074 // Get the question id from the response name
1075 if (false !== ($quid = question_get_id_from_name_prefix($key))) {
1076 // check if this is a valid id
1077 if (!isset($questions[$quid])) {
1078 error('Form contained question that is not in questionids');
1081 // Remove the name prefix from the name
1083 $key = substr($key, strlen($questions[$quid]->name_prefix
));
1084 if (false === $key) {
1087 // Check for question validate and mark buttons & set events
1088 if ($key === 'validate') {
1089 $actions[$quid]->event
= QUESTION_EVENTVALIDATE
;
1090 } else if ($key === 'submit') {
1091 $actions[$quid]->event
= QUESTION_EVENTSUBMIT
;
1093 $actions[$quid]->event
= $defaultevent;
1096 // Update the state with the new response
1097 $actions[$quid]->responses
[$key] = $response;
1099 // Set the timestamp
1100 $actions[$quid]->timestamp
= $time;
1103 foreach ($actions as $quid => $notused) {
1104 ksort($actions[$quid]->responses
);
1111 * Returns the html for question feedback image.
1112 * @param float $fraction value representing the correctness of the user's
1113 * response to a question.
1114 * @param boolean $selected whether or not the answer is the one that the
1118 function question_get_feedback_image($fraction, $selected=true) {
1122 if ($fraction >= 1.0) {
1124 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_green_big.gif" '.
1125 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
1127 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_green_small.gif" '.
1128 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
1130 } else if ($fraction > 0.0 && $fraction < 1.0) {
1132 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_amber_big.gif" '.
1133 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
1135 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/tick_amber_small.gif" '.
1136 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
1140 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/cross_red_big.gif" '.
1141 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
1143 $feedbackimg = '<img src="'.$CFG->pixpath
.'/i/cross_red_small.gif" '.
1144 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
1147 return $feedbackimg;
1152 * Returns the class name for question feedback.
1153 * @param float $fraction value representing the correctness of the user's
1154 * response to a question.
1157 function question_get_feedback_class($fraction) {
1161 if ($fraction >= 1.0) {
1163 } else if ($fraction > 0.0 && $fraction < 1.0) {
1164 $class = 'partiallycorrect';
1166 $class = 'incorrect';
1173 * For a given question in an attempt we walk the complete history of states
1174 * and recalculate the grades as we go along.
1176 * This is used when a question is changed and old student
1177 * responses need to be marked with the new version of a question.
1179 * TODO: Make sure this is not quiz-specific
1181 * @return boolean Indicates whether the grade has changed
1182 * @param object $question A question object
1183 * @param object $attempt The attempt, in which the question needs to be regraded.
1184 * @param object $cmoptions
1185 * @param boolean $verbose Optional. Whether to print progress information or not.
1187 function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false) {
1189 // load all states for this question in this attempt, ordered in sequence
1190 if ($states = get_records_select('question_states',
1191 "attempt = '{$attempt->uniqueid}' AND question = '{$question->id}'",
1192 'seq_number ASC')) {
1193 $states = array_values($states);
1195 // Subtract the grade for the latest state from $attempt->sumgrades to get the
1196 // sumgrades for the attempt without this question.
1197 $attempt->sumgrades
-= $states[count($states)-1]->grade
;
1199 // Initialise the replaystate
1200 $state = clone($states[0]);
1201 $state->manualcomment
= get_field('question_sessions', 'manualcomment', 'attemptid',
1202 $attempt->uniqueid
, 'questionid', $question->id
);
1203 restore_question_state($question, $state);
1204 $state->sumpenalty
= 0.0;
1205 $replaystate = clone($state);
1206 $replaystate->last_graded
= $state;
1209 for($j = 1; $j < count($states); $j++
) {
1210 restore_question_state($question, $states[$j]);
1211 $action = new stdClass
;
1212 $action->responses
= $states[$j]->responses
;
1213 $action->timestamp
= $states[$j]->timestamp
;
1215 // Change event to submit so that it will be reprocessed
1216 if (QUESTION_EVENTCLOSE
== $states[$j]->event
1217 or QUESTION_EVENTGRADE
== $states[$j]->event
1218 or QUESTION_EVENTCLOSEANDGRADE
== $states[$j]->event
) {
1219 $action->event
= QUESTION_EVENTSUBMIT
;
1221 // By default take the event that was saved in the database
1223 $action->event
= $states[$j]->event
;
1226 if ($action->event
== QUESTION_EVENTMANUALGRADE
) {
1227 // Ensure that the grade is in range - in the past this was not checked,
1228 // but now it is (MDL-14835) - so we need to ensure the data is valid before
1230 if ($states[$j]->grade
< 0) {
1231 $states[$j]->grade
= 0;
1232 } else if ($states[$j]->grade
> $question->maxgrade
) {
1233 $states[$j]->grade
= $question->maxgrade
;
1235 $error = question_process_comment($question, $replaystate, $attempt,
1236 $replaystate->manualcomment
, $states[$j]->grade
);
1237 if (is_string($error)) {
1242 // Reprocess (regrade) responses
1243 if (!question_process_responses($question, $replaystate,
1244 $action, $cmoptions, $attempt)) {
1245 $verbose && notify("Couldn't regrade state #{$state->id}!");
1249 // We need rounding here because grades in the DB get truncated
1250 // e.g. 0.33333 != 0.3333333, but we want them to be equal here
1251 if ((round((float)$replaystate->raw_grade
, 5) != round((float)$states[$j]->raw_grade
, 5))
1252 or (round((float)$replaystate->penalty
, 5) != round((float)$states[$j]->penalty
, 5))
1253 or (round((float)$replaystate->grade
, 5) != round((float)$states[$j]->grade
, 5))) {
1257 $replaystate->id
= $states[$j]->id
;
1258 $replaystate->changed
= true;
1259 $replaystate->update
= true; // This will ensure that the existing database entry is updated rather than a new one created
1260 save_question_session($question, $replaystate);
1263 // TODO, call a method in quiz to do this, where 'quiz' comes from
1264 // the question_attempts table.
1265 update_record('quiz_attempts', $attempt);
1274 * Processes an array of student responses, grading and saving them as appropriate
1276 * @param object $question Full question object, passed by reference
1277 * @param object $state Full state object, passed by reference
1278 * @param object $action object with the fields ->responses which
1279 * is an array holding the student responses,
1280 * ->action which specifies the action, e.g., QUESTION_EVENTGRADE,
1281 * and ->timestamp which is a timestamp from when the responses
1282 * were submitted by the student.
1283 * @param object $cmoptions
1284 * @param object $attempt The attempt is passed by reference so that
1285 * during grading its ->sumgrades field can be updated
1286 * @return boolean Indicates success/failure
1288 function question_process_responses(&$question, &$state, $action, $cmoptions, &$attempt) {
1291 // if no responses are set initialise to empty response
1292 if (!isset($action->responses
)) {
1293 $action->responses
= array('' => '');
1296 // make sure these are gone!
1297 unset($action->responses
['submit'], $action->responses
['validate']);
1299 // Check the question session is still open
1300 if (question_state_is_closed($state)) {
1304 // If $action->event is not set that implies saving
1305 if (! isset($action->event
)) {
1306 debugging('Ambiguous action in question_process_responses.' , DEBUG_DEVELOPER
);
1307 $action->event
= QUESTION_EVENTSAVE
;
1309 // If submitted then compare against last graded
1310 // responses, not last given responses in this case
1311 if (question_isgradingevent($action->event
)) {
1312 $state->responses
= $state->last_graded
->responses
;
1315 // Check for unchanged responses (exactly unchanged, not equivalent).
1316 // We also have to catch questions that the student has not yet attempted
1317 $sameresponses = $QTYPES[$question->qtype
]->compare_responses($question, $action, $state);
1318 if (!empty($state->last_graded
) && $state->last_graded
->event
== QUESTION_EVENTOPEN
&&
1319 question_isgradingevent($action->event
)) {
1320 $sameresponses = false;
1323 // If the response has not been changed then we do not have to process it again
1324 // unless the attempt is closing or validation is requested
1325 if ($sameresponses and QUESTION_EVENTCLOSE
!= $action->event
1326 and QUESTION_EVENTVALIDATE
!= $action->event
) {
1330 // Roll back grading information to last graded state and set the new
1332 $newstate = clone($state->last_graded
);
1333 $newstate->responses
= $action->responses
;
1334 $newstate->seq_number
= $state->seq_number +
1;
1335 $newstate->changed
= true; // will assure that it gets saved to the database
1336 $newstate->last_graded
= clone($state->last_graded
);
1337 $newstate->timestamp
= $action->timestamp
;
1340 // Set the event to the action we will perform. The question type specific
1341 // grading code may override this by setting it to QUESTION_EVENTCLOSE if the
1342 // attempt at the question causes the session to close
1343 $state->event
= $action->event
;
1345 if (!question_isgradingevent($action->event
)) {
1346 // Grade the response but don't update the overall grade
1347 if (!$QTYPES[$question->qtype
]->grade_responses($question, $state, $cmoptions)) {
1351 // Temporary hack because question types are not given enough control over what is going
1352 // on. Used by Opaque questions.
1353 // TODO fix this code properly.
1354 if (!empty($state->believeevent
)) {
1355 // If the state was graded we need to ...
1356 if (question_state_is_graded($state)) {
1357 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1359 // update the attempt grade
1360 $attempt->sumgrades
-= (float)$state->last_graded
->grade
;
1361 $attempt->sumgrades +
= (float)$state->grade
;
1363 // and update the last_graded field.
1364 unset($state->last_graded
);
1365 $state->last_graded
= clone($state);
1366 unset($state->last_graded
->changed
);
1369 // Don't allow the processing to change the event type
1370 $state->event
= $action->event
;
1373 } else { // grading event
1375 // Unless the attempt is closing, we want to work out if the current responses
1376 // (or equivalent responses) were already given in the last graded attempt.
1377 if(QUESTION_EVENTCLOSE
!= $action->event
&& QUESTION_EVENTOPEN
!= $state->last_graded
->event
&&
1378 $QTYPES[$question->qtype
]->compare_responses($question, $state, $state->last_graded
)) {
1379 $state->event
= QUESTION_EVENTDUPLICATE
;
1382 // If we did not find a duplicate or if the attempt is closing, perform grading
1383 if ((!$sameresponses and QUESTION_EVENTDUPLICATE
!= $state->event
) or
1384 QUESTION_EVENTCLOSE
== $action->event
) {
1385 if (!$QTYPES[$question->qtype
]->grade_responses($question, $state, $cmoptions)) {
1389 // Calculate overall grade using correct penalty method
1390 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1393 // If the state was graded we need to ...
1394 if (question_state_is_graded($state)) {
1395 // update the attempt grade
1396 $attempt->sumgrades
-= (float)$state->last_graded
->grade
;
1397 $attempt->sumgrades +
= (float)$state->grade
;
1399 // and update the last_graded field.
1400 unset($state->last_graded
);
1401 $state->last_graded
= clone($state);
1402 unset($state->last_graded
->changed
);
1405 $attempt->timemodified
= $action->timestamp
;
1411 * Determine if event requires grading
1413 function question_isgradingevent($event) {
1414 return (QUESTION_EVENTSUBMIT
== $event || QUESTION_EVENTCLOSE
== $event);
1418 * Applies the penalty from the previous graded responses to the raw grade
1419 * for the current responses
1421 * The grade for the question in the current state is computed by subtracting the
1422 * penalty accumulated over the previous graded responses at the question from the
1423 * raw grade. If the timestamp is more than 1 minute beyond the end of the attempt
1424 * the grade is set to zero. The ->grade field of the state object is modified to
1425 * reflect the new grade but is never allowed to decrease.
1426 * @param object $question The question for which the penalty is to be applied.
1427 * @param object $state The state for which the grade is to be set from the
1428 * raw grade and the cumulative penalty from the last
1429 * graded state. The ->grade field is updated by applying
1430 * the penalty scheme determined in $cmoptions to the ->raw_grade and
1431 * ->last_graded->penalty fields.
1432 * @param object $cmoptions The options set by the course module.
1433 * The ->penaltyscheme field determines whether penalties
1434 * for incorrect earlier responses are subtracted.
1436 function question_apply_penalty_and_timelimit(&$question, &$state, $attempt, $cmoptions) {
1437 // TODO. Quiz dependancy. The fact that the attempt that is passed in here
1438 // is from quiz_attempts, and we use things like $cmoptions->timelimit.
1440 // deal with penalty
1441 if ($cmoptions->penaltyscheme
) {
1442 $state->grade
= $state->raw_grade
- $state->sumpenalty
;
1443 $state->sumpenalty +
= (float) $state->penalty
;
1445 $state->grade
= $state->raw_grade
;
1448 // deal with timelimit
1449 if ($cmoptions->timelimit
) {
1450 // We allow for 5% uncertainty in the following test
1451 if ($state->timestamp
- $attempt->timestart
> $cmoptions->timelimit
* 63) {
1452 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id
);
1453 if (!has_capability('mod/quiz:ignoretimelimits', get_context_instance(CONTEXT_MODULE
, $cm->id
),
1454 $attempt->userid
, false)) {
1460 // deal with closing time
1461 if ($cmoptions->timeclose
and $state->timestamp
> ($cmoptions->timeclose +
60) // allowing 1 minute lateness
1462 and !$attempt->preview
) { // ignore closing time for previews
1466 // Ensure that the grade does not go down
1467 $state->grade
= max($state->grade
, $state->last_graded
->grade
);
1471 * Print the icon for the question type
1473 * @param object $question The question object for which the icon is required
1474 * @param boolean $return If true the functions returns the link as a string
1476 function print_question_icon($question, $return = false) {
1477 global $QTYPES, $CFG;
1479 if (array_key_exists($question->qtype
, $QTYPES)) {
1480 $namestr = $QTYPES[$question->qtype
]->menu_name();
1482 $namestr = 'missingtype';
1484 $html = '<img src="' . $CFG->wwwroot
. '/question/type/' .
1485 $question->qtype
. '/icon.gif" alt="' .
1486 $namestr . '" title="' . $namestr . '" />';
1495 * Returns a html link to the question image if there is one
1497 * @return string The html image tag or the empy string if there is no image.
1498 * @param object $question The question object
1500 function get_question_image($question) {
1505 if (!$category = get_record('question_categories', 'id', $question->category
)){
1506 error('invalid category id '.$question->category
);
1508 $coursefilesdir = get_filesdir_from_context(get_context_instance_by_id($category->contextid
));
1510 if ($question->image
) {
1512 if (substr(strtolower($question->image
), 0, 7) == 'http://') {
1513 $img .= $question->image
;
1516 require_once($CFG->libdir
.'/filelib.php');
1517 $img = get_file_url("$coursefilesdir/{$question->image}");
1523 function question_print_comment_box($question, $state, $attempt, $url) {
1524 global $CFG, $QTYPES;
1526 $prefix = 'response';
1527 $usehtmleditor = can_use_richtext_editor();
1528 if (!question_state_is_graded($state) && $QTYPES[$question->qtype
]->is_question_manual_graded($question, $attempt->layout
)) {
1531 $grade = round($state->last_graded
->grade
, 3);
1533 echo '<form method="post" action="'.$url.'">';
1534 include($CFG->dirroot
.'/question/comment.html');
1535 echo '<input type="hidden" name="attempt" value="'.$attempt->uniqueid
.'" />';
1536 echo '<input type="hidden" name="question" value="'.$question->id
.'" />';
1537 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1538 echo '<input type="submit" name="submit" value="'.get_string('save', 'quiz').'" />';
1541 if ($usehtmleditor) {
1547 * Process a manual grading action. That is, use $comment and $grade to update
1548 * $state and $attempt. The attempt and the comment text are stored in the
1549 * database. $state is only updated in memory, it is up to the call to store
1550 * that, if appropriate.
1552 * @param object $question the question
1553 * @param object $state the state to be updated.
1554 * @param object $attempt the attempt the state belongs to, to be updated.
1555 * @param string $comment the new comment from the teacher.
1556 * @param mixed $grade the grade the teacher assigned, or '' to not change the grade.
1557 * @return mixed true on success, a string error message if a problem is detected
1558 * (for example score out of range).
1560 function question_process_comment($question, &$state, &$attempt, $comment, $grade) {
1561 $grade = trim($grade);
1562 if ($grade < 0 ||
$grade > $question->maxgrade
) {
1565 $a->maxgrade
= $question->maxgrade
;
1566 $a->name
= $question->name
;
1567 return get_string('errormanualgradeoutofrange', 'question', $a);
1570 // Update the comment and save it in the database
1571 $comment = trim($comment);
1572 $state->manualcomment
= $comment;
1573 if (!set_field('question_sessions', 'manualcomment', $comment, 'attemptid', $attempt->uniqueid
, 'questionid', $question->id
)) {
1574 return get_string('errorsavingcomment', 'question', $question);
1577 // Update the attempt if the score has changed.
1578 if ($grade !== '' && (abs($state->last_graded
->grade
- $grade) > 0.002 ||
$state->last_graded
->event
!= QUESTION_EVENTMANUALGRADE
)) {
1579 $attempt->sumgrades
= $attempt->sumgrades
- $state->last_graded
->grade +
$grade;
1580 $attempt->timemodified
= time();
1581 if (!update_record('quiz_attempts', $attempt)) {
1582 return get_string('errorupdatingattempt', 'question', $attempt);
1585 // We want to update existing state (rather than creating new one) if it
1586 // was itself created by a manual grading event.
1587 $state->update
= $state->event
== QUESTION_EVENTMANUALGRADE
;
1589 // Update the other parts of the state object.
1590 $state->raw_grade
= $grade;
1591 $state->grade
= $grade;
1592 $state->penalty
= 0;
1593 $state->timestamp
= time();
1594 $state->seq_number++
;
1595 $state->event
= QUESTION_EVENTMANUALGRADE
;
1597 // Update the last graded state (don't simplify!)
1598 unset($state->last_graded
);
1599 $state->last_graded
= clone($state);
1601 // We need to indicate that the state has changed in order for it to be saved.
1602 $state->changed
= 1;
1609 * Construct name prefixes for question form element names
1611 * Construct the name prefix that should be used for example in the
1612 * names of form elements created by questions.
1613 * This is called by {@link get_question_options()}
1614 * to set $question->name_prefix.
1615 * This name prefix includes the question id which can be
1616 * extracted from it with {@link question_get_id_from_name_prefix()}.
1619 * @param integer $id The question id
1621 function question_make_name_prefix($id) {
1622 return 'resp' . $id . '_';
1626 * Extract question id from the prefix of form element names
1628 * @return integer The question id
1629 * @param string $name The name that contains a prefix that was
1630 * constructed with {@link question_make_name_prefix()}
1632 function question_get_id_from_name_prefix($name) {
1633 if (!preg_match('/^resp([0-9]+)_/', $name, $matches))
1635 return (integer) $matches[1];
1639 * Returns the unique id for a new attempt
1641 * Every module can keep their own attempts table with their own sequential ids but
1642 * the question code needs to also have a unique id by which to identify all these
1643 * attempts. Hence a module, when creating a new attempt, calls this function and
1644 * stores the return value in the 'uniqueid' field of its attempts table.
1646 function question_new_attempt_uniqueid($modulename='quiz') {
1648 $attempt = new stdClass
;
1649 $attempt->modulename
= $modulename;
1650 if (!$id = insert_record('question_attempts', $attempt)) {
1651 error('Could not create new entry in question_attempts table');
1657 * Creates a stamp that uniquely identifies this version of the question
1659 * In future we want this to use a hash of the question data to guarantee that
1660 * identical versions have the same version stamp.
1662 * @param object $question
1663 * @return string A unique version stamp
1665 function question_hash($question) {
1666 return make_unique_id_code();
1670 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
1672 * Get the HTML that needs to be included in the head tag when the
1673 * questions in $questionlist are printed in the gives states.
1675 * @param array $questionlist a list of questionids of the questions what will appear on this page.
1676 * @param array $questions an array of question objects, whose keys are question ids.
1677 * Must contain all the questions in $questionlist
1678 * @param array $states an array of question state objects, whose keys are question ids.
1679 * Must contain the state of all the questions in $questionlist
1681 * @return string some HTML code that can go inside the head tag.
1683 function get_html_head_contributions(&$questionlist, &$questions, &$states) {
1686 $contributions = array();
1687 foreach ($questionlist as $questionid) {
1688 $question = $questions[$questionid];
1689 $contributions = array_merge($contributions,
1690 $QTYPES[$question->qtype
]->get_html_head_contributions(
1691 $question, $states[$questionid]));
1693 return implode("\n", array_unique($contributions));
1697 * Like @see{get_html_head_contributions} but for the editing page
1698 * question/question.php.
1700 * @param $question A question object. Only $question->qtype is used.
1701 * @return string some HTML code that can go inside the head tag.
1703 function get_editing_head_contributions($question) {
1705 $contributions = $QTYPES[$question->qtype
]->get_editing_head_contributions();
1706 return implode("\n", array_unique($contributions));
1712 * Simply calls the question type specific print_question() method.
1713 * @param object $question The question to be rendered.
1714 * @param object $state The state to render the question in.
1715 * @param integer $number The number for this question.
1716 * @param object $cmoptions The options specified by the course module
1717 * @param object $options An object specifying the rendering options.
1719 function print_question(&$question, &$state, $number, $cmoptions, $options=null) {
1721 $QTYPES[$question->qtype
]->print_question($question, $state, $number, $cmoptions, $options);
1724 * Saves question options
1726 * Simply calls the question type specific save_question_options() method.
1728 function save_question_options($question) {
1731 $QTYPES[$question->qtype
]->save_question_options($question);
1735 * Gets all teacher stored answers for a given question
1737 * Simply calls the question type specific get_all_responses() method.
1740 function get_question_responses($question, $state) {
1742 $r = $QTYPES[$question->qtype
]->get_all_responses($question, $state);
1748 * Gets the response given by the user in a particular state
1750 * Simply calls the question type specific get_actual_response() method.
1753 function get_question_actual_response($question, $state) {
1756 $r = $QTYPES[$question->qtype
]->get_actual_response($question, $state);
1761 * TODO: document this
1764 function get_question_fraction_grade($question, $state) {
1767 $r = $QTYPES[$question->qtype
]->get_fractional_grade($question, $state);
1772 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1775 * returns the categories with their names ordered following parent-child relationships
1776 * finally it tries to return pending categories (those being orphaned, whose parent is
1777 * incorrect) to avoid missing any category from original array.
1779 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1780 $children = array();
1781 $keys = array_keys($categories);
1783 foreach ($keys as $key) {
1784 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
1785 $children[$key] = $categories[$key];
1786 $categories[$key]->processed
= true;
1787 $children = $children +
sort_categories_by_tree($categories, $children[$key]->id
, $level+
1);
1790 //If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too
1792 foreach ($keys as $key) {
1793 //If not processed and it's a good candidate to start (because its parent doesn't exist in the course)
1794 if (!isset($categories[$key]->processed
) && !record_exists('question_categories', 'course', $categories[$key]->course
, 'id', $categories[$key]->parent
)) {
1795 $children[$key] = $categories[$key];
1796 $categories[$key]->processed
= true;
1797 $children = $children +
sort_categories_by_tree($categories, $children[$key]->id
, $level+
1);
1805 * Private method, only for the use of add_indented_names().
1807 * Recursively adds an indentedname field to each category, starting with the category
1808 * with id $id, and dealing with that category and all its children, and
1809 * return a new array, with those categories in the right order.
1811 * @param array $categories an array of categories which has had childids
1812 * fields added by flatten_category_tree(). Passed by reference for
1813 * performance only. It is not modfied.
1814 * @param int $id the category to start the indenting process from.
1815 * @param int $depth the indent depth. Used in recursive calls.
1816 * @return array a new array of categories, in the right order for the tree.
1818 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1820 // Indent the name of this category.
1821 $newcategories = array();
1822 $newcategories[$id] = $categories[$id];
1823 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) . $categories[$id]->name
;
1825 // Recursively indent the children.
1826 foreach ($categories[$id]->childids
as $childid) {
1827 if ($childid != $nochildrenof){
1828 $newcategories = $newcategories +
flatten_category_tree($categories, $childid, $depth +
1, $nochildrenof);
1832 // Remove the childids array that were temporarily added.
1833 unset($newcategories[$id]->childids
);
1835 return $newcategories;
1839 * Format categories into an indented list reflecting the tree structure.
1841 * @param array $categories An array of category objects, for example from the.
1842 * @return array The formatted list of categories.
1844 function add_indented_names($categories, $nochildrenof = -1) {
1846 // Add an array to each category to hold the child category ids. This array will be removed
1847 // again by flatten_category_tree(). It should not be used outside these two functions.
1848 foreach (array_keys($categories) as $id) {
1849 $categories[$id]->childids
= array();
1852 // Build the tree structure, and record which categories are top-level.
1853 // We have to be careful, because the categories array may include published
1854 // categories from other courses, but not their parents.
1855 $toplevelcategoryids = array();
1856 foreach (array_keys($categories) as $id) {
1857 if (!empty($categories[$id]->parent
) && array_key_exists($categories[$id]->parent
, $categories)) {
1858 $categories[$categories[$id]->parent
]->childids
[] = $id;
1860 $toplevelcategoryids[] = $id;
1864 // Flatten the tree to and add the indents.
1865 $newcategories = array();
1866 foreach ($toplevelcategoryids as $id) {
1867 $newcategories = $newcategories +
flatten_category_tree($categories, $id, 0, $nochildrenof);
1870 return $newcategories;
1874 * Output a select menu of question categories.
1876 * Categories from this course and (optionally) published categories from other courses
1877 * are included. Optionally, only categories the current user may edit can be included.
1879 * @param integer $courseid the id of the course to get the categories for.
1880 * @param integer $published if true, include publised categories from other courses.
1881 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1882 * @param integer $selected optionally, the id of a category to be selected by default in the dropdown.
1884 function question_category_select_menu($contexts, $top = false, $currentcat = 0, $selected = "", $nochildrenof = -1) {
1885 $categoriesarray = question_category_options($contexts, $top, $currentcat, false, $nochildrenof);
1889 $nothing = 'choose';
1891 choose_from_menu_nested($categoriesarray, 'category', $selected, $nothing);
1895 * Gets the default category in the most specific context.
1896 * If no categories exist yet then default ones are created in all contexts.
1898 * @param array $contexts The context objects for this context and all parent contexts.
1899 * @return object The default category - the category in the course context
1901 function question_make_default_categories($contexts) {
1902 static $preferredlevels = array(
1903 CONTEXT_COURSE
=> 4,
1904 CONTEXT_MODULE
=> 3,
1905 CONTEXT_COURSECAT
=> 2,
1906 CONTEXT_SYSTEM
=> 1,
1910 // If it already exists, just return it.
1911 foreach ($contexts as $key => $context) {
1912 if (!$categoryrs = get_recordset_select("question_categories", "contextid = '{$context->id}'", 'sortorder, name', '*', '', 1)) {
1913 error('error getting category record');
1915 if (!$category = rs_fetch_record($categoryrs)){
1916 // Otherwise, we need to make one
1917 $category = new stdClass
;
1918 $contextname = print_context_name($context, false, true);
1919 $category->name
= addslashes(get_string('defaultfor', 'question', $contextname));
1920 $category->info
= addslashes(get_string('defaultinfofor', 'question', $contextname));
1921 $category->contextid
= $context->id
;
1922 $category->parent
= 0;
1923 $category->sortorder
= 999; // By default, all categories get this number, and are sorted alphabetically.
1924 $category->stamp
= make_unique_id_code();
1925 if (!$category->id
= insert_record('question_categories', $category)) {
1926 error('Error creating a default category for context '.print_context_name($context));
1930 if ($preferredlevels[$context->contextlevel
] > $preferredness &&
1931 has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1932 $toreturn = $category;
1933 $preferredness = $preferredlevels[$context->contextlevel
];
1937 if (!is_null($toreturn)) {
1938 $toreturn = clone($toreturn);
1944 * Get all the category objects, including a count of the number of questions in that category,
1945 * for all the categories in the lists $contexts.
1947 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1948 * @param string $sortorder used as the ORDER BY clause in the select statement.
1949 * @return array of category objects.
1951 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1953 return get_records_sql("
1954 SELECT c.*, (SELECT count(1) FROM {$CFG->prefix}question q
1955 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') as questioncount
1956 FROM {$CFG->prefix}question_categories c
1957 WHERE c.contextid IN ($contexts)
1958 ORDER BY $sortorder");
1962 * Output an array of question categories.
1964 function question_category_options($contexts, $top = false, $currentcat = 0, $popupform = false, $nochildrenof = -1) {
1966 $pcontexts = array();
1967 foreach($contexts as $context){
1968 $pcontexts[] = $context->id
;
1970 $contextslist = join($pcontexts, ', ');
1972 $categories = get_categories_for_contexts($contextslist);
1974 $categories = question_add_context_in_key($categories);
1977 $categories = question_add_tops($categories, $pcontexts);
1979 $categories = add_indented_names($categories, $nochildrenof);
1981 //sort cats out into different contexts
1982 $categoriesarray = array();
1983 foreach ($pcontexts as $pcontext){
1984 $contextstring = print_context_name(get_context_instance_by_id($pcontext), true, true);
1985 foreach ($categories as $category) {
1986 if ($category->contextid
== $pcontext){
1987 $cid = $category->id
;
1988 if ($currentcat!= $cid ||
$currentcat==0) {
1989 $countstring = (!empty($category->questioncount
))?
" ($category->questioncount)":'';
1990 $categoriesarray[$contextstring][$cid] = $category->indentedname
.$countstring;
1996 $popupcats = array();
1997 foreach ($categoriesarray as $contextstring => $optgroup){
1998 $popupcats[] = '--'.$contextstring;
1999 $popupcats = array_merge($popupcats, $optgroup);
2000 $popupcats[] = '--';
2004 return $categoriesarray;
2008 function question_add_context_in_key($categories){
2009 $newcatarray = array();
2010 foreach ($categories as $id => $category) {
2011 $category->parent
= "$category->parent,$category->contextid";
2012 $category->id
= "$category->id,$category->contextid";
2013 $newcatarray["$id,$category->contextid"] = $category;
2015 return $newcatarray;
2017 function question_add_tops($categories, $pcontexts){
2019 foreach ($pcontexts as $context){
2020 $newcat = new object();
2021 $newcat->id
= "0,$context";
2022 $newcat->name
= get_string('top');
2023 $newcat->parent
= -1;
2024 $newcat->contextid
= $context;
2025 $topcats["0,$context"] = $newcat;
2027 //put topcats in at beginning of array - they'll be sorted into different contexts later.
2028 return array_merge($topcats, $categories);
2032 * Returns a comma separated list of ids of the category and all subcategories
2034 function question_categorylist($categoryid) {
2035 // returns a comma separated list of ids of the category and all subcategories
2036 $categorylist = $categoryid;
2037 if ($subcategories = get_records('question_categories', 'parent', $categoryid, 'sortorder ASC', 'id, 1 AS notused')) {
2038 foreach ($subcategories as $subcategory) {
2039 $categorylist .= ','. question_categorylist($subcategory->id
);
2042 return $categorylist;
2048 //===========================
2049 // Import/Export Functions
2050 //===========================
2053 * Get list of available import or export formats
2054 * @param string $type 'import' if import list, otherwise export list assumed
2055 * @return array sorted list of import/export formats available
2057 function get_import_export_formats( $type ) {
2060 $fileformats = get_list_of_plugins("question/format");
2062 $fileformatname=array();
2063 require_once( "{$CFG->dirroot}/question/format.php" );
2064 foreach ($fileformats as $key => $fileformat) {
2065 $format_file = $CFG->dirroot
. "/question/format/$fileformat/format.php";
2066 if (file_exists( $format_file ) ) {
2067 require_once( $format_file );
2072 $classname = "qformat_$fileformat";
2073 $format_class = new $classname();
2074 if ($type=='import') {
2075 $provided = $format_class->provide_import();
2078 $provided = $format_class->provide_export();
2081 $formatname = get_string($fileformat, 'quiz');
2082 if ($formatname == "[[$fileformat]]") {
2083 $formatname = get_string($fileformat, 'qformat_'.$fileformat);
2084 if ($formatname == "[[$fileformat]]") {
2085 $formatname = $fileformat; // Just use the raw folder name
2088 $fileformatnames[$fileformat] = $formatname;
2091 natcasesort($fileformatnames);
2093 return $fileformatnames;
2098 * Create default export filename
2100 * @return string default export filename
2101 * @param object $course
2102 * @param object $category
2104 function default_export_filename($course,$category) {
2105 //Take off some characters in the filename !!
2106 $takeoff = array(" ", ":", "/", "\\", "|");
2107 $export_word = str_replace($takeoff,"_",moodle_strtolower(get_string("exportfilename","quiz")));
2108 //If non-translated, use "export"
2109 if (substr($export_word,0,1) == "[") {
2110 $export_word= "export";
2113 //Calculate the date format string
2114 $export_date_format = str_replace(" ","_",get_string("exportnameformat","quiz"));
2115 //If non-translated, use "%Y%m%d-%H%M"
2116 if (substr($export_date_format,0,1) == "[") {
2117 $export_date_format = "%%Y%%m%%d-%%H%%M";
2120 //Calculate the shortname
2121 $export_shortname = clean_filename($course->shortname
);
2122 if (empty($export_shortname) or $export_shortname == '_' ) {
2123 $export_shortname = $course->id
;
2126 //Calculate the category name
2127 $export_categoryname = clean_filename($category->name
);
2129 //Calculate the final export filename
2131 $export_name = $export_word."-";
2133 $export_name .= moodle_strtolower($export_shortname)."-";
2135 $export_name .= moodle_strtolower($export_categoryname)."-";
2137 $export_name .= userdate(time(),$export_date_format,99,false);
2138 //Extension is supplied by format later.
2140 return $export_name;
2142 class context_to_string_translator
{
2144 * @var array used to translate between contextids and strings for this context.
2146 var $contexttostringarray = array();
2148 function context_to_string_translator($contexts){
2149 $this->generate_context_to_string_array($contexts);
2152 function context_to_string($contextid){
2153 return $this->contexttostringarray
[$contextid];
2156 function string_to_context($contextname){
2157 $contextid = array_search($contextname, $this->contexttostringarray
);
2161 function generate_context_to_string_array($contexts){
2162 if (!$this->contexttostringarray
){
2164 foreach ($contexts as $context){
2165 switch ($context->contextlevel
){
2166 case CONTEXT_MODULE
:
2167 $contextstring = 'module';
2169 case CONTEXT_COURSE
:
2170 $contextstring = 'course';
2172 case CONTEXT_COURSECAT
:
2173 $contextstring = "cat$catno";
2176 case CONTEXT_SYSTEM
:
2177 $contextstring = 'system';
2180 $this->contexttostringarray
[$context->id
] = $contextstring;
2188 * Check capability on category
2189 * @param mixed $question object or id
2190 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
2191 * @param integer $cachecat useful to cache all question records in a category
2192 * @return boolean this user has the capability $cap for this question $question?
2194 function question_has_capability_on($question, $cap, $cachecat = -1){
2196 // nicolasconnault@gmail.com In some cases I get $question === false. Since no such object exists, it can't be deleted, we can safely return true
2197 if ($question === false) {
2201 // these are capabilities on existing questions capabilties are
2202 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
2203 $question_questioncaps = array('edit', 'view', 'use', 'move');
2204 static $questions = array();
2205 static $categories = array();
2206 static $cachedcat = array();
2207 if ($cachecat != -1 && (array_search($cachecat, $cachedcat)===FALSE)){
2208 $questions +
= get_records('question', 'category', $cachecat);
2209 $cachedcat[] = $cachecat;
2211 if (!is_object($question)){
2212 if (!isset($questions[$question])){
2213 if (!$questions[$question] = get_record('question', 'id', $question)){
2214 print_error('questiondoesnotexist', 'question');
2217 $question = $questions[$question];
2219 if (!isset($categories[$question->category
])){
2220 if (!$categories[$question->category
] = get_record('question_categories', 'id', $question->category
)){
2221 print_error('invalidcategory', 'quiz');
2224 $category = $categories[$question->category
];
2226 if (array_search($cap, $question_questioncaps)!== FALSE){
2227 if (!has_capability('moodle/question:'.$cap.'all', get_context_instance_by_id($category->contextid
))){
2228 if ($question->createdby
== $USER->id
){
2229 return has_capability('moodle/question:'.$cap.'mine', get_context_instance_by_id($category->contextid
));
2237 return has_capability('moodle/question:'.$cap, get_context_instance_by_id($category->contextid
));
2243 * Require capability on question.
2245 function question_require_capability_on($question, $cap){
2246 if (!question_has_capability_on($question, $cap)){
2247 print_error('nopermissions', '', '', $cap);
2252 function question_file_links_base_url($courseid){
2254 $baseurl = preg_quote("$CFG->wwwroot/file.php", '!');
2255 $baseurl .= '('.preg_quote('?file=', '!').')?';//may or may not
2256 //be using slasharguments, accept either
2257 $baseurl .= "/$courseid/";//course directory
2262 * Find all course / site files linked to in a piece of html.
2263 * @param string html the html to search
2264 * @param int course search for files for courseid course or set to siteid for
2265 * finding site files.
2266 * @return array files with keys being files.
2268 function question_find_file_links_from_html($html, $courseid){
2270 $baseurl = question_file_links_base_url($courseid);
2272 '(<\s*(a|img)\s[^>]*(href|src)\s*=\s*")'.$baseurl.'([^"]*)"'.
2274 '(<\s*(a|img)\s[^>]*(href|src)\s*=\s*\')'.$baseurl.'([^\']*)\''.
2277 $no = preg_match_all($searchfor, $html, $matches);
2279 $rawurls = array_filter(array_merge($matches[5], $matches[10]));//array_filter removes empty elements
2280 //remove any links that point somewhere they shouldn't
2281 foreach (array_keys($rawurls) as $rawurlkey){
2282 if (!$cleanedurl = question_url_check($rawurls[$rawurlkey])){
2283 unset($rawurls[$rawurlkey]);
2285 $rawurls[$rawurlkey] = $cleanedurl;
2289 $urls = array_flip($rawurls);// array_flip removes duplicate files
2290 // and when we merge arrays will continue to automatically remove duplicates
2297 * Check that url doesn't point anywhere it shouldn't
2299 * @param $url string relative url within course files directory
2300 * @return mixed boolean false if not OK or cleaned URL as string if OK
2302 function question_url_check($url){
2304 if ((substr(strtolower($url), 0, strlen($CFG->moddata
)) == strtolower($CFG->moddata
)) ||
2305 (substr(strtolower($url), 0, 10) == 'backupdata')){
2308 return clean_param($url, PARAM_PATH
);
2313 * Find all course / site files linked to in a piece of html.
2314 * @param string html the html to search
2315 * @param int course search for files for courseid course or set to siteid for
2316 * finding site files.
2317 * @return array files with keys being files.
2319 function question_replace_file_links_in_html($html, $fromcourseid, $tocourseid, $url, $destination, &$changed){
2321 require_once($CFG->libdir
.'/filelib.php');
2322 $tourl = get_file_url("$tocourseid/$destination");
2323 $fromurl = question_file_links_base_url($fromcourseid).preg_quote($url, '!');
2324 $searchfor = array('!(<\s*(a|img)\s[^>]*(href|src)\s*=\s*")'.$fromurl.'(")!i',
2325 '!(<\s*(a|img)\s[^>]*(href|src)\s*=\s*\')'.$fromurl.'(\')!i');
2326 $newhtml = preg_replace($searchfor, '\\1'.$tourl.'\\5', $html);
2327 if ($newhtml != $html){
2333 function get_filesdir_from_context($context){
2334 switch ($context->contextlevel
){
2335 case CONTEXT_COURSE
:
2336 $courseid = $context->instanceid
;
2338 case CONTEXT_MODULE
:
2339 $courseid = get_field('course_modules', 'course', 'id', $context->instanceid
);
2341 case CONTEXT_COURSECAT
:
2342 case CONTEXT_SYSTEM
:
2346 error('Unsupported contextlevel in category record!');